sonic-ws 1.3.2 → 1.3.3

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 (46) hide show
  1. package/dist/index.d.ts +0 -4
  2. package/dist/version.d.ts +1 -5
  3. package/dist/version.js +23 -4
  4. package/dist/ws/Connection.d.ts +0 -4
  5. package/dist/ws/Connection.js +124 -4
  6. package/dist/ws/PacketProcessor.d.ts +0 -4
  7. package/dist/ws/PacketProcessor.js +50 -4
  8. package/dist/ws/client/core/ClientCore.d.ts +0 -4
  9. package/dist/ws/client/core/ClientCore.js +249 -4
  10. package/dist/ws/client/node/ClientNode.d.ts +0 -4
  11. package/dist/ws/client/node/ClientNode.js +34 -4
  12. package/dist/ws/debug/DebugServer.d.ts +0 -4
  13. package/dist/ws/debug/DebugServer.js +605 -4
  14. package/dist/ws/packets/PacketProcessors.d.ts +0 -4
  15. package/dist/ws/packets/PacketProcessors.js +315 -4
  16. package/dist/ws/packets/PacketType.d.ts +0 -4
  17. package/dist/ws/packets/PacketType.js +59 -4
  18. package/dist/ws/packets/Packets.d.ts +0 -4
  19. package/dist/ws/packets/Packets.js +275 -4
  20. package/dist/ws/server/SonicWSConnection.d.ts +0 -4
  21. package/dist/ws/server/SonicWSConnection.js +296 -4
  22. package/dist/ws/server/SonicWSServer.d.ts +1 -5
  23. package/dist/ws/server/SonicWSServer.js +305 -4
  24. package/dist/ws/util/BufferUtil.d.ts +0 -4
  25. package/dist/ws/util/BufferUtil.js +40 -4
  26. package/dist/ws/util/StringUtil.d.ts +0 -4
  27. package/dist/ws/util/StringUtil.js +49 -4
  28. package/dist/ws/util/enums/EnumHandler.d.ts +0 -4
  29. package/dist/ws/util/enums/EnumHandler.js +58 -4
  30. package/dist/ws/util/enums/EnumType.d.ts +0 -4
  31. package/dist/ws/util/enums/EnumType.js +70 -4
  32. package/dist/ws/util/packets/BatchHelper.d.ts +0 -4
  33. package/dist/ws/util/packets/BatchHelper.js +83 -4
  34. package/dist/ws/util/packets/CompressionUtil.d.ts +5 -9
  35. package/dist/ws/util/packets/CompressionUtil.js +275 -4
  36. package/dist/ws/util/packets/HashUtil.d.ts +0 -4
  37. package/dist/ws/util/packets/HashUtil.js +120 -4
  38. package/dist/ws/util/packets/JSONUtil.d.ts +0 -4
  39. package/dist/ws/util/packets/JSONUtil.js +177 -4
  40. package/dist/ws/util/packets/PacketHolder.d.ts +0 -4
  41. package/dist/ws/util/packets/PacketHolder.js +124 -4
  42. package/dist/ws/util/packets/PacketUtils.d.ts +0 -4
  43. package/dist/ws/util/packets/PacketUtils.js +281 -4
  44. package/dist/ws/util/packets/RateHandler.d.ts +0 -4
  45. package/dist/ws/util/packets/RateHandler.js +64 -4
  46. package/package.json +3 -3
@@ -1,6 +1,179 @@
1
- /**
1
+ "use strict";
2
+ /*
2
3
  * Copyright 2026 Lily (liwybloc)
3
- * Licensed under the Apache License, Version 2.0.
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.
4
16
  */
