@dim24/servin 0.2.1 → 1.0.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/src/tree.js CHANGED
@@ -202,7 +202,6 @@ function classifySegment(seg, customTypes = {}, paramRule = null) {
202
202
  }
203
203
  return { type: 'static', priority: 0, value: seg, parse: null, raw: seg };
204
204
  }
205
-
206
205
  export function compileDomainTree(apiRoot = {}, customTypes = {}, staticConfig = null) {
207
206
  const routes = [];
208
207
  let nodeCounter = 0;
@@ -283,6 +282,27 @@ export function compileDomainTree(apiRoot = {}, customTypes = {}, staticConfig =
283
282
  for (const [key, value] of Object.entries(node)) {
284
283
  if (META_KEYS.has(key)) continue;
285
284
 
285
+ if (key === 'ws' && value && typeof value === 'object') {
286
+ const paramNames = segments.filter((s) => s.type !== 'static').map((s) => s.param);
287
+ const wsMeta = { ...meta, wsConfig: value };
288
+ routes.push({
289
+ nodeId: `${nodeId}_ws`,
290
+ dotPath: [...dotPath, key].join('.'),
291
+ segments,
292
+ paramNames,
293
+ verbs: ['WS'],
294
+ handler: typeof value.handler === 'function' ? value.handler : null,
295
+ isAsyncGen: false,
296
+ guards,
297
+ meta: wsMeta,
298
+ nodeCache: null,
299
+ ancestorCaches,
300
+ nodeInFlight: null,
301
+ nodeIdempotency: null
302
+ });
303
+ continue;
304
+ }
305
+
286
306
  const verbs = parseVerbKey(key);
287
307
  if (verbs && value instanceof RedirectDescriptor) {
288
308
  registerRedirectDescriptor(value, segments, [...dotPath, key], guards, meta, verbs);
@@ -498,6 +518,363 @@ export function matchDomainRoute(routes, method, pathname) {
498
518
  return { status: 404 };
499
519
  }
500
520
 
521
+ // export function generateVirtualClientModule(routes) {
522
+ // const manifest = routes
523
+ // .filter((r) => !r.staticDescriptor && !r.redirectDescriptor)
524
+ // .map((r) => ({
525
+ // dotPath: r.dotPath,
526
+ // verbs: r.verbs,
527
+ // isAsyncGen: r.isAsyncGen
528
+ // }));
529
+
530
+ // return `// Auto-generated Zero-Build Virtual ESM Client by servin
531
+ // const MANIFEST = ${JSON.stringify(manifest, null, 2)};
532
+ // const ORIGIN = new URL(import.meta.url).origin;
533
+ // const HTTP_VERBS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);
534
+
535
+ // function parseMethod(key) {
536
+ // if (key === 'ws') return 'WS';
537
+ // const upper = key.split('|')[0].toUpperCase();
538
+ // return HTTP_VERBS.has(upper) ? upper : null;
539
+ // }
540
+
541
+ // function isOptionsBag(arg) {
542
+ // return Boolean(
543
+ // arg &&
544
+ // typeof arg === 'object' &&
545
+ // !Array.isArray(arg) &&
546
+ // !(arg instanceof FormData) &&
547
+ // !(arg instanceof URLSearchParams) &&
548
+ // !(arg instanceof Blob) &&
549
+ // Object.prototype.hasOwnProperty.call(arg, 'headers')
550
+ // );
551
+ // }
552
+
553
+ // function createNode(chain) {
554
+ // return new Proxy(function () {}, {
555
+ // get(_, prop) {
556
+ // if (typeof prop === 'symbol') return undefined;
557
+ // return createNode([...chain, prop]);
558
+ // },
559
+ // apply(_, __, args) {
560
+ // const argQueue = [...args];
561
+ // const dotKey = chain.join('.');
562
+ // const entry = MANIFEST.find((m) => m.dotPath === dotKey);
563
+ // const lastKey = chain[chain.length - 1];
564
+ // let method = parseMethod(lastKey);
565
+ // const pathSegments = method ? chain.slice(0, -1) : [...chain];
566
+
567
+ // if (!method) {
568
+ // method = entry?.verbs?.[0] || 'POST';
569
+ // }
570
+
571
+ // const resolvedParts = [];
572
+ // for (const seg of pathSegments) {
573
+ // if (seg.startsWith('$')) {
574
+ // const val = argQueue.shift();
575
+ // resolvedParts.push(encodeURIComponent(String(val ?? '')));
576
+ // } else {
577
+ // resolvedParts.push(encodeURIComponent(seg));
578
+ // }
579
+ // }
580
+
581
+ // const pathname = '/' + resolvedParts.join('/');
582
+
583
+ // if (method === 'WS') {
584
+ // const wsOrigin = ORIGIN.replace(/^http/, 'ws');
585
+ // const firstArg = argQueue.shift();
586
+ // let connData = (firstArg && typeof firstArg === 'object' && !Array.isArray(firstArg))
587
+ // ? { ...firstArg }
588
+ // : {};
589
+
590
+ // let socket = null;
591
+ // let manualClose = false;
592
+ // let hasConnectedOnce = false;
593
+ // let lastSeq = 0;
594
+ // let currentState = null;
595
+
596
+ // const queue = [];
597
+ // let notify = null;
598
+ // let closed = false;
599
+
600
+ // const listeners = {
601
+ // open: new Set(),
602
+ // close: new Set(),
603
+ // error: new Set(),
604
+ // event: new Set(),
605
+ // broadcast: new Set()
606
+ // };
607
+ // const syncCallbacks = new Set();
608
+
609
+ // const emitLocal = (type, detail) => {
610
+ // const set = listeners[type];
611
+ // if (!set) return;
612
+ // for (const fn of set) fn(detail);
613
+ // };
614
+
615
+ // const notifySync = (meta) => {
616
+ // for (const fn of syncCallbacks) {
617
+ // fn(currentState, meta);
618
+ // }
619
+ // };
620
+
621
+ // const buildWsUrl = () => {
622
+ // const u = new URL(wsOrigin + pathname);
623
+ // for (const [k, v] of Object.entries(connData)) {
624
+ // if (v !== undefined && v !== null) {
625
+ // u.searchParams.set(k, String(v));
626
+ // }
627
+ // }
628
+ // if (lastSeq > 0) {
629
+ // u.searchParams.set('__lastSeq', String(lastSeq));
630
+ // }
631
+ // return u.toString();
632
+ // };
633
+
634
+ // const connect = () => {
635
+ // if (socket && socket.readyState <= WebSocket.OPEN) {
636
+ // socket.close(1000, 'refresh');
637
+ // }
638
+ // manualClose = false;
639
+ // closed = false;
640
+
641
+ // const ws = new WebSocket(buildWsUrl());
642
+ // socket = ws;
643
+
644
+ // ws.addEventListener('open', () => {
645
+ // const reconnected = hasConnectedOnce;
646
+ // hasConnectedOnce = true;
647
+ // emitLocal('open', { reconnected });
648
+ // });
649
+
650
+ // ws.addEventListener('message', (ev) => {
651
+ // let data = ev.data;
652
+ // if (typeof data === 'string') {
653
+ // try { data = JSON.parse(data); } catch {}
654
+ // }
655
+
656
+ // if (data && typeof data === 'object') {
657
+ // if (data.type === 'sync_snapshot') {
658
+ // currentState = data.state;
659
+ // if (typeof data.seq === 'number') lastSeq = data.seq;
660
+ // notifySync({
661
+ // seq: data.seq,
662
+ // room: data.room,
663
+ // fullSnapshot: true,
664
+ // replayed: false
665
+ // });
666
+ // return;
667
+ // }
668
+ // if (data.type === 'sync_patch') {
669
+ // currentState = data.state;
670
+ // if (typeof data.seq === 'number') lastSeq = data.seq;
671
+ // notifySync({
672
+ // seq: data.seq,
673
+ // room: data.room,
674
+ // meta: data.meta,
675
+ // fullSnapshot: false,
676
+ // replayed: Boolean(data.replayed)
677
+ // });
678
+ // return;
679
+ // }
680
+ // if (data.type === 'error') {
681
+ // emitLocal('error', data);
682
+ // return;
683
+ // }
684
+ // if (data.type === 'broadcast') {
685
+ // emitLocal('broadcast', data);
686
+ // return;
687
+ // }
688
+ // if (data.type === 'event') {
689
+ // emitLocal('event', data.payload);
690
+ // return;
691
+ // }
692
+ // }
693
+
694
+ // queue.push(data);
695
+ // if (notify) { notify(); notify = null; }
696
+ // });
697
+
698
+ // ws.addEventListener('close', (ev) => {
699
+ // closed = true;
700
+ // emitLocal('close', { code: ev.code, reason: ev.reason, manual: manualClose });
701
+ // if (notify) { notify(); notify = null; }
702
+ // if (!manualClose) {
703
+ // setTimeout(() => connect(), 1000);
704
+ // }
705
+ // });
706
+
707
+ // ws.addEventListener('error', () => {
708
+ // emitLocal('error', { message: 'WEBSOCKET_ERROR' });
709
+ // });
710
+ // };
711
+
712
+ // connect();
713
+
714
+ // const clientWs = {
715
+ // on(event, cb) {
716
+ // if (listeners[event]) listeners[event].add(cb);
717
+ // return clientWs;
718
+ // },
719
+ // off(event, cb) {
720
+ // if (listeners[event]) listeners[event].delete(cb);
721
+ // return clientWs;
722
+ // },
723
+ // sync(cb) {
724
+ // syncCallbacks.add(cb);
725
+ // if (currentState !== null) {
726
+ // cb(currentState, { seq: lastSeq, fullSnapshot: true, replayed: false });
727
+ // }
728
+ // return clientWs;
729
+ // },
730
+ // emit(name, payload = {}) {
731
+ // if (socket && socket.readyState === WebSocket.OPEN) {
732
+ // socket.send(JSON.stringify({ type: 'action', name, payload }));
733
+ // }
734
+ // return clientWs;
735
+ // },
736
+ // refresh(nextData = null) {
737
+ // if (nextData && typeof nextData === 'object') {
738
+ // connData = { ...connData, ...nextData };
739
+ // }
740
+ // lastSeq = 0;
741
+ // manualClose = true;
742
+ // connect();
743
+ // return clientWs;
744
+ // },
745
+ // resync(room = null) {
746
+ // if (socket && socket.readyState === WebSocket.OPEN) {
747
+ // socket.send(JSON.stringify({ type: 'resync', room }));
748
+ // }
749
+ // return clientWs;
750
+ // },
751
+ // send(data) {
752
+ // const payload = (data instanceof Uint8Array || typeof data === 'string')
753
+ // ? data
754
+ // : JSON.stringify(data);
755
+ // if (socket && socket.readyState === WebSocket.OPEN) {
756
+ // socket.send(payload);
757
+ // } else if (socket) {
758
+ // socket.addEventListener('open', () => socket.send(payload), { once: true });
759
+ // }
760
+ // },
761
+ // close(code = 1000, reason = '') {
762
+ // console.log({code,reason})
763
+ // manualClose = true;
764
+ // if (socket) socket.close(code, reason);
765
+ // },
766
+ // async *[Symbol.asyncIterator]() {
767
+ // while (!closed || queue.length > 0) {
768
+ // if (queue.length > 0) {
769
+ // yield queue.shift();
770
+ // } else {
771
+ // await new Promise((r) => { notify = r; });
772
+ // }
773
+ // }
774
+ // }
775
+ // };
776
+
777
+ // return clientWs;
778
+ // }
779
+
780
+ // let customHeaders = {};
781
+ // let payload;
782
+ // let queryObj;
783
+
784
+ // const hasBody = method === 'POST' || method === 'PUT' || method === 'PATCH';
785
+
786
+ // if (hasBody) {
787
+ // const first = argQueue.shift();
788
+ // if (isOptionsBag(first)) {
789
+ // customHeaders = { ...first.headers };
790
+ // payload = first.body !== undefined ? first.body : argQueue.shift();
791
+ // queryObj = first.query !== undefined ? first.query : argQueue.shift();
792
+ // } else {
793
+ // payload = first;
794
+ // const second = argQueue.shift();
795
+ // if (isOptionsBag(second)) {
796
+ // customHeaders = { ...second.headers };
797
+ // queryObj = second.query !== undefined ? second.query : argQueue.shift();
798
+ // } else {
799
+ // queryObj = second;
800
+ // }
801
+ // }
802
+ // } else {
803
+ // const first = argQueue.shift();
804
+ // if (isOptionsBag(first)) {
805
+ // customHeaders = { ...first.headers };
806
+ // queryObj = first.query !== undefined ? first.query : argQueue.shift();
807
+ // } else {
808
+ // queryObj = first;
809
+ // const second = argQueue.shift();
810
+ // if (isOptionsBag(second)) {
811
+ // customHeaders = { ...second.headers };
812
+ // }
813
+ // }
814
+ // }
815
+
816
+ // const url = new URL(ORIGIN + pathname);
817
+ // if (queryObj && typeof queryObj === 'object') {
818
+ // for (const [k, v] of Object.entries(queryObj)) {
819
+ // if (v !== undefined && v !== null) url.searchParams.set(k, String(v));
820
+ // }
821
+ // }
822
+
823
+ // if (entry?.isAsyncGen) {
824
+ // return (async function* () {
825
+ // const res = await fetch(url, {
826
+ // method,
827
+ // headers: { Accept: 'text/event-stream', ...customHeaders },
828
+ // credentials: 'include'
829
+ // });
830
+ // if (!res.ok) throw Object.assign(new Error(await res.text()), { status: res.status });
831
+ // const reader = res.body.getReader();
832
+ // const decoder = new TextDecoder();
833
+ // let buffer = '';
834
+ // while (true) {
835
+ // const { done, value } = await reader.read();
836
+ // if (done) break;
837
+ // buffer += decoder.decode(value, { stream: true });
838
+ // const blocks = buffer.split('\\n\\n');
839
+ // buffer = blocks.pop() || '';
840
+ // for (const block of blocks) {
841
+ // const line = block.split('\\n').find((l) => l.startsWith('data:'));
842
+ // if (line) yield JSON.parse(line.slice(5).trim());
843
+ // }
844
+ // }
845
+ // })();
846
+ // }
847
+
848
+ // return (async () => {
849
+ // const headers = { ...customHeaders };
850
+ // let body;
851
+ // if (hasBody && payload !== undefined) {
852
+ // if (!Object.keys(headers).some((k) => k.toLowerCase() === 'content-type')) {
853
+ // headers['Content-Type'] = 'application/json';
854
+ // }
855
+ // body = typeof payload === 'string' ? payload : JSON.stringify(payload);
856
+ // }
857
+ // const res = await fetch(url, { method, headers, body, credentials: 'include' });
858
+ // if (res.status === 204) return null;
859
+ // const text = await res.text();
860
+ // let data = text;
861
+ // try { data = JSON.parse(text); } catch {}
862
+ // if (!res.ok) {
863
+ // throw Object.assign(new Error(data?.error || text || 'Request failed'), {
864
+ // status: res.status,
865
+ // data
866
+ // });
867
+ // }
868
+ // return data;
869
+ // })();
870
+ // }
871
+ // });
872
+ // }
873
+
874
+ // export const api = createNode([]);
875
+ // export default api;`;
876
+ // }
877
+
501
878
  export function generateVirtualClientModule(routes) {
502
879
  const manifest = routes
503
880
  .filter((r) => !r.staticDescriptor && !r.redirectDescriptor)
@@ -562,34 +939,215 @@ function createNode(chain) {
562
939
 
563
940
  if (method === 'WS') {
564
941
  const wsOrigin = ORIGIN.replace(/^http/, 'ws');
565
- const ws = new WebSocket(wsOrigin + pathname);
942
+ const firstArg = argQueue.shift();
943
+ let connData = (firstArg && typeof firstArg === 'object' && !Array.isArray(firstArg))
944
+ ? { ...firstArg }
945
+ : {};
946
+
947
+ let activeRoom = connData.room ? String(connData.room) : null;
948
+ let socket = null;
949
+ let manualClose = false;
950
+ let hasConnectedOnce = false;
951
+ let lastSeq = 0;
952
+ let currentState = null;
953
+
566
954
  const queue = [];
567
955
  let notify = null;
568
956
  let closed = false;
569
957
 
570
- ws.onmessage = (ev) => {
571
- let data = ev.data;
572
- if (typeof data === 'string') {
573
- try { data = JSON.parse(data); } catch {}
958
+ const listeners = {
959
+ open: new Set(),
960
+ close: new Set(),
961
+ error: new Set(),
962
+ event: new Set(),
963
+ broadcast: new Set()
964
+ };
965
+ const syncCallbacks = new Set();
966
+
967
+ const emitLocal = (type, detail) => {
968
+ const set = listeners[type];
969
+ if (!set) return;
970
+ for (const fn of set) fn(detail);
971
+ };
972
+
973
+ const notifySync = (meta) => {
974
+ for (const fn of syncCallbacks) {
975
+ fn(currentState, meta);
976
+ }
977
+ };
978
+
979
+ const buildWsUrl = () => {
980
+ const u = new URL(wsOrigin + pathname);
981
+ for (const [k, v] of Object.entries(connData)) {
982
+ if (v !== undefined && v !== null) {
983
+ u.searchParams.set(k, String(v));
984
+ }
985
+ }
986
+ if (lastSeq > 0) {
987
+ u.searchParams.set('__lastSeq', String(lastSeq));
574
988
  }
575
- queue.push(data);
576
- if (notify) { notify(); notify = null; }
989
+ return u.toString();
577
990
  };
578
- ws.onclose = () => {
579
- closed = true;
580
- if (notify) { notify(); notify = null; }
991
+
992
+ const isAllowedRoom = (msgRoom) => {
993
+ if (!activeRoom) return true;
994
+ return Boolean(msgRoom) && String(msgRoom) === activeRoom;
581
995
  };
582
996
 
583
- return {
997
+ const connect = () => {
998
+ if (socket && socket.readyState <= WebSocket.OPEN) {
999
+ socket.close(1000, 'refresh');
1000
+ }
1001
+ manualClose = false;
1002
+ closed = false;
1003
+
1004
+ const ws = new WebSocket(buildWsUrl());
1005
+ socket = ws;
1006
+
1007
+ ws.addEventListener('open', () => {
1008
+ const reconnected = hasConnectedOnce;
1009
+ hasConnectedOnce = true;
1010
+ emitLocal('open', { reconnected });
1011
+ });
1012
+
1013
+ ws.addEventListener('message', (ev) => {
1014
+ let data = ev.data;
1015
+ if (typeof data === 'string') {
1016
+ try { data = JSON.parse(data); } catch {}
1017
+ }
1018
+
1019
+ if (data && typeof data === 'object') {
1020
+ if (data.type === 'sync_snapshot') {
1021
+ if (!isAllowedRoom(data.room)) return;
1022
+ currentState = data.state;
1023
+ if (typeof data.seq === 'number') lastSeq = data.seq;
1024
+ notifySync({
1025
+ seq: data.seq,
1026
+ room: data.room,
1027
+ fullSnapshot: true,
1028
+ replayed: false
1029
+ });
1030
+ return;
1031
+ }
1032
+ if (data.type === 'sync_patch') {
1033
+ if (!isAllowedRoom(data.room)) return;
1034
+ currentState = data.state;
1035
+ if (typeof data.seq === 'number') lastSeq = data.seq;
1036
+ notifySync({
1037
+ seq: data.seq,
1038
+ room: data.room,
1039
+ meta: data.meta,
1040
+ fullSnapshot: false,
1041
+ replayed: Boolean(data.replayed)
1042
+ });
1043
+ return;
1044
+ }
1045
+ if (data.type === 'error') {
1046
+ emitLocal('error', data);
1047
+ return;
1048
+ }
1049
+ if (data.type === 'broadcast') {
1050
+ if (!data.global && !isAllowedRoom(data.room)) return;
1051
+ emitLocal('broadcast', data);
1052
+ return;
1053
+ }
1054
+ if (data.type === 'event') {
1055
+ emitLocal('event', data.payload);
1056
+ return;
1057
+ }
1058
+ if (typeof data.event === 'string' && listeners[data.event]) {
1059
+ emitLocal(data.event, data.data !== undefined ? data.data : data);
1060
+ return;
1061
+ }
1062
+ }
1063
+
1064
+ queue.push(data);
1065
+ if (notify) { notify(); notify = null; }
1066
+ });
1067
+
1068
+ ws.addEventListener('close', (ev) => {
1069
+ closed = true;
1070
+ emitLocal('close', { code: ev.code, reason: ev.reason, manual: manualClose });
1071
+ if (notify) { notify(); notify = null; }
1072
+ if (!manualClose) {
1073
+ setTimeout(() => connect(), 1000);
1074
+ }
1075
+ });
1076
+
1077
+ ws.addEventListener('error', () => {
1078
+ emitLocal('error', { message: 'WEBSOCKET_ERROR' });
1079
+ });
1080
+ };
1081
+
1082
+ connect();
1083
+
1084
+ const clientWs = {
1085
+ on(event, cb) {
1086
+ if (!listeners[event]) listeners[event] = new Set();
1087
+ listeners[event].add(cb);
1088
+ return clientWs;
1089
+ },
1090
+ off(event, cb) {
1091
+ if (listeners[event]) listeners[event].delete(cb);
1092
+ return clientWs;
1093
+ },
1094
+ sync(cb) {
1095
+ syncCallbacks.add(cb);
1096
+ if (currentState !== null) {
1097
+ cb(currentState, {
1098
+ seq: lastSeq,
1099
+ room: activeRoom,
1100
+ fullSnapshot: true,
1101
+ replayed: false
1102
+ });
1103
+ }
1104
+ return clientWs;
1105
+ },
1106
+ emit(name, payload = {}) {
1107
+ if (socket && socket.readyState === WebSocket.OPEN) {
1108
+ socket.send(JSON.stringify({ type: 'action', name, payload }));
1109
+ }
1110
+ return clientWs;
1111
+ },
1112
+ refresh(nextData = null) {
1113
+ if (nextData && typeof nextData === 'object') {
1114
+ connData = { ...connData, ...nextData };
1115
+ if (nextData.room !== undefined) {
1116
+ activeRoom = nextData.room ? String(nextData.room) : null;
1117
+ }
1118
+ }
1119
+ currentState = null;
1120
+ lastSeq = 0;
1121
+ manualClose = true;
1122
+ connect();
1123
+ return clientWs;
1124
+ },
1125
+ resync(room = null) {
1126
+ if (room !== null && room !== undefined) {
1127
+ activeRoom = String(room);
1128
+ connData.room = activeRoom;
1129
+ currentState = null;
1130
+ lastSeq = 0;
1131
+ }
1132
+ if (socket && socket.readyState === WebSocket.OPEN) {
1133
+ socket.send(JSON.stringify({ type: 'resync', room: room ?? activeRoom }));
1134
+ }
1135
+ return clientWs;
1136
+ },
584
1137
  send(data) {
585
1138
  const payload = (data instanceof Uint8Array || typeof data === 'string')
586
1139
  ? data
587
1140
  : JSON.stringify(data);
588
- if (ws.readyState === WebSocket.OPEN) ws.send(payload);
589
- else ws.addEventListener('open', () => ws.send(payload), { once: true });
1141
+ if (socket && socket.readyState === WebSocket.OPEN) {
1142
+ socket.send(payload);
1143
+ } else if (socket) {
1144
+ socket.addEventListener('open', () => socket.send(payload), { once: true });
1145
+ }
590
1146
  },
591
- close(code, reason) {
592
- ws.close(code, reason);
1147
+ close(code=1000, reason = '') {
1148
+ console.log({code,reason})
1149
+ manualClose = true;
1150
+ if (socket) socket.close(code, reason);
593
1151
  },
594
1152
  async *[Symbol.asyncIterator]() {
595
1153
  while (!closed || queue.length > 0) {
@@ -601,6 +1159,8 @@ function createNode(chain) {
601
1159
  }
602
1160
  }
603
1161
  };
1162
+
1163
+ return clientWs;
604
1164
  }
605
1165
 
606
1166
  let customHeaders = {};