sonic-ws 1.3.3 → 2.0.0-fix

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.
Files changed (84) hide show
  1. package/LICENSE +56 -196
  2. package/README.md +88 -17
  3. package/bundled/bundle.js +6 -0
  4. package/bundled/bundle.wasm +0 -0
  5. package/dist/{index.d.ts → ts/index.d.ts} +11 -0
  6. package/dist/{index.js → ts/index.js} +10 -11
  7. package/dist/ts/native/wrapper.d.ts +64 -0
  8. package/dist/ts/native/wrapper.js +7 -0
  9. package/dist/ts/version.d.ts +16 -0
  10. package/dist/ts/version.js +7 -0
  11. package/dist/{ws → ts/ws}/Connection.d.ts +10 -0
  12. package/dist/ts/ws/Connection.js +7 -0
  13. package/dist/{ws → ts/ws}/PacketProcessor.d.ts +10 -0
  14. package/dist/ts/ws/PacketProcessor.js +7 -0
  15. package/dist/{ws → ts/ws}/client/core/ClientCore.d.ts +10 -0
  16. package/dist/ts/ws/client/core/ClientCore.js +7 -0
  17. package/dist/{ws → ts/ws}/client/node/ClientNode.d.ts +10 -0
  18. package/dist/ts/ws/client/node/ClientNode.js +7 -0
  19. package/dist/ts/ws/debug/DebugServer.d.ts +17 -0
  20. package/dist/ts/ws/debug/DebugServer.js +7 -0
  21. package/dist/{ws → ts/ws}/packets/PacketType.d.ts +11 -1
  22. package/dist/ts/ws/packets/PacketType.js +7 -0
  23. package/dist/{ws → ts/ws}/packets/Packets.d.ts +10 -3
  24. package/dist/ts/ws/packets/Packets.js +7 -0
  25. package/dist/{ws → ts/ws}/server/SonicWSConnection.d.ts +10 -0
  26. package/dist/ts/ws/server/SonicWSConnection.js +7 -0
  27. package/dist/{ws → ts/ws}/server/SonicWSServer.d.ts +13 -0
  28. package/dist/ts/ws/server/SonicWSServer.js +7 -0
  29. package/dist/{ws → ts/ws}/util/BufferUtil.d.ts +10 -0
  30. package/dist/ts/ws/util/BufferUtil.js +7 -0
  31. package/dist/ts/ws/util/StringUtil.d.ts +13 -0
  32. package/dist/ts/ws/util/StringUtil.js +7 -0
  33. package/dist/{ws → ts/ws}/util/enums/EnumHandler.d.ts +10 -0
  34. package/dist/ts/ws/util/enums/EnumHandler.js +7 -0
  35. package/dist/ts/ws/util/enums/EnumType.d.ts +12 -0
  36. package/dist/ts/ws/util/enums/EnumType.js +7 -0
  37. package/dist/ts/ws/util/packets/BatchHelper.d.ts +11 -0
  38. package/dist/ts/ws/util/packets/BatchHelper.js +7 -0
  39. package/dist/ts/ws/util/packets/CompressionUtil.d.ts +18 -0
  40. package/dist/ts/ws/util/packets/CompressionUtil.js +7 -0
  41. package/dist/ts/ws/util/packets/HashUtil.d.ts +12 -0
  42. package/dist/ts/ws/util/packets/HashUtil.js +7 -0
  43. package/dist/ts/ws/util/packets/JSONUtil.d.ts +12 -0
  44. package/dist/ts/ws/util/packets/JSONUtil.js +7 -0
  45. package/dist/ts/ws/util/packets/PacketHolder.d.ts +11 -0
  46. package/dist/ts/ws/util/packets/PacketHolder.js +7 -0
  47. package/dist/{ws → ts/ws}/util/packets/PacketUtils.d.ts +10 -0
  48. package/dist/ts/ws/util/packets/PacketUtils.js +7 -0
  49. package/dist/ts/ws/util/packets/RateHandler.d.ts +11 -0
  50. package/dist/ts/ws/util/packets/RateHandler.js +7 -0
  51. package/package.json +14 -10
  52. package/dist/version.d.ts +0 -6
  53. package/dist/version.js +0 -25
  54. package/dist/ws/Connection.js +0 -126
  55. package/dist/ws/PacketProcessor.js +0 -52
  56. package/dist/ws/client/core/ClientCore.js +0 -251
  57. package/dist/ws/client/node/ClientNode.js +0 -36
  58. package/dist/ws/debug/DebugServer.d.ts +0 -7
  59. package/dist/ws/debug/DebugServer.js +0 -607
  60. package/dist/ws/packets/PacketProcessors.d.ts +0 -13
  61. package/dist/ws/packets/PacketProcessors.js +0 -317
  62. package/dist/ws/packets/PacketType.js +0 -61
  63. package/dist/ws/packets/Packets.js +0 -277
  64. package/dist/ws/server/SonicWSConnection.js +0 -298
  65. package/dist/ws/server/SonicWSServer.js +0 -307
  66. package/dist/ws/util/BufferUtil.js +0 -42
  67. package/dist/ws/util/StringUtil.d.ts +0 -5
  68. package/dist/ws/util/StringUtil.js +0 -51
  69. package/dist/ws/util/enums/EnumHandler.js +0 -60
  70. package/dist/ws/util/enums/EnumType.d.ts +0 -2
  71. package/dist/ws/util/enums/EnumType.js +0 -72
  72. package/dist/ws/util/packets/BatchHelper.d.ts +0 -1
  73. package/dist/ws/util/packets/BatchHelper.js +0 -85
  74. package/dist/ws/util/packets/CompressionUtil.d.ts +0 -35
  75. package/dist/ws/util/packets/CompressionUtil.js +0 -277
  76. package/dist/ws/util/packets/HashUtil.d.ts +0 -2
  77. package/dist/ws/util/packets/HashUtil.js +0 -122
  78. package/dist/ws/util/packets/JSONUtil.d.ts +0 -2
  79. package/dist/ws/util/packets/JSONUtil.js +0 -179
  80. package/dist/ws/util/packets/PacketHolder.d.ts +0 -1
  81. package/dist/ws/util/packets/PacketHolder.js +0 -126
  82. package/dist/ws/util/packets/PacketUtils.js +0 -283
  83. package/dist/ws/util/packets/RateHandler.d.ts +0 -1
  84. package/dist/ws/util/packets/RateHandler.js +0 -66
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Copyright (c) 2026 Lily (liwybloc)
3
+ * License-Identifier: LicenseRef-Lily-Personal-NonCommercial-2026
4
+ * See LICENSE for personal, non-commercial license terms.
5
+ */
6
+ /**
7
+ * Copyright (c) 2026 Lily (liwybloc)
8
+ * License-Identifier: LicenseRef-Lily-Personal-NonCommercial-2026
9
+ * See LICENSE for personal, non-commercial license terms.
10
+ */
11
+ export declare function setHashFunc(use64Bit: boolean): void;
12
+ export declare function hashValue(value: any): bigint | number;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Copyright (c) 2026 Lily (liwybloc)
3
+ * License-Identifier: LicenseRef-Lily-Personal-NonCommercial-2026
4
+ * See LICENSE for personal, non-commercial license terms.
5
+ */
6
+
7
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.setHashFunc=function(e){o=e?n:r},exports.hashValue=function(e){return o(e)};const e=1099511628211n,t=(1n<<64n)-1n,n=n=>{let r=14695981039346656037n;const o=n=>{if(null===n)return r^=0n,void(r=r*e&t);const l=typeof n;if("number"===l)return r^=BigInt(Math.trunc(n)),void(r=r*e&t);if("string"!==l){if("boolean"===l)return r^=n?1n:0n,void(r=r*e&t);if(Array.isArray(n))for(let e=0;e<n.length;e++)o(n[e]);else if("object"===l){const l=Object.keys(n).sort();for(let s=0;s<l.length;s++){const i=l[s];for(let n=0;n<i.length;n++)r^=BigInt(i.charCodeAt(n)),r=r*e&t;o(n[i])}}}else for(let o=0;o<n.length;o++)r^=BigInt(n.charCodeAt(o)),r=r*e&t};return o(n),r},r=e=>{let t=2166136261;const n=e=>{if(null===e)return void(t^=0);const r=typeof e;if("number"===r)return t^=0|e,void(t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24));if("string"!==r)if("boolean"!==r){if(Array.isArray(e))for(let t=0;t<e.length;t++)n(e[t]);else if("object"===r){const r=Object.keys(e).sort();for(let o=0;o<r.length;o++){const l=r[o];for(let e=0;e<l.length;e++)t^=l.charCodeAt(e),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);n(e[l])}}}else t^=e?1:0;else for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24)};return n(e),t>>>0};let o=n;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Copyright (c) 2026 Lily (liwybloc)
3
+ * License-Identifier: LicenseRef-Lily-Personal-NonCommercial-2026
4
+ * See LICENSE for personal, non-commercial license terms.
5
+ */
6
+ /**
7
+ * Copyright (c) 2026 Lily (liwybloc)
8
+ * License-Identifier: LicenseRef-Lily-Personal-NonCommercial-2026
9
+ * See LICENSE for personal, non-commercial license terms.
10
+ */
11
+ export declare const compressJSON: (value: any) => Uint8Array<ArrayBuffer>;
12
+ export declare const decompressJSON: (bytes: Uint8Array) => any;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Copyright (c) 2026 Lily (liwybloc)
3
+ * License-Identifier: LicenseRef-Lily-Personal-NonCommercial-2026
4
+ * See LICENSE for personal, non-commercial license terms.
5
+ */
6
+
7
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.decompressJSON=exports.compressJSON=void 0;const r=require("../BufferUtil"),e=r=>Array.from({length:8},(e,t)=>!!(r&1<<7-t));function t(r){if(!Number.isInteger(r)||r<0)throw new Error(`Invalid JSON variable integer: ${r}`);const e=[];do{let t=127&r;(r>>>=7)>0&&(t|=128),e.push(t)}while(r>0);return e}function n(r,e){let t=0,n=0;for(;;){if(e>=r.length||n>28)throw new Error("Invalid JSON variable integer");const s=r[e++];if(t+=(127&s)<<n,!(128&s))return[e,t];n+=7}}var s;!function(r){r[r.NULL=0]="NULL",r[r.BOOL=1]="BOOL",r[r.INT=2]="INT",r[r.FLOAT=3]="FLOAT",r[r.STRING=4]="STRING",r[r.ARRAY=5]="ARRAY",r[r.OBJECT=6]="OBJECT"}(s||(s={}));const o=r=>{const e=(new TextEncoder).encode(r);return[...t(e.length),...e]},a=(r,e)=>{const[t,s]=n(r,e);return{value:(new TextDecoder).decode(r.subarray(t,t+s)),length:t+s-e}};exports.compressJSON=e=>{const n=[],a=[],u=[],c=r=>{switch(null===r?"null":Array.isArray(r)?"array":typeof r){case"null":u.push(s.NULL);break;case"boolean":u.push(s.BOOL),n.push(r);break;case"number":Number.isInteger(r)?(u.push(s.INT),a.push(...t((r=>r<<1^r>>31)(r)))):(u.push(s.FLOAT),a.push(...function(r){if(Number.isNaN(r))return[127,128,0,1];const e=r<0?1:0;if(0===(r=Math.abs(r)))return[0,0,0,0];const t=Math.floor(Math.log2(r));if(!Number.isFinite(r)||t>127||t<-126)return[e?255:127,128,0,0];const n=(e<<31|t+127<<23|8388607&Math.round((r/2**t-1)*2**23))>>>0;return[n>>>24,n>>>16&255,n>>>8&255,255&n]}(r)));break;case"string":u.push(s.STRING),a.push(...o(r));break;case"array":u.push(s.ARRAY),a.push(...t(r.length));for(const e of r)c(e);break;case"object":{u.push(s.OBJECT);const e=Object.keys(r);a.push(...t(e.length));for(const t of e)a.push(...o(t)),c(r[t]);break}default:throw new Error("Unsupported type")}};c(e);const l=n.length?(0,r.splitArray)(n,8).map(r=>r.reduce((r,e,t)=>r|Number(e)<<7-t,0)):[],h=(r=>{let e="";for(const t of r)e+=t.toString(2).padStart(3,"0");return(r=>new Uint8Array(r.match(/.{1,8}/g)?.map(r=>parseInt(r.padEnd(8,"0"),2))??[]))(e)})(u),p=[...t(l.length),...t(h.length)];return Uint8Array.from([...p,...l.flat(),...h,...a])},exports.decompressJSON=r=>{let t=0;const[o,u]=n(r,t);t=o;const[c,l]=n(r,t);t=c;const h=[];for(let n=0;n<u;n++)h.push(...e(r[t++]));let p=0;const i=r.subarray(t,t+l);t+=l;const f=((r,e)=>{const t=(r=>Array.from(r,r=>r.toString(2).padStart(8,"0")).join(""))(r),n=[];for(let r=0;r<e;r++)n.push(parseInt(t.slice(3*r,3*r+3),2));return n})(i,8*i.length/3);let N=0;const O=e=>{if(e>500)throw new Error("JSON array too deep.");const o=f[N++];switch(o){case s.NULL:return null;case s.BOOL:return h[p++];case s.INT:{const[e,s]=n(r,t);return t=e,(u=s)>>>1^-(1&u)}case s.FLOAT:{const e=function(r){const e=(r[0]<<24|r[1]<<16|r[2]<<8|r[3])>>>0,t=e>>>23&255,n=(0===t?0:1)+(8388607&e)/2**23,s=255===t?0===n?1/0:NaN:n*2**(0===t?-126:t-127);return e>>>31?-s:s}(Array.from(r.subarray(t,t+4)));return t+=4,e}case s.STRING:{const{value:e,length:n}=a(r,t);return t+=n,e}case s.ARRAY:{const[s,o]=n(r,t);t=s;const a=[];for(let r=0;r<o;r++)a.push(O(e+1));return a}case s.OBJECT:{const[s,o]=n(r,t);t=s;const u={};for(let n=0;n<o;n++){const{value:n,length:s}=a(r,t);t+=s,u[n]=O(e+1)}return u}default:throw new Error(`Unknown type ${o}`)}var u};return O(0)};
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Copyright (c) 2026 Lily (liwybloc)
3
+ * License-Identifier: LicenseRef-Lily-Personal-NonCommercial-2026
4
+ * See LICENSE for personal, non-commercial license terms.
5
+ */
6
+ /**
7
+ * Copyright (c) 2026 Lily (liwybloc)
8
+ * License-Identifier: LicenseRef-Lily-Personal-NonCommercial-2026
9
+ * See LICENSE for personal, non-commercial license terms.
10
+ */
11
+ export {};
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Copyright (c) 2026 Lily (liwybloc)
3
+ * License-Identifier: LicenseRef-Lily-Personal-NonCommercial-2026
4
+ * See LICENSE for personal, non-commercial license terms.
5
+ */
6
+
7
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.PacketHolder=void 0,exports.PacketHolder=class{key;keys;tags;packetMap;packets;constructor(t){this.key=1,this.keys={},this.tags={},this.packetMap={},t&&this.holdPackets(t)}createKey(t){this.keys[t]=this.key,this.tags[this.key]=t,this.key++}holdPackets(t){this.packets=t;for(const e of t)this.createKey(e.tag),this.packetMap[e.tag]=e}getKey(t){if(!(t in this.keys))throw new Error(`Not a valid tag: ${t}`);return this.keys[t]}getTag(t){if(t in this.tags)return this.tags[t]}getPacket(t){if(!(t in this.packetMap))throw new Error("Unknown packet tag: "+t);return this.packetMap[t]}hasKey(t){return t in this.tags}hasTag(t){return t in this.keys}getKeys(){return this.keys}getTagMap(){return this.tags}getTags(){return Object.values(this.tags)}getPackets(){return this.packets}serialize(){return this.packets.map(t=>t.serialize()).flat()}};
@@ -1,3 +1,13 @@
1
+ /**
2
+ * Copyright (c) 2026 Lily (liwybloc)
3
+ * License-Identifier: LicenseRef-Lily-Personal-NonCommercial-2026
4
+ * See LICENSE for personal, non-commercial license terms.
5
+ */
6
+ /**
7
+ * Copyright (c) 2026 Lily (liwybloc)
8
+ * License-Identifier: LicenseRef-Lily-Personal-NonCommercial-2026
9
+ * See LICENSE for personal, non-commercial license terms.
10
+ */
1
11
  import { ConvertType, Packet, ValidatorFunction } from "../../packets/Packets";