5
-
6
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.decompressJSON=exports.compressJSON=void 0;const e=require("../BufferUtil"),r=require("./CompressionUtil");var t;!function(e){e[e.NULL=0]="NULL",e[e.BOOL=1]="BOOL",e[e.INT=2]="INT",e[e.FLOAT=3]="FLOAT",e[e.STRING=4]="STRING",e[e.ARRAY=5]="ARRAY",e[e.OBJECT=6]="OBJECT"}(t||(t={}));const s=e=>{const t=(new TextEncoder).encode(e);return[...(0,r.convertVarInt)(t.length),...t]},n=(e,t)=>{const[s,n]=(0,r.readVarInt)(e,t);return{value:(new TextDecoder).decode(e.subarray(s,s+n)),length:s+n-t}};exports.compressJSON=n=>{const o=[],c=[],a=[],u=e=>{if(null===e)a.push(t.NULL);else if("boolean"==typeof e)a.push(t.BOOL),o.push(e);else if(Number.isInteger(e))a.push(t.INT),c.push(...(0,r.convertVarInt)((0,r.mapZigZag)(e)));else if("number"==typeof e)a.push(t.FLOAT),c.push(...(0,r.convertFloat)(e));else if("string"==typeof e)a.push(t.STRING),c.push(...s(e));else if(Array.isArray(e)){a.push(t.ARRAY),c.push(...(0,r.convertVarInt)(e.length));for(const r of e)u(r)}else{if("object"!=typeof e)throw new Error("Unsupported type");{a.push(t.OBJECT);const n=Object.keys(e);c.push(...(0,r.convertVarInt)(n.length));for(const r of n)c.push(...s(r)),u(e[r])}}};u(n);const p=o.length?(0,e.splitArray)(o,8).map(e=>(0,r.compressBools)(e)):[],l=(e=>{let t="";for(const r of e)t+=r.toString(2).padStart(3,"0");return(0,r.bitsToBytes)(t)})(a),h=[...(0,r.convertVarInt)(p.length),...(0,r.convertVarInt)(l.length)];return Uint8Array.from([...h,...p.flat(),...l,...c])};exports.decompressJSON=e=>{let s=0;const[o,c]=(0,r.readVarInt)(e,s);s=o;const[a,u]=(0,r.readVarInt)(e,s);s=a;const p=[];for(let t=0;t<c;t++)p.push(...(0,r.decompressBools)(e[s++]));let l=0;const h=e.subarray(s,s+u);s+=u;const f=((e,t)=>{const s=(0,r.bytesToBits)(e),n=[];for(let e=0;e<t;e++)n.push(parseInt(s.slice(3*e,3*e+3),2));return n})(h,8*h.length/3);let i=0;const d=o=>{if(o>500)throw new Error("JSON array too deep.");const c=f[i++];switch(c){case t.NULL:return null;case t.BOOL:return p[l++];case t.INT:{const[t,n]=(0,r.readVarInt)(e,s);return s=t,(0,r.demapZigZag)(n)}case t.FLOAT:{const t=(0,r.deconvertFloat)(Array.from(e.subarray(s,s+4)));return s+=4,t}case t.STRING:{const{value:r,length:t}=n(e,s);return s+=t,r}case t.ARRAY:{const[t,n]=(0,r.readVarInt)(e,s);s=t;const c=[];for(let e=0;e<n;e++)c.push(d(o+1));return c}case t.OBJECT:{const[t,c]=(0,r.readVarInt)(e,s);s=t;const a={};for(let r=0;r<c;r++){const{value:r,length:t}=n(e,s);s+=t,a[r]=d(o+1)}return a}default:throw new Error(`Unknown type ${c}`)}};return d(0)};
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.decompressJSON = exports.compressJSON = void 0;
19
+ const BufferUtil_1 = require("../BufferUtil");
20
+ const CompressionUtil_1 = require("./CompressionUtil");
21
+ var JSONType;
22
+ (function (JSONType) {
23
+ JSONType[JSONType["NULL"] = 0] = "NULL";
24
+ JSONType[JSONType["BOOL"] = 1] = "BOOL";
25
+ JSONType[JSONType["INT"] = 2] = "INT";
26
+ JSONType[JSONType["FLOAT"] = 3] = "FLOAT";
27
+ JSONType[JSONType["STRING"] = 4] = "STRING";
28
+ JSONType[JSONType["ARRAY"] = 5] = "ARRAY";
29
+ JSONType[JSONType["OBJECT"] = 6] = "OBJECT";
30
+ })(JSONType || (JSONType = {}));
31
+ const encodeString = (str) => {
32
+ const encoder = new TextEncoder();
33
+ const data = encoder.encode(str);
34
+ return [...(0, CompressionUtil_1.convertVarInt)(data.length), ...data];
35
+ };
36
+ const decodeString = (bytes, offset) => {
37
+ const [off, len] = (0, CompressionUtil_1.readVarInt)(bytes, offset);
38
+ const decoder = new TextDecoder();
39
+ return { value: decoder.decode(bytes.subarray(off, off + len)), length: off + len - offset };
40
+ };
41
+ // utility: pack 3-bit values into bytes
42
+ const packTypeBits = (types) => {
43
+ let bits = '';
44
+ for (const t of types)
45
+ bits += t.toString(2).padStart(3, '0');
46
+ return (0, CompressionUtil_1.bitsToBytes)(bits);
47
+ };
48
+ // utility: unpack bytes into 3-bit type array
49
+ const unpackTypeBits = (bytes, totalValues) => {
50
+ const bitStr = (0, CompressionUtil_1.bytesToBits)(bytes);
51
+ const types = [];
52
+ for (let i = 0; i < totalValues; i++) {
53
+ types.push(parseInt(bitStr.slice(i * 3, i * 3 + 3), 2));
54
+ }
55
+ return types;
56
+ };
57
+ // main compression
58
+ const compressJSON = (value) => {
59
+ const bools = [];
60
+ const payload = [];
61
+ const typeList = [];
62
+ const encodeValue = (val) => {
63
+ if (val === null) {
64
+ typeList.push(JSONType.NULL);
65
+ }
66
+ else if (typeof val === 'boolean') {
67
+ typeList.push(JSONType.BOOL);
68
+ bools.push(val);
69
+ }
70
+ else if (Number.isInteger(val)) {
71
+ typeList.push(JSONType.INT);
72
+ payload.push(...(0, CompressionUtil_1.convertVarInt)((0, CompressionUtil_1.mapZigZag)(val)));
73
+ }
74
+ else if (typeof val === 'number') {
75
+ typeList.push(JSONType.FLOAT);
76
+ payload.push(...(0, CompressionUtil_1.convertFloat)(val));
77
+ }
78
+ else if (typeof val === 'string') {
79
+ typeList.push(JSONType.STRING);
80
+ payload.push(...encodeString(val));
81
+ }
82
+ else if (Array.isArray(val)) {
83
+ typeList.push(JSONType.ARRAY);
84
+ payload.push(...(0, CompressionUtil_1.convertVarInt)(val.length));
85
+ for (const item of val)
86
+ encodeValue(item);
87
+ }
88
+ else if (typeof val === 'object') {
89
+ typeList.push(JSONType.OBJECT);
90
+ const keys = Object.keys(val);
91
+ payload.push(...(0, CompressionUtil_1.convertVarInt)(keys.length));
92
+ for (const key of keys) {
93
+ payload.push(...encodeString(key));
94
+ encodeValue(val[key]);
95
+ }
96
+ }
97
+ else {
98
+ throw new Error('Unsupported type');
99
+ }
100
+ };
101
+ encodeValue(value);
102
+ // boolean bitmap bytes
103
+ const boolBytes = bools.length
104
+ ? (0, BufferUtil_1.splitArray)(bools, 8).map((slice) => (0, CompressionUtil_1.compressBools)(slice))
105
+ : [];
106
+ // type map bytes (3-bit per value)
107
+ const typeBytes = packTypeBits(typeList);
108
+ // prepend lengths of boolBytes and typeBytes as varints
109
+ const header = [...(0, CompressionUtil_1.convertVarInt)(boolBytes.length), ...(0, CompressionUtil_1.convertVarInt)(typeBytes.length)];
110
+ return Uint8Array.from([...header, ...boolBytes.flat(), ...typeBytes, ...payload]);
111
+ };
112
+ exports.compressJSON = compressJSON;
113
+ // decompression
114
+ const decompressJSON = (bytes) => {
115
+ let offset = 0;
116
+ // read lengths
117
+ const [off1, boolByteLen] = (0, CompressionUtil_1.readVarInt)(bytes, offset);
118
+ offset = off1;
119
+ const [off2, typeByteLen] = (0, CompressionUtil_1.readVarInt)(bytes, offset);
120
+ offset = off2;
121
+ // boolean bitmap
122
+ const boolStream = [];
123
+ for (let i = 0; i < boolByteLen; i++) {
124
+ boolStream.push(...(0, CompressionUtil_1.decompressBools)(bytes[offset++]));
125
+ }
126
+ let boolIndex = 0;
127
+ // type map
128
+ const typeBytes = bytes.subarray(offset, offset + typeByteLen);
129
+ offset += typeByteLen;
130
+ const typeList = unpackTypeBits(typeBytes, typeBytes.length * 8 / 3); // overestimate, will only use while decoding
131
+ let typeIndex = 0;
132
+ const decodeValue = (depth) => {
133
+ if (depth > 500)
134
+ throw new Error("JSON array too deep.");
135
+ const type = typeList[typeIndex++];
136
+ switch (type) {
137
+ case JSONType.NULL: return null;
138
+ case JSONType.BOOL: return boolStream[boolIndex++];
139
+ case JSONType.INT: {
140
+ const [off, n] = (0, CompressionUtil_1.readVarInt)(bytes, offset);
141
+ offset = off;
142
+ return (0, CompressionUtil_1.demapZigZag)(n);
143
+ }
144
+ case JSONType.FLOAT: {
145
+ const val = (0, CompressionUtil_1.deconvertFloat)(Array.from(bytes.subarray(offset, offset + 4)));
146
+ offset += 4;
147
+ return val;
148
+ }
149
+ case JSONType.STRING: {
150
+ const { value, length } = decodeString(bytes, offset);
151
+ offset += length;
152
+ return value;
153
+ }
154
+ case JSONType.ARRAY: {
155
+ const [off, len] = (0, CompressionUtil_1.readVarInt)(bytes, offset);
156
+ offset = off;
157
+ const arr = [];
158
+ for (let i = 0; i < len; i++)
159
+ arr.push(decodeValue(depth + 1));
160
+ return arr;
161
+ }
162
+ case JSONType.OBJECT: {
163
+ const [off, numKeys] = (0, CompressionUtil_1.readVarInt)(bytes, offset);
164
+ offset = off;
165
+ const obj = {};
166
+ for (let i = 0; i < numKeys; i++) {
167
+ const { value: key, length: keyLen } = decodeString(bytes, offset);
168
+ offset += keyLen;
169
+ obj[key] = decodeValue(depth + 1);
170
+ }
171
+ return obj;
172
+ }
173
+ default:
174
+ throw new Error(`Unknown type ${type}`);
175
+ }
176
+ };
177
+ return decodeValue(0);
178
+ };
179
+ exports.decompressJSON = decompressJSON;
@@ -1,5 +1 @@
1
- /**
2
- * Copyright 2026 Lily (liwybloc)
3
- * Licensed under the Apache License, Version 2.0.
4
- */
5
1
  export {};
