@zardoy/flying-squid 0.0.114 → 0.0.116

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/dist/index.js CHANGED
@@ -158,7 +158,7 @@ class MCServer extends events_1.EventEmitter {
158
158
  };
159
159
  patchServer(server);
160
160
  const promises = [];
161
- const coreModules = ['utils', 'communication', 'tick', 'settings', 'commands', 'tabComplete'];
161
+ const coreModules = ['utils', 'communication', 'tick', 'settings', 'commands', 'tabComplete', 'log'];
162
162
  server.modules = builtinModules.builtinPlugins;
163
163
  // Sort modules so core modules are first in specified order
164
164
  const sortedModules = {};
@@ -11,7 +11,7 @@ const server = function (serv) {
11
11
  if (whitelist.type === 'player')
12
12
  whitelist = [whitelist];
13
13
  // Log the broadcast message
14
- serv.log(`[${serv.color.blue}SERVER BROADCAST${serv.color.reset}]: ${message}`);
14
+ serv.log(`[SERVER BROADCAST]: ${message}`);
15
15
  whitelist.filter(w => blacklist.indexOf(w) === -1).forEach(player => {
16
16
  if (!system)
17
17
  player.chat(message);
@@ -31,13 +31,18 @@ const server = (serv, options) => {
31
31
  const isValidResponse = (obj) => {
32
32
  return typeof obj === 'object' && obj !== null &&
33
33
  typeof obj.requestId === 'number' &&
34
- Array.isArray(obj.entityIds) &&
35
- obj.entityIds.every(id => typeof id === 'number');
34
+ Array.isArray(obj.entities) &&
35
+ obj.entities.every((entity) => typeof entity === 'object' && entity !== null &&
36
+ typeof entity.entityId === 'number' &&
37
+ typeof entity.position === 'object' && entity.position !== null &&
38
+ typeof entity.position.x === 'number' &&
39
+ typeof entity.position.y === 'number' &&
40
+ typeof entity.position.z === 'number');
36
41
  };
37
42
  if (!isValidResponse(parsed)) {
38
43
  throw new Error('Invalid response format');
39
44
  }
40
- const { requestId, entityIds } = parsed;
45
+ const { requestId, entities } = parsed;
41
46
  // Verify this is a response to our last request
42
47
  const lastRequest = module.lastSyncRequests.get(player.uuid);
43
48
  if (!lastRequest || lastRequest.requestId !== requestId) {
@@ -48,7 +53,7 @@ const server = (serv, options) => {
48
53
  player._client.latency = latency;
49
54
  // Clean up the request
50
55
  module.lastSyncRequests.delete(player.uuid);
51
- const trackedIds = new Set(entityIds);
56
+ const trackedIds = new Set(entities.map(e => e.entityId));
52
57
  const expectedIds = new Set();
53
58
  // Find entities that should be visible to the player
54
59
  for (const entity of Object.values(serv.entities)) {
@@ -64,6 +69,38 @@ const server = (serv, options) => {
64
69
  expectedIds.add(entity.id);
65
70
  }
66
71
  }
72
+ // Check position deltas and send teleport packets if needed
73
+ for (const clientEntity of entities) {
74
+ const entity = serv.entities[clientEntity.entityId];
75
+ if (!entity)
76
+ continue;
77
+ // Calculate position delta
78
+ const deltaX = Math.abs(entity.position.x - clientEntity.position.x);
79
+ const deltaY = Math.abs(entity.position.y - clientEntity.position.y);
80
+ const deltaZ = Math.abs(entity.position.z - clientEntity.position.z);
81
+ const maxDelta = Math.max(deltaX, deltaY, deltaZ);
82
+ // If delta is more than 3 blocks, send entity_teleport packet
83
+ if (maxDelta > 3) {
84
+ serv.warn(`Player ${player.username} entity ${clientEntity.entityId} position desync (delta: ${maxDelta.toFixed(2)}), sending teleport... (ping: ${latency}ms)`);
85
+ // Send entity_teleport packet to sync position
86
+ let entityPosition;
87
+ if (serv.supportFeature('fixedPointPosition')) {
88
+ entityPosition = entity.position.scaled(32).floored();
89
+ }
90
+ else if (serv.supportFeature('doublePosition')) {
91
+ entityPosition = entity.position;
92
+ }
93
+ player.writePacket('entity_teleport', {
94
+ entityId: entity.id,
95
+ x: entityPosition.x,
96
+ y: entityPosition.y,
97
+ z: entityPosition.z,
98
+ yaw: entity.yaw,
99
+ pitch: entity.pitch,
100
+ onGround: entity.onGround
101
+ });
102
+ }
103
+ }
67
104
  // Find missing entities
68
105
  for (const entityId of expectedIds) {
69
106
  if (!trackedIds.has(entityId)) {
@@ -18,5 +18,13 @@ declare global {
18
18
  interface Options {
19
19
  /** Whether to redirect console.log output to server log file. Defaults to true. */
20
20
  noConsoleLogRedirect?: boolean;
21
+ logging?: boolean | string;
22
+ /** Whether to clear the log file when server starts. Defaults to false. */
23
+ clearLogOnStart?: boolean;
24
+ /**
25
+ * Maximum log file size in MB before rotation. When exceeded, keeps 70% of recent lines.
26
+ * @default 30
27
+ */
28
+ maxLogFileSize?: number;
21
29
  }
22
30
  }
@@ -76,6 +76,29 @@ const server = function (serv, settings) {
76
76
  // Initialize log streams
77
77
  let logStream = null;
78
78
  let logPath = null;
79
+ // Log file size management
80
+ const checkLogFileSize = () => {
81
+ if (!logPath)
82
+ return;
83
+ const maxSize = settings.maxLogFileSize ?? 30; // Default to 30MB
84
+ if (!maxSize)
85
+ return;
86
+ try {
87
+ const stats = fs_1.default.statSync(logPath);
88
+ const fileSizeMB = stats.size / (1024 * 1024); // Convert to MB
89
+ if (fileSizeMB > maxSize) {
90
+ // Rotate log file by removing old lines
91
+ const lines = fs_1.default.readFileSync(logPath, 'utf8').split('\n');
92
+ const linesToKeep = Math.floor(lines.length * 0.7); // Keep 70% of lines
93
+ const newContent = lines.slice(-linesToKeep).join('\n');
94
+ fs_1.default.writeFileSync(logPath, newContent);
95
+ serv.info(`Log file rotated: ${fileSizeMB.toFixed(2)}MB -> ${(fs_1.default.statSync(logPath).size / (1024 * 1024)).toFixed(2)}MB`);
96
+ }
97
+ }
98
+ catch (err) {
99
+ serv.warn(`Failed to check log file size: ${err.message}`);
100
+ }
101
+ };
79
102
  // Setup logging if enabled
80
103
  if (settings.logging) {
81
104
  try {
@@ -98,6 +121,18 @@ const server = function (serv, settings) {
98
121
  if (logPath) {
99
122
  // Ensure directory exists
100
123
  fs_1.default.mkdirSync(path_1.default.dirname(logPath), { recursive: true });
124
+ // Clear log file if requested
125
+ if (settings.clearLogOnStart) {
126
+ try {
127
+ if (fs_1.default.existsSync(logPath)) {
128
+ fs_1.default.writeFileSync(logPath, '');
129
+ serv.info(`Cleared existing log file: ${logPath}`);
130
+ }
131
+ }
132
+ catch (err) {
133
+ serv.warn(`Failed to clear log file: ${err.message}`);
134
+ }
135
+ }
101
136
  // Create write stream
102
137
  logStream = fs_1.default.createWriteStream(logPath, {
103
138
  flags: 'a', // Append mode
@@ -112,6 +147,7 @@ const server = function (serv, settings) {
112
147
  // Disable logging on error
113
148
  // logStream = null
114
149
  });
150
+ // serv.setInterval(checkLogFileSize, 5 * 60 * 1000) // 5 minutes
115
151
  serv.cleanupFunctions.push(() => {
116
152
  if (logStream) {
117
153
  logStream.end('\n[INFO]: Logging ended\n');
@@ -166,6 +202,10 @@ const server = function (serv, settings) {
166
202
  // Write to log file if stream is available
167
203
  if (logStream?.writable) {
168
204
  logStream.write(plain + '\n');
205
+ // Check log file size periodically (every 100 log entries)
206
+ if (serv._logBuffer.length % 100 === 0) {
207
+ checkLogFileSize();
208
+ }
169
209
  }
170
210
  };
171
211
  serv.info = message => {
@@ -181,19 +221,19 @@ const server = function (serv, settings) {
181
221
  serv.log(line);
182
222
  };
183
223
  if (isInNode) {
184
- console.log = (function () {
185
- const orig = console.log;
224
+ // Helper function to create console method wrapper
225
+ const createConsoleWrapper = (originalMethod, prefix) => {
186
226
  return function () {
187
227
  readline.cursorTo(process.stdout, 0);
188
- // Apply original console.log to stdout
189
- orig.apply(console, arguments);
228
+ // Apply original method to stdout
229
+ originalMethod.apply(console, arguments);
190
230
  // Redirect to server log if enabled and not disabled
191
231
  if (!settings.noConsoleLogRedirect && logStream?.writable) {
192
232
  const args = Array.from(arguments);
193
233
  const message = args.map(arg => typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)).join(' ');
194
- // Add timestamp and prefix for console.log entries
234
+ // Add timestamp and prefix for console entries
195
235
  const timestamp = new Date().toISOString();
196
- const logEntry = `[${timestamp}] [CONSOLE]: ${message}\n`;
236
+ const logEntry = `[${timestamp}] [CONSOLE ${prefix}]: ${message}\n`;
197
237
  try {
198
238
  logStream.write(logEntry);
199
239
  }
@@ -203,7 +243,53 @@ const server = function (serv, settings) {
203
243
  }
204
244
  rl.prompt(true);
205
245
  };
206
- })();
246
+ };
247
+ // Patch console.log
248
+ console.log = createConsoleWrapper(console.log, 'LOG');
249
+ // Patch console.error
250
+ console.error = createConsoleWrapper(console.error, 'ERROR');
251
+ // Patch console.warn
252
+ console.warn = createConsoleWrapper(console.warn, 'WARN');
253
+ // Patch console.time and console.timeEnd
254
+ const originalTime = console.time;
255
+ const originalTimeEnd = console.timeEnd;
256
+ const timeLabels = new Map();
257
+ console.time = function (label) {
258
+ const startTime = Date.now();
259
+ timeLabels.set(label, startTime);
260
+ originalTime.call(console, label);
261
+ if (!settings.noConsoleLogRedirect && logStream?.writable) {
262
+ const timestamp = new Date().toISOString();
263
+ const logEntry = `[${timestamp}] [CONSOLE TIME]: Timer '${label}' started\n`;
264
+ try {
265
+ logStream.write(logEntry);
266
+ }
267
+ catch (err) {
268
+ // Silently fail if log writing fails to avoid infinite loops
269
+ }
270
+ }
271
+ };
272
+ console.timeEnd = function (label) {
273
+ const startTime = timeLabels.get(label);
274
+ if (startTime) {
275
+ const duration = Date.now() - startTime;
276
+ timeLabels.delete(label);
277
+ originalTimeEnd.call(console, label);
278
+ if (!settings.noConsoleLogRedirect && logStream?.writable) {
279
+ const timestamp = new Date().toISOString();
280
+ const logEntry = `[${timestamp}] [CONSOLE TIME]: Timer '${label}' ended: ${duration}ms\n`;
281
+ try {
282
+ logStream.write(logEntry);
283
+ }
284
+ catch (err) {
285
+ // Silently fail if log writing fails to avoid infinite loops
286
+ }
287
+ }
288
+ }
289
+ else {
290
+ originalTimeEnd.call(console, label);
291
+ }
292
+ };
207
293
  }
208
294
  // Return current log file path
209
295
  serv.getLogPath = () => logPath;
@@ -8,6 +8,7 @@ const user_error_1 = __importDefault(require("../user_error"));
8
8
  const server = function (serv, settings) {
9
9
  serv.ban = (uuid, reason, kick = true) => {
10
10
  if (!serv.bannedPlayers[uuid]) {
11
+ console.log('banning player', uuid, reason);
11
12
  reason ||= 'Your account is banned!';
12
13
  serv.bannedPlayers[uuid] = {
13
14
  time: Date.now(),
package/dist/modules.d.ts CHANGED
@@ -74,7 +74,6 @@ declare global {
74
74
  noWarpsLoad?: boolean;
75
75
  "max-players"?: number;
76
76
  "online-mode"?: boolean;
77
- logging?: boolean | string;
78
77
  gameMode?: number;
79
78
  difficulty?: number;
80
79
  worldFolder?: string | false;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zardoy/flying-squid",
3
3
  "description": "A minecraft server written in TS",
4
- "version": "0.0.114",
4
+ "version": "0.0.116",
5
5
  "main": "dist/index.js",
6
6
  "types": "./dist/index.d.ts",
7
7
  "bin": "dist/app.js",