2
12
  import { PacketType } from "../../packets/PacketType";
3
13
  import { EnumPackage } from "../enums/EnumType";
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Copyright (c) 2026 Lily (liwybloc)
3
+ * License-Identifier: LicenseRef-Lily-Personal-NonCommercial-2026
4
+ * See LICENSE for personal, non-commercial license terms.
5
+ */
6
+
7
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.processPacket=async function e(a,o,i,s,c,l=!1){const f=a.getKey(o),p=a.getPacket(o);return async function(t,a,n,r,o,i,s){if(t[0]&&!i)return new Promise(e=>t[1].push([e,r,o]));t[0]=!0;const c=await s();if(t[1].length>0){const[r,o,i]=t[1].shift();queueMicrotask(async()=>{r(await e(a,o,i,t,n,!0))})}else t[0]=!1;return c}(s,a,c,o,i,l,async()=>{if(p.rereference){if(-1===c)throw new Error("Cannot send a re-referenced packet from the server-wide sender!");const e=(0,r.hashValue)(i);if(p.lastSent[c]===e)return[f,n.EMPTY_UINT8,p];p.lastSent[c]=e}if(p.autoFlatten)i=u(i[0]);else{if(i.length>p.maxSize)throw new Error(`Packet "${o}" only allows ${p.maxSize} values!`);if(i.length<p.minSize)throw new Error(`Packet "${o}" requires at least ${p.minSize} values!`)}if(p.object){if(i=i.map(e=>Array.isArray(e)?e:[e]),!p.autoFlatten){const e=p.dataMin,t=p.dataMax;for(let a=0;a<e.length;a++){if(i[a].length<e[a])throw new Error(`Section ${a+1} of packet "${o}" requires at least ${e[a]} values!`);if(i[a].length>t[a])throw new Error(`Section ${a+1} of packet "${o}" only allows ${t[a]} values!`)}}}else if(p.type!==t.PacketType.JSON){const e=i.find(e=>"object"==typeof e&&null!=e);e&&console.warn(`Passing an array will result in undefined behavior (${JSON.stringify(e)}). Spread the array with ...arr`)}const e=i.length>0?await p.processSend(i):n.EMPTY_UINT8;return[f,e,p]})},exports.listenPacket=async function(e,t,a){if("string"==typeof e)return a(e);const[n,r]=e;try{if(r&&Array.isArray(n))for(const e of t)await e(...n);else for(const e of t)await e(n)}catch(e){console.error(e),a(e)}},exports.CreatePacket=l,exports.CreateObjPacket=function(a){let{tag:n,types:r=[],dataMaxes:l,dataMins:u,noDataRange:f=!1,dontSpread:p=!1,autoFlatten:h=!1,validator:y=null,dataBatching:m=0,maxBatchSize:d=10,rateLimit:w=0,enabled:g=!0,async:k=!1,gzipCompression:P=r&&r.includes(t.PacketType.JSON)}=a;if(!n)throw new Error("Tag not selected!");if(!r||0==r.length)throw new Error("Types is set to 0 length");for(const e of r)if(o(e))throw new Error(`Invalid packet type in "${n}" packet: ${e}`);f?(l=Array.from({length:r.length}).map(()=>i),u=Array.from({length:r.length}).map(()=>0)):(null==l?l=Array.from({length:r.length}).map(()=>1):Array.isArray(l)||(l=Array.from({length:r.length}).map(()=>l)),null==u?u=Array.from({length:r.length}).map((e,t)=>l[t]):Array.isArray(u)||(u=Array.from({length:r.length}).map(()=>u)));const E=l.map(s),S=u.map((e,a)=>r[a]==t.PacketType.NONE?0:c(e,E[a])),x=new e.PacketSchema(!0,r,k,S,E,w,p,h,!1,m,d,P);return new e.Packet(n,x,y,g,!1)},exports.CreateEnumPacket=function(e){const{tag:t,enumData:a,dataMax:n=1,dataMin:r=0,noDataRange:o=!1,dontSpread:i=!1,validator:s=null,dataBatching:c=0,maxBatchSize:u=10,rateLimit:f=0,enabled:p=!0,async:h=!1}=e;return l({tag:t,type:a,dataMax:n,dataMin:r,noDataRange:o,dontSpread:i,validator:s,dataBatching:c,maxBatchSize:u,rateLimit:f,enabled:p,async:h})},exports.CreateKeyEffective=function(e){const{tag:t,count:a=2,validator:n=null,async:r=!1}=e;if(!t)throw new Error("Tag not selected!");if(a<2)throw new Error("Must have at least 2 key consumptions on key effective packet!");throw new Error("Currently W.I.P.")},exports.FlattenData=u,exports.UnFlattenData=function(e){return e[0]?.map((t,a)=>e.map(e=>e[a]))??[]};const e=require("../../packets/Packets"),t=require("../../packets/PacketType"),a=require("../enums/EnumType"),n=require("./CompressionUtil"),r=require("./HashUtil");function o(e){return!(("number"==typeof e&&e in t.PacketType||e instanceof a.EnumPackage)&&e!=t.PacketType.KEY_EFFECTIVE)}const i=2048383;function s(e){return e<0?(console.warn("Having a data maximum below 0 does not do anything!"),0):e>i?(console.warn(`Only ${i} values can be sent on a type! Uhh make an issue if you want to send more.`),i):e}function c(e,t){return e<0?(console.warn("Having a data minimum below 0 does not do anything!"),0):e>t?(console.warn("Data minimum can not be higher than the data maximum!"),t):e}function l(a){let{tag:n,type:r=t.PacketType.NONE,dataMax:l=1,dataMin:u=1,noDataRange:f=!1,dontSpread:p=!1,validator:h=null,dataBatching:y=0,maxBatchSize:m=10,rateLimit:d=0,enabled:w=!0,async:g=!1,gzipCompression:k=r==t.PacketType.JSON,rereference:P=!1}=a;if(!n)throw new Error("Tag not selected!");if(f?(u=P?1:0,l=i):null==u&&(u=r==t.PacketType.NONE?0:l),P&&0==u)throw new Error("Rereference cannot be true if the dataMin is 0");if(o(r))throw new Error(`Invalid packet type: ${r}`);const E=new e.PacketSchema(!1,r,g,c(u,l),s(l),d,p,!1,P,y,m,k);return new e.Packet(n,E,h,w,!1)}function u(e){if(null==e)return[];const t=e[0];if(null==t)return[];if(!Array.isArray(t))throw new Error(`Cannot flatten array: ${e}`);return t.map((t,a)=>e.map(e=>e[a]))??[]}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Copyright (c) 2026 Lily (liwybloc)
3
+ * License-Identifier: LicenseRef-Lily-Personal-NonCommercial-2026
4
+ * See LICENSE for personal, non-commercial license terms.
5
+ */
6
+ /**
7
+ * Copyright (c) 2026 Lily (liwybloc)
8
+ * License-Identifier: LicenseRef-Lily-Personal-NonCommercial-2026
9
+ * See LICENSE for personal, non-commercial license terms.
10
+ */
11
+ export {};
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Copyright (c) 2026 Lily (liwybloc)
3
+ * License-Identifier: LicenseRef-Lily-Personal-NonCommercial-2026
4
+ * See LICENSE for personal, non-commercial license terms.
5
+ */
6
+
7
+ Object.defineProperty(exports,"__esModule",{value:!0}),exports.RateHandler=void 0;const t=require("../../Connection");exports.RateHandler=class{rates={};limits={};setInterval;socket;constructor(t){this.setInterval=t.setInterval,this.socket=t.socket}start(){0!=Object.keys(this.rates).length&&this.setInterval(()=>{for(const t in this.rates)this.rates[t]=0},1e3)}registerRate(t,e){0!=e&&(this.rates[t]=0,this.limits[t]=e)}registerAll(t,e){const s=t.getPackets();for(const r of s)this.registerRate(e+t.getKey(r.tag),r.rateLimit)}trigger(e){return e in this.rates&&++this.rates[e]>this.limits[e]&&(this.socket.close(t.CloseCodes.RATELIMIT),!0)}subtract(t){t in this.rates&&this.rates[t]--}};
package/package.json CHANGED
@@ -1,17 +1,20 @@
1
1
  {
2
2
  "name": "sonic-ws",
3
- "version": "1.3.3",
3
+ "version": "2.0.0-fix",
4
4
  "description": "Ultra-lightweight, high-performance, and bandwidth efficient websocket library",
5
- "main": "dist/index.js",
6
- "types": "dist/index.d.ts",
5
+ "main": "dist/ts/index.js",
6
+ "types": "dist/ts/index.d.ts",
7
7
  "scripts": {
8
8
  "webpack": "webpack --mode production",
9
- "build_web": "rimraf ./html && tsc --moduleResolution nodenext --module nodenext --outDir ./html src/ws/client/browser/ClientBrowser.ts && npm run webpack",
10
- "build_node": "rimraf ./dist && tsc -d",
11
- "build": "npm run build_node && npm run build_web && rimraf ./dist/ws/client/browser && rimraf ./dist/ws/debug/DebugClient.d.ts && rimraf ./dist/ws/debug/DebugClient.js",
12
- "test_web": "npm run build && node test-site/server.mjs",
13
- "test_node": "npm run build_node && node test.mjs",
14
- "publish": "npm run build && node minify && cp ./bundled/SonicWS_bundle.js ./release/SonicWS_bundle.js && sleep 1"
9
+ "build_wasm_browser": "wasm-pack build --release --target bundler --out-dir ../ts/native/wasm/pkg --out-name sonic_ws_core ./src/core --features wasm --no-default-features",
10
+ "build_wasm_node": "wasm-pack build --release --target nodejs --out-dir ../ts/native/wasm/node --out-name sonic_ws_core ./src/core --features wasm --no-default-features",
11
+ "build_wasm": "npm run build_wasm_browser && npm run build_wasm_node",
12
+ "build_web": "npm run build_wasm_browser && tsc --moduleResolution nodenext --module nodenext --outDir ./dist/ts src/ts/ws/client/browser/ClientBrowser.ts && cpy \"src/ts/native/wasm/pkg/*\" dist/ts/native/wasm/pkg --flat && npm run webpack",
13
+ "build_node": "npm run build_wasm && rimraf ./dist/ts && tsc -d && cpy \"src/ts/native/wasm/node/*\" dist/ts/native/wasm/node --flat",
14
+ "build": "npm run build_node && npm run build_web && rimraf ./dist/ts/ws/client/browser && rimraf ./dist/ts/ws/debug/DebugClient.d.ts && rimraf ./dist/ts/ws/debug/DebugClient.js && node minify",
15
+ "test_web": "npm run build && node tests/test_web.mjs",
16
+ "test_node": "npm --prefix src/core/tests/typescript run build:native && npm run build_node && node tests/test_node.mjs",
17
+ "publish": "npm run build && node minify && rimraf ./release/SonicWS_bundle.js ./release/SonicWS_core.wasm && cp ./bundled/bundle.js ./release/bundle.js && cp ./bundled/bundle.wasm ./release/bundle.wasm && sleep 1"
15
18
  },
16
19
  "repository": {
17
20
  "type": "git",
@@ -22,7 +25,7 @@
22
25
  },
23
26
  "homepage": "https://github.com/liwybloc/sonic-ws#readme",
24
27
  "author": "lily",
25
- "license": "Apache-2.0",
28
+ "license": "LicenseRef-Lily-Personal-NonCommercial-2026",
26
29
  "dependencies": {
27
30
  "open": "^11.0.0",
28
31
  "ws": "^8.18.2"
@@ -33,6 +36,7 @@
33
36
  "cpy-cli": "^5.0.0",
34
37
  "esbuild-loader": "^4.4.2",
35
38
  "form-data": "^4.0.4",
39
+ "playwright": "^1.61.1",
36
40
  "rimraf": "^6.0.1",
37
41
  "terser": "^5.46.0",
38
42
  "ts-loader": "^9.5.2",
package/dist/version.d.ts DELETED
@@ -1,6 +0,0 @@
1
- /** Current protocol version */
2
- export declare const VERSION = 22;
3
- /** Server data suffix */
4
- export declare const SERVER_SUFFIX = "SWS";
5
- /** Server data suffix in array */
6
- export declare const SERVER_SUFFIX_NUMS: number[];
package/dist/version.js DELETED
@@ -1,25 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright 2026 Lily (liwybloc)
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.SERVER_SUFFIX_NUMS = exports.SERVER_SUFFIX = exports.VERSION = void 0;
19
- const StringUtil_1 = require("./ws/util/StringUtil");
20
- /** Current protocol version */
21
- exports.VERSION = 22;
22
- /** Server data suffix */
23
- exports.SERVER_SUFFIX = "SWS";
24
- /** Server data suffix in array */
25
- exports.SERVER_SUFFIX_NUMS = (0, StringUtil_1.processCharCodes)(exports.SERVER_SUFFIX);
@@ -1,126 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright 2026 Lily (liwybloc)
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.CloseCodes = exports.Connection = void 0;
19
- exports.getClosureCause = getClosureCause;
20
- const PacketProcessor_1 = require("./PacketProcessor");
21
- const BatchHelper_1 = require("./util/packets/BatchHelper");
22
- class Connection extends PacketProcessor_1.MiddlewareHolder {
23
- listeners;
24
- name;
25
- closed = false;
26
- socket;
27
- _timers = {};
28
- batcher;
29
- _on;
30
- _off;
31
- /** The index of the connection; unique for all connected, not unique after disconnection. */
32
- id;
33
- constructor(socket, id, name, addListener, removeListener) {
34
- super();
35
- this.id = id;
36
- this.listeners = {};
37
- this.name = name;
38
- this.socket = socket;
39
- this.batcher = new BatchHelper_1.BatchHelper();
40
- this._on = addListener;
41
- this._off = removeListener;
42
- this._on("close", () => {
43
- this.callMiddleware('onStatusChange', WebSocket.CLOSED);
44
- this.closed = true;
45
- for (const [id, callback, shouldCall] of Object.values(this._timers)) {
46
- this.clearTimeout(id);
47
- if (shouldCall)
48
- callback(true);
49
- }
50
- });
51
- this._on('open', () => this.callMiddleware('onStatusChange', WebSocket.OPEN));
52
- }
53
- setTimeout(call, time, callOnClose = false) {
54
- const timeout = setTimeout(() => {
55
- call();
56
- this.clearTimeout(timeout);
57
- }, time);
58
- this._timers[timeout] = [timeout, call, callOnClose];
59
- return timeout;
60
- }
61
- setInterval(call, time, callOnClose = false) {
62
- const interval = setInterval(call, time);
63
- this._timers[interval] = [interval, call, callOnClose];
64
- return interval;
65
- }
66
- clearTimeout(id) {
67
- clearTimeout(id);
68
- delete this._timers[id];
69
- }
70
- clearInterval(id) {
71
- this.clearTimeout(id);
72
- }
73
- raw_send(data) {
74
- this.socket.send(data);
75
- }
76
- raw_onmessage(listener) {
77
- this._on("message", listener);
78
- }
79
- close(code = 1000, reason) {
80
- this.closed = true;
81
- this.socket.close(code, reason?.toString());
82
- }
83
- isClosed() {
84
- return this.closed || this.socket.readyState == WebSocket.CLOSED;
85
- }
86
- async setName(name) {
87
- if (await this.callMiddleware("onNameChange", name))
88
- return;
89
- this.name = name;
90
- }
91
- getName() {
92
- return this.name;
93
- }
94
- }
95
- exports.Connection = Connection;
96
- var CloseCodes;
97
- (function (CloseCodes) {
98
- CloseCodes[CloseCodes["RATELIMIT"] = 4000] = "RATELIMIT";
99
- CloseCodes[CloseCodes["SMALL"] = 4001] = "SMALL";
100
- CloseCodes[CloseCodes["INVALID_KEY"] = 4002] = "INVALID_KEY";
101
- CloseCodes[CloseCodes["INVALID_PACKET"] = 4003] = "INVALID_PACKET";
102
- CloseCodes[CloseCodes["INVALID_DATA"] = 4004] = "INVALID_DATA";
103
- CloseCodes[CloseCodes["REPEATED_HANDSHAKE"] = 4005] = "REPEATED_HANDSHAKE";
104
- CloseCodes[CloseCodes["DISABLED_PACKET"] = 4006] = "DISABLED_PACKET";
105
- CloseCodes[CloseCodes["MIDDLEWARE"] = 4007] = "MIDDLEWARE";
106
- CloseCodes[CloseCodes["MANUAL_SHUTDOWN"] = 4008] = "MANUAL_SHUTDOWN";
107
- })(CloseCodes || (exports.CloseCodes = CloseCodes = {}));
108
- function getClosureCause(id) {
109
- if (id >= 4000) {
110
- return CloseCodes[id] ?? 'UNKNOWN';
111
- }
112
- switch (id) {
113
- case 1000:
114
- return 'NORMAL_CLOSURE';
115
- case 1001:
116
- return 'GOING_AWAY';
117
- case 1002:
118
- return 'PROTOCOL_ERROR';
119
- case 1003:
120
- return 'UNSUPPORTED_DATA';
121
- case 1006:
122
- return 'ABNORMAL_CLOSURE';
123
- default:
124
- return 'UNKNOWN';
125
- }
126
- }
@@ -1,52 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright 2026 Lily (liwybloc)
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.MiddlewareHolder = void 0;
19
- class MiddlewareHolder {
20
- middlewares = [];
21
- addMiddleware(middleware) {
22
- this.middlewares.push(middleware);
23
- const m = middleware;
24
- try {
25
- if (typeof m.init === 'function')
26
- m.init(this);
27
- }
28
- catch (e) {
29
- console.warn('Middleware init threw an error:', e);
30
- }
31
- }
32
- async callMiddleware(method, ...values) {
33
- let cancelled = false;
34
- for (const middleware of this.middlewares) {
35
- const fn = middleware[method];
36
- if (!fn)
37
- continue;
38
- try {
39
- if (await fn(...values)) {
40
- cancelled = true;
41
- }
42
- }
43
- catch (e) {
44
- console.warn(`Middleware ${String(method)} threw an error:`, e);
45
- }
46
- }
47
- return cancelled;
48
- }
49
- }
50
- exports.MiddlewareHolder = MiddlewareHolder;
51
- ;
52
- ;
@@ -1,251 +0,0 @@
1
- "use strict";
2
- /*
3
- * Copyright 2026 Lily (liwybloc)
4
- *
5
- * Licensed under the Apache License, Version 2.0 (the "License");
6
- * you may not use this file except in compliance with the License.
7
- * You may obtain a copy of the License at
8
- *
9
- * http://www.apache.org/licenses/LICENSE-2.0
10
- *
11
- * Unless required by applicable law or agreed to in writing, software
12
- * distributed under the License is distributed on an "AS IS" BASIS,
13
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- * See the License for the specific language governing permissions and
15
- * limitations under the License.
16
- */
17
- Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.SonicWSCore = void 0;
19
- const PacketHolder_1 = require("../../util/packets/PacketHolder");
20
- const CompressionUtil_1 = require("../../util/packets/CompressionUtil");
21
- const PacketUtils_1 = require("../../util/packets/PacketUtils");
22
- const version_1 = require("../../../version");
23
- const Packets_1 = require("../../packets/Packets");
24
- const BatchHelper_1 = require("../../util/packets/BatchHelper");
25
- const BufferUtil_1 = require("../../util/BufferUtil");
26
- const Connection_1 = require("../../Connection");
27
- const StringUtil_1 = require("../../util/StringUtil");
28
- class SonicWSCore extends Connection_1.Connection {
29
- preListen;
30
- clientPackets = new PacketHolder_1.PacketHolder();
31
- serverPackets = new PacketHolder_1.PacketHolder();
32
- pastKeys = false;
33
- readyListeners = [];
34
- bufferHandler;
35
- _timers = {};
36
- asyncData = {};
37
- asyncMap = {};
38
- constructor(ws, bufferHandler, on, off) {
39
- super(ws, -1, "LocalSocket", on, off);
40
- this.socket = ws;
41
- this.preListen = {};
42
- this.invalidPacket = this.invalidPacket.bind(this);
43
- this.serverKeyHandler = this.serverKeyHandler.bind(this);
44
- this.messageHandler = this.messageHandler.bind(this);
45
- this._on('message', this.serverKeyHandler);
46
- this._on('close', () => {
47
- this.callMiddleware('onStatusChange', WebSocket.CLOSED);
48
- for (const [id, callback, shouldCall] of Object.values(this._timers)) {
49
- this.clearTimeout(id);
50
- if (shouldCall)
51
- callback(true);
52
- }
53
- for (const packet of this.clientPackets.getPackets()) {
54
- delete packet.lastSent[0];
55
- }
56
- for (const packet of this.serverPackets.getPackets()) {
57
- delete packet.lastReceived[0];
58
- }
59
- });
60
- this.bufferHandler = bufferHandler;
61
- }
62
- reading = false;
63
- readQueue = [];
64
- async serverKeyHandler(event) {
65
- if (this.reading)
66
- return this.readQueue.push(event);
67
- this.reading = true;
68
- const cdata = await this.bufferHandler(event);
69
- if (cdata.length < 3 || (0, StringUtil_1.as8String)(cdata.slice(0, 3)) != version_1.SERVER_SUFFIX) {
70
- this.close(1000);
71
- throw new Error("The server requested is not a Sonic WS server.");
72
- }
73
- const version = cdata[3];
74
- if (version != version_1.VERSION) {
75
- this.close(1000);
76
- throw new Error(`Version mismatch: ${version > version_1.VERSION ? "client" : "server"} is outdated (server: ${version}, client: ${version_1.VERSION})`);
77
- }
78
- const data = await (0, CompressionUtil_1.decompressGzip)(cdata.subarray(4, cdata.length));
79
- const [ckOff, id] = (0, CompressionUtil_1.readVarInt)(data, 0);
80
- this.id = id;
81
- const [valuesOff, ckLength] = (0, CompressionUtil_1.readVarInt)(data, ckOff);
82
- const ckData = data.subarray(valuesOff, valuesOff + ckLength);
83
- this.clientPackets.holdPackets(Packets_1.Packet.deserializeAll(ckData, true));
84
- const skData = data.subarray(valuesOff + ckLength, data.length);
85
- this.serverPackets.holdPackets(Packets_1.Packet.deserializeAll(skData, true));
86
- this.batcher.registerSendPackets(this.clientPackets, this);
87
- for (const p of this.serverPackets.getPackets()) {
88
- const key = this.serverPackets.getKey(p.tag);
89
- this.asyncMap[key] = p.async;
90
- if (p.async) {
91
- this.asyncData[key] = [false, []];
92
- }
93
- }
94
- Object.keys(this.preListen).forEach(tag => this.preListen[tag].forEach(listener => {
95
- // print the error to console without halting execution
96
- if (!this.serverPackets.hasTag(tag))
97
- return console.error(new Error(`The server does not send the packet with tag "${tag}"!`));
98
- this.listen(tag, listener);
99
- }));
100
- this.preListen = null; // clear
101
- this.pastKeys = true;
102
- this.readyListeners.forEach(l => l());
103
- this.readyListeners = null; // clear
104
- this._off('message', this.serverKeyHandler);
105
- this._on('message', this.messageHandler);
106
- this.readQueue.forEach(e => this.messageHandler(e));
107
- this.readQueue = [];
108
- }
109
- invalidPacket(listened) {
110
- console.error(listened);
111
- throw new Error("An error occured with data from the server!! This is probably my fault.. make an issue at https://github.com/liwybloc/sonic-ws");
112
- }
113
- listenLock = false;
114
- packetQueue = [];
115
- async listenPacket(data, tag, packetQueue, isAsync, asyncData) {
116
- const listeners = this.listeners[tag];
117
- if (!listeners)
118
- return console.warn("Warn: No listener for packet " + tag);
119
- await this.enqueuePacket(data, listeners, packetQueue, isAsync, asyncData);
120
- await this.callMiddleware('onReceive_post', tag, typeof data == 'string' ? [data] : data[0]);
121
- }
122
- isAsync(code) {
123
- return this.asyncMap[code];
124
- }
125
- async enqueuePacket(data, listeners, packetQueue, isAsync, asyncData) {
126
- await (0, PacketUtils_1.listenPacket)(data, listeners, this.invalidPacket);
127
- await this.triggerNextPacket(packetQueue, isAsync, asyncData);
128
- }
129
- async triggerNextPacket(packetQueue, isAsync, asyncData) {
130
- if (isAsync)
131
- asyncData[0] = false;
132
- else
133
- this.listenLock = false;
134
- if (packetQueue.length > 0) {
135
- this.dataHandler(packetQueue.shift());
136
- return;
137
- }
138
- }
139
- async dataHandler(data) {
140
- const key = data[0];
141
- const value = data.slice(1);
142
- const isAsync = this.isAsync(key);
143
- let locked;
144
- let packetQueue;
145
- let asyncData;
146
- if (isAsync) {
147
- asyncData = this.asyncData[key];
148
- locked = asyncData[0];
149
- packetQueue = asyncData[1];
150
- }
151
- else {
152
- locked = this.listenLock;
153
- packetQueue = this.packetQueue;
154
- }
155
- if (locked) {
156
- packetQueue.push(data);
157
- return;
158
- }
159
- if (isAsync)
160
- asyncData[0] = true;
161
- else
162
- this.listenLock = true;
163
- const tag = this.serverPackets.getTag(key);
164
- const packet = this.serverPackets.getPacket(tag);
165
- if (await this.callMiddleware('onReceive_pre', packet.tag, data, data.length))
166
- return;
167
- if (packet.rereference && value.length == 0) {
168
- if (packet.lastReceived[0] === undefined)
169
- return this.invalidPacket("No previous value to rereference");
170
- this.listenPacket(packet.lastReceived[0], tag, packetQueue, isAsync, asyncData);
171
- return;
172
- }
173
- if (packet.dataBatching == 0) {
174
- const res = packet.lastReceived[0] = await packet.listen(value, null);
175
- this.listenPacket(res, tag, packetQueue, isAsync, asyncData);
176
- return;
177
- }
178
- const batchData = await BatchHelper_1.BatchHelper.unravelBatch(packet, value, null);
179
- if (typeof batchData == 'string')
180
- return this.invalidPacket(batchData);
181
- batchData.forEach(data => this.listenPacket(data, tag, packetQueue, isAsync, asyncData));
182
- }
183
- async messageHandler(event) {
184
- const data = await this.bufferHandler(event);
185
- if (data.length < 1)
186
- return;
187
- await this.dataHandler(data);
188
- }
189
- listen(tag, listener) {
190
- if (!this.serverPackets.hasTag(tag)) {
191
- console.log("Tag is not available on server: " + tag);
192
- return;
193
- }
194
- (this.listeners[tag] ??= []).push(listener);
195
- }
196
- /**
197
- * Listens for all sent messages rawly
198
- * @param listener Callback for when data is received
199
- */
200
- raw_onsend(listener) {
201
- this.listeners.send.push(listener);
202
- }
203
- sendQueue = [false, [], undefined];
204
- /**
205
- * Sends a packet to the server
206
- * @param tag The tag of the packet
207
- * @param values The values to send
208
- */
209
- async send(tag, ...values) {
210
- if (await this.callMiddleware('onSend_pre', tag, values, Date.now(), performance.now()))
211
- return;
212
- const [code, data, packet] = await (0, PacketUtils_1.processPacket)(this.clientPackets, tag, values, this.sendQueue, 0);
213
- if (packet.dataBatching == 0)
214
- this.raw_send((0, BufferUtil_1.toPacketBuffer)(code, data));
215
- else
216
- this.batcher.batchPacket(code, data);
217
- await this.callMiddleware('onSend_post', tag, data, data.length);
218
- }
219
- /**
220
- * Listens for when the client connects
221
- * @param listener Callback on connection
222
- */
223
- on_ready(listener) {
224
- if (this.pastKeys)
225
- listener();
226
- else
227
- this.readyListeners.push(listener);
228
- }
229
- /**
230
- * Listens for when the client closes
231
- * @param listener Callback on close with close event
232
- */
233
- on_close(listener) {
234
- this._on("close", listener);
235
- }
236
- /**
237
- * Listens to a packet from the server
238
- * @param tag The tag to listen for
239
- * @param listener The callback with the values
240
- */
241
- on(tag, listener) {
242
- if (this.socket.readyState !== WebSocket.OPEN) {
243
- if (!this.preListen[tag])
244
- this.preListen[tag] = [];
245
- this.preListen[tag].push(listener);
246
- return;
247
- }
248
- this.listen(tag, listener);
249
- }
250
- }
251
- exports.SonicWSCore = SonicWSCore;