@@ -1,6 +1,126 @@
1
- /**
1
+ "use strict";
2
+ /*
2
3
  * Copyright 2026 Lily (liwybloc)
3
- * Licensed under the Apache License, Version 2.0.
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.PacketHolder = void 0;
19
+ /**
20
+ * Holds and maps packets to indexed keys and tags for serialization and lookup
21
+ * @internal
4
22
  */
5
-
6
- 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()}};
23
+ class PacketHolder {
24
+ /** Current key index for packet tags */
25
+ key;
26
+ /** Maps tags to keys */
27
+ keys;
28
+ /** Maps keys to tags */
29
+ tags;
30
+ /** Maps tags to packet instances */
31
+ packetMap;
32
+ /** List of all packet instances */
33
+ packets;
34
+ /**
35
+ * Creates a new PacketHolder with an array of packets
36
+ * @param packets Array of packets to register
37
+ */
38
+ constructor(packets) {
39
+ // reserves:
40
+ // 0 - enum update
41
+ this.key = 1;
42
+ this.keys = {};
43
+ this.tags = {};
44
+ this.packetMap = {};
45
+ if (!packets)
46
+ return;
47
+ this.holdPackets(packets);
48
+ }
49
+ /** Assigns a new unique key to a tag */
50
+ createKey(tag) {
51
+ this.keys[tag] = this.key;
52
+ this.tags[this.key] = tag;
53
+ this.key++;
54
+ }
55
+ /**
56
+ * Registers an array of packets and assigns them keys
57
+ * @param packets Array of packets to register
58
+ */
59
+ holdPackets(packets) {
60
+ this.packets = packets;
61
+ for (const packet of packets)
62
+ this.createKey(packet.tag), this.packetMap[packet.tag] = packet;
63
+ }
64
+ /**
65
+ * Returns the numeric key for a given tag
66
+ * @param tag The packet tag
67
+ */
68
+ getKey(tag) {
69
+ if (!(tag in this.keys))
70
+ throw new Error(`Not a valid tag: ${tag}`);
71
+ return this.keys[tag];
72
+ }
73
+ /**
74
+ * Returns the tag associated with a given character key
75
+ * @param key Key bytre
76
+ */
77
+ getTag(key) {
78
+ if (!(key in this.tags))
79
+ return undefined;
80
+ return this.tags[key];
81
+ }
82
+ /**
83
+ * Returns the packet instance associated with a tag
84
+ * @param tag The packet tag
85
+ */
86
+ getPacket(tag) {
87
+ if (!(tag in this.packetMap))
88
+ throw new Error("Unknown packet tag: " + tag);
89
+ return this.packetMap[tag];
90
+ }
91
+ /**
92
+ * Checks if a given character key exists
93
+ * @param key A string index
94
+ */
95
+ hasKey(key) {
96
+ return key in this.tags;
97
+ }
98
+ /**
99
+ * Checks if a tag has been assigned a key
100
+ * @param tag The packet tag
101
+ */
102
+ hasTag(tag) {
103
+ return tag in this.keys;
104
+ }
105
+ /** Returns the mapping of tags to keys */
106
+ getKeys() {
107
+ return this.keys;
108
+ }
109
+ /** Returns the mapping of keys to tags */
110
+ getTagMap() {
111
+ return this.tags;
112
+ }
113
+ /** Returns an array of all registered tags */
114
+ getTags() {
115
+ return Object.values(this.tags);
116
+ }
117
+ /** Returns the list of all registered packets */
118
+ getPackets() {
119
+ return this.packets;
120
+ }
121
+ /** Serializes all registered packets into a string */
122
+ serialize() {
123
+ return this.packets.map(p => p.serialize()).flat();
124
+ }
125
+ }
126
+ exports.PacketHolder = PacketHolder;
@@ -1,7 +1,3 @@
1
- /**
2
- * Copyright 2026 Lily (liwybloc)
3
- * Licensed under the Apache License, Version 2.0.
4
- */
5
1
  import { ConvertType, Packet, ValidatorFunction } from "../../packets/Packets";
6
2
  import { PacketType } from "../../packets/PacketType";
7
3
  import { EnumPackage } from "../enums/EnumType";
@@ -1,6 +1,283 @@
1
- /**
1
+ "use strict";
2
+ /*
2
3
  * Copyright 2026 Lily (liwybloc)
3
- * Licensed under the Apache License, Version 2.0.
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.processPacket = processPacket;
19
+ exports.listenPacket = listenPacket;
20
+ exports.CreatePacket = CreatePacket;
21
+ exports.CreateObjPacket = CreateObjPacket;
22
+ exports.CreateEnumPacket = CreateEnumPacket;
23
+ exports.CreateKeyEffective = CreateKeyEffective;
24
+ exports.FlattenData = FlattenData;
25
+ exports.UnFlattenData = UnFlattenData;
26
+ const Packets_1 = require("../../packets/Packets");
27
+ const PacketType_1 = require("../../packets/PacketType");
28
+ const EnumType_1 = require("../enums/EnumType");
29
+ const CompressionUtil_1 = require("./CompressionUtil");
30
+ const HashUtil_1 = require("./HashUtil");
31
+ /**
32
+ * Processes and verifies values into a sendable format
33
+ * @param packets Packet holder
34
+ * @param tag The tag of the packet
35
+ * @param values The values
36
+ * @returns The indexed code, the data, and the packet schema
37
+ * @internal
38
+ */
39
+ async function processPacket(packets, tag, values, sendQueue, id, force = false) {
40
+ const code = packets.getKey(tag);
41
+ const packet = packets.getPacket(tag);
42
+ return handleQueue(sendQueue, packets, id, tag, values, force, async () => {
43
+ if (packet.rereference) {
44
+ if (id === -1)
45
+ throw new Error("Cannot send a re-referenced packet from the server-wide sender!");
46
+ const serialized = (0, HashUtil_1.hashValue)(values);
47
+ if (packet.lastSent[id] === serialized) {
48
+ return [code, CompressionUtil_1.EMPTY_UINT8, packet];
49
+ }
50
+ packet.lastSent[id] = serialized;
51
+ }
52
+ if (packet.autoFlatten) {
53
+ values = FlattenData(values[0]);
54
+ }
55
+ else {
56
+ if (values.length > packet.maxSize)
57
+ throw new Error(`Packet "${tag}" only allows ${packet.maxSize} values!`);
58
+ if (values.length < packet.minSize)
59
+ throw new Error(`Packet "${tag}" requires at least ${packet.minSize} values!`);
60
+ }
61
+ if (!packet.object) {
62
+ if (packet.type !== PacketType_1.PacketType.JSON) {
63
+ const found = values.find(v => typeof v === 'object' && v != null);
64
+ if (found)
65
+ console.warn(`Passing an array will result in undefined behavior (${JSON.stringify(found)}). Spread the array with ...arr`);
66
+ }
67
+ }
68
+ else {
69
+ values = values.map(x => !Array.isArray(x) ? [x] : x);
70
+ if (!packet.autoFlatten) {
71
+ const dataMins = packet.dataMin;
72
+ const dataMaxes = packet.dataMax;
73
+ for (let i = 0; i < dataMins.length; i++) {
74
+ if (values[i].length < dataMins[i])
75
+ throw new Error(`Section ${i + 1} of packet "${tag}" requires at least ${dataMins[i]} values!`);
76
+ if (values[i].length > dataMaxes[i])
77
+ throw new Error(`Section ${i + 1} of packet "${tag}" only allows ${dataMaxes[i]} values!`);
78
+ }
79
+ }
80
+ }
81
+ const sendData = values.length > 0 ? await packet.processSend(values) : CompressionUtil_1.EMPTY_UINT8;
82
+ return [code, sendData, packet];
83
+ });
84
+ }
85
+ /**
86
+ * @internal
87
+ */
88
+ async function handleQueue(sendQueue, packets, id, tag, values, force, fn) {
89
+ if (sendQueue[0] && !force) {
90
+ return new Promise((resolve) => sendQueue[1].push([resolve, tag, values]));
91
+ }
92
+ sendQueue[0] = true;
93
+ const result = await fn();
94
+ if (sendQueue[1].length > 0) {
95
+ const [resolve, nextTag, nextValues] = sendQueue[1].shift();
96
+ queueMicrotask(async () => {
97
+ resolve(await processPacket(packets, nextTag, nextValues, sendQueue, id, true));
98
+ });
99
+ }
100
+ else {
101
+ sendQueue[0] = false;
102
+ }
103
+ return result;
104
+ }
105
+ /**
106
+ * Calls the listener for a packet with error callback
107
+ * @param listened The listened data
108
+ * @param listeners The listeners to run
109
+ * @param errorCB The callback if something goes wrong
110
+ * @internal
111
+ */
112
+ async function listenPacket(listened, listeners, errorCB) {
113
+ if (typeof listened === 'string')
114
+ return errorCB(listened);
115
+ const [processed, flatten] = listened;
116
+ try {
117
+ if (flatten && Array.isArray(processed)) {
118
+ for (const l of listeners) {
119
+ await l(...processed);
120
+ }
121
+ }
122
+ else {
123
+ for (const l of listeners) {
124
+ await l(processed);
125
+ }
126
+ }
127
+ }
128
+ catch (err) {
129
+ console.error(err);
130
+ errorCB(err);
131
+ }
132
+ }
133
+ /**
134
+ * Determines if a type is a invalid packet type
135
+ * @param type A possible type
136
+ * @internal
137
+ */
138
+ function isInvalidType(type) {
139
+ return (!(typeof type == 'number' && type in PacketType_1.PacketType) && !(type instanceof EnumType_1.EnumPackage)) || type == PacketType_1.PacketType.KEY_EFFECTIVE;
140
+ }
141
+ const MAX_DATA_MAX = 2048383;
142
+ /** Clamps data max between 0 and MAX_DATA_MAX @internal */
143
+ function clampDataMax(dataMax) {
144
+ if (dataMax < 0) {
145
+ console.warn(`Having a data maximum below 0 does not do anything!`);
146
+ return 0;
147
+ }
148
+ // dfkjgsdkfgjk
149
+ if (dataMax > MAX_DATA_MAX) {
150
+ console.warn(`Only ${MAX_DATA_MAX} values can be sent on a type! Uhh make an issue if you want to send more.`);
151
+ return MAX_DATA_MAX;
152
+ }
153
+ return dataMax;
154
+ }
155
+ /** Clamps data min between 0 and datamax @internal */
156
+ function clampDataMin(dataMin, dataMax) {
157
+ if (dataMin < 0) {
158
+ console.warn(`Having a data minimum below 0 does not do anything!`);
159
+ return 0;
160
+ }
161
+ // also catches >MAX_DATA_MAX
162
+ if (dataMin > dataMax) {
163
+ console.warn(`Data minimum can not be higher than the data maximum!`);
164
+ return dataMax;
165
+ }
166
+ return dataMin;
167
+ }
168
+ /**
169
+ * Creates a structure for a simple single-typed packet.
170
+ * This packet can be sent and received with the specified tag, type, and data cap.
171
+ * @param settings The settings object containing `tag`, `type`, `dataMax`, `dataMin`, `noDataRange`, `dontSpread`, `validator`, `dataBatching`, and/or `maxBatchSize`.
172
+ * @returns The constructed packet structure data.
173
+ * @throws {Error} If the `type` is invalid.
174
+ */
175
+ function CreatePacket(settings) {
176
+ let { tag, type = PacketType_1.PacketType.NONE, dataMax = 1, dataMin = 1, noDataRange = false, dontSpread = false, validator = null, dataBatching = 0, maxBatchSize = 10, rateLimit = 0, enabled = true, async = false, gzipCompression = type == PacketType_1.PacketType.JSON, rereference = false } = settings;
177
+ if (!tag)
178
+ throw new Error("Tag not selected!");
179
+ if (noDataRange) {
180
+ dataMin = rereference ? 1 : 0;
181
+ dataMax = MAX_DATA_MAX;
182
+ }
183
+ else if (dataMin == undefined)
184
+ dataMin = type == PacketType_1.PacketType.NONE ? 0 : dataMax;
185
+ if (rereference && dataMin == 0)
186
+ throw new Error("Rereference cannot be true if the dataMin is 0");
187
+ if (isInvalidType(type)) {
188
+ throw new Error(`Invalid packet type: ${type}`);
189
+ }
190
+ const schema = new Packets_1.PacketSchema(false, type, async, clampDataMin(dataMin, dataMax), clampDataMax(dataMax), rateLimit, dontSpread, false, rereference, dataBatching, maxBatchSize, gzipCompression);
191
+ return new Packets_1.Packet(tag, schema, validator, enabled, false);
192
+ }
193
+ /**
194
+ * Creates a structure for an object (multi-typed) packet.
195
+ * This packet allows multiple types and their associated data caps.
196
+ * @param settings The settings object containing `tag`, `types`, `dataMaxes`, `dataMins`, `noDataRange`, `dontSpread`, `autoFlatten`, `largePacket`, `validator`, `dataBatching`, and/or `maxBatchSize`.
197
+ * @returns The constructed packet structure data.
198
+ * @throws {Error} If any type in `types` is invalid.
199
+ */
200
+ function CreateObjPacket(settings) {
201
+ let { tag, types = [], dataMaxes, dataMins, noDataRange = false, dontSpread = false, autoFlatten = false, validator = null, dataBatching = 0, maxBatchSize = 10, rateLimit = 0, enabled = true, async = false, gzipCompression = types && types.includes(PacketType_1.PacketType.JSON) } = settings;
202
+ if (!tag)
203
+ throw new Error("Tag not selected!");
204
+ if (!types || types.length == 0)
205
+ throw new Error("Types is set to 0 length");
206
+ for (const type of types) {
207
+ if (!isInvalidType(type))
208
+ continue;
209
+ throw new Error(`Invalid packet type in "${tag}" packet: ${type}`);
210
+ }
211
+ if (noDataRange) {
212
+ dataMaxes = Array.from({ length: types.length }).map(() => MAX_DATA_MAX);
213
+ dataMins = Array.from({ length: types.length }).map(() => 0);
214
+ }
215
+ else {
216
+ if (dataMaxes == undefined)
217
+ dataMaxes = Array.from({ length: types.length }).map(() => 1);
218
+ else if (!Array.isArray(dataMaxes))
219
+ dataMaxes = Array.from({ length: types.length }).map(() => dataMaxes);
220
+ if (dataMins == undefined)
221
+ dataMins = Array.from({ length: types.length }).map((_, i) => dataMaxes[i]);
222
+ else if (!Array.isArray(dataMins))
223
+ dataMins = Array.from({ length: types.length }).map(() => dataMins);
224
+ }
225
+ const clampedDataMaxes = dataMaxes.map(clampDataMax);
226
+ const clampedDataMins = dataMins.map((m, i) => types[i] == PacketType_1.PacketType.NONE ? 0 : clampDataMin(m, clampedDataMaxes[i]));
227
+ const schema = new Packets_1.PacketSchema(true, types, async, clampedDataMins, clampedDataMaxes, rateLimit, dontSpread, autoFlatten, false, dataBatching, maxBatchSize, gzipCompression);
228
+ return new Packets_1.Packet(tag, schema, validator, enabled, false);
229
+ }
230
+ /**
231
+ * Creates and defines an enum packet. This can be used to create an enum-based packet
232
+ * with a specific tag and possible values.
233
+ * @param settings The settings object containing `tag`, `enumTag`, `values`, `dataMax`, `dataMin`, `noDataRange`, `dontSpread`, `validator`, `dataBatching`, and/or `maxBatchSize`.
234
+ * @returns The constructed packet structure data.
235
+ */
236
+ function CreateEnumPacket(settings) {
237
+ const { tag, enumData, dataMax = 1, dataMin = 0, noDataRange = false, dontSpread = false, validator = null, dataBatching = 0, maxBatchSize = 10, rateLimit = 0, enabled = true, async = false } = settings;
238
+ return CreatePacket({
239
+ tag: tag,
240
+ type: enumData,
241
+ dataMax,
242
+ dataMin,
243
+ noDataRange,
244
+ dontSpread,
245
+ validator,
246
+ dataBatching,
247
+ maxBatchSize,
248
+ rateLimit,
249
+ enabled,
250
+ async,
251
+ });
252
+ }
253
+ function CreateKeyEffective(settings) {
254
+ const { tag, count = 2, validator = null, async = false } = settings;
255
+ if (!tag)
256
+ throw new Error("Tag not selected!");
257
+ if (count < 2)
258
+ throw new Error("Must have at least 2 key consumptions on key effective packet!");
259
+ throw new Error("Currently W.I.P.");
260
+ }
261
+ /**
262
+ * Flattens a 2-depth array for efficient wire transfer
263
+ * Turns [[x,y,z],[x,y,z]...] to [[x,x...],[y,y...],[z,z...]]
264
+ * @param array A 2-depth array of multi-valued
265
+ */
266
+ function FlattenData(arr) {
267
+ if (arr == null)
268
+ return [];
269
+ const setup = arr[0];
270
+ if (setup == null)
271
+ return [];
272
+ if (!Array.isArray(setup))
273
+ throw new Error(`Cannot flatten array: ${arr}`);
274
+ return setup.map((_, i) => arr.map(row => row[i])) ?? [];
275
+ }
276
+ /**
277
+ * Unflattens an array into 2-depth; reverse of FlattenData()
278
+ * turns [[x,x...],[y,y...],[z,z...]] to [[x,y,z],[x,y,z]...]
279
+ * @param array A flattened array
4
280
  */
5
-
6
- Object.defineProperty(exports,"__esModule",{value:!0}),exports.processPacket=o,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=u,exports.CreateObjPacket=function(a){let{tag:n,types:r=[],dataMaxes:o,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(i(e))throw new Error(`Invalid packet type in "${n}" packet: ${e}`);f?(o=Array.from({length:r.length}).map(()=>s),u=Array.from({length:r.length}).map(()=>0)):(null==o?o=Array.from({length:r.length}).map(()=>1):Array.isArray(o)||(o=Array.from({length:r.length}).map(()=>o)),null==u?u=Array.from({length:r.length}).map((e,t)=>o[t]):Array.isArray(u)||(u=Array.from({length:r.length}).map(()=>u)));const E=o.map(c),S=u.map((e,a)=>r[a]==t.PacketType.NONE?0:l(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:l=10,rateLimit:f=0,enabled:p=!0,async:h=!1}=e;return u({tag:t,type:a,dataMax:n,dataMin:r,noDataRange:o,dontSpread:i,validator:s,dataBatching:c,maxBatchSize:l,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=f,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");async function o(e,a,i,s,c,l=!1){const u=e.getKey(a),p=e.getPacket(a);return async function(e,t,a,n,r,i,s){if(e[0]&&!i)return new Promise(t=>e[1].push([t,n,r]));e[0]=!0;const c=await s();if(e[1].length>0){const[n,r,i]=e[1].shift();queueMicrotask(async()=>{n(await o(t,r,i,e,a,!0))})}else e[0]=!1;return c}(s,e,c,a,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[u,n.EMPTY_UINT8,p];p.lastSent[c]=e}if(p.autoFlatten)i=f(i[0]);else{if(i.length>p.maxSize)throw new Error(`Packet "${a}" only allows ${p.maxSize} values!`);if(i.length<p.minSize)throw new Error(`Packet "${a}" 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 n=0;n<e.length;n++){if(i[n].length<e[n])throw new Error(`Section ${n+1} of packet "${a}" requires at least ${e[n]} values!`);if(i[n].length>t[n])throw new Error(`Section ${n+1} of packet "${a}" only allows ${t[n]} 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[u,e,p]})}function i(e){return!(("number"==typeof e&&e in t.PacketType||e instanceof a.EnumPackage)&&e!=t.PacketType.KEY_EFFECTIVE)}const s=2048383;function c(e){return e<0?(console.warn("Having a data maximum below 0 does not do anything!"),0):e>s?(console.warn(`Only ${s} values can be sent on a type! Uhh make an issue if you want to send more.`),s):e}function l(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 u(a){let{tag:n,type:r=t.PacketType.NONE,dataMax:o=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,o=s):null==u&&(u=r==t.PacketType.NONE?0:o),P&&0==u)throw new Error("Rereference cannot be true if the dataMin is 0");if(i(r))throw new Error(`Invalid packet type: ${r}`);const E=new e.PacketSchema(!1,r,g,l(u,o),c(o),d,p,!1,P,y,m,k);return new e.Packet(n,E,h,w,!1)}function f(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]))??[]}
281
+ function UnFlattenData(arr) {
282
+ return arr[0]?.map((_, i) => arr.map(col => col[i])) ?? [];
283
+ }
@@ -1,5 +1 @@
1
- /**
2
- * Copyright 2026 Lily (liwybloc)
3
- * Licensed under the Apache License, Version 2.0.
4
- */
5
1
  export {};