jsql-neo 6.8.4 → 6.8.7

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.
@@ -30,6 +30,58 @@ function parseRedisFloat(raw) {
30
30
  return Number(s);
31
31
  }
32
32
 
33
+ // #175:索引必须是严格十进制整数;parseInt 会把 "x" 变 NaN、把 "1.5" 截断。
34
+ function parseRedisInt(raw) {
35
+ const s = String(raw).trim();
36
+ if (!/^-?\d+$/.test(s)) throw new Error('ERR value is not an integer or out of range');
37
+ const n = Number(s);
38
+ if (!Number.isSafeInteger(n)) throw new Error('ERR value is not an integer or out of range');
39
+ return n;
40
+ }
41
+
42
+ // Redis glob:* / ? / [abc] / [!abc] / [a-c];其余正则元字符按字面转义
43
+ function globToRegex(pattern) {
44
+ const p = String(pattern);
45
+ let src = '^';
46
+ for (let i = 0; i < p.length; i++) {
47
+ const c = p[i];
48
+ // #241:反斜杠转义下一个字符,按字面量匹配
49
+ if (c === '\\' && i + 1 < p.length) {
50
+ i++;
51
+ src += p[i].replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
52
+ continue;
53
+ }
54
+ if (c === '*') { src += '.*'; continue; }
55
+ if (c === '?') { src += '.'; continue; }
56
+ if (c === '[') {
57
+ const close = p.indexOf(']', i + 1);
58
+ if (close > i + 1) {
59
+ let body = p.slice(i + 1, close).replace(/\\/g, '\\\\');
60
+ if (body[0] === '!' || body[0] === '^') body = '^' + body.slice(1);
61
+ src += '[' + body + ']';
62
+ i = close;
63
+ continue;
64
+ }
65
+ }
66
+ src += c.replace(/[.+^${}()|[\]\\]/g, '\\$&');
67
+ }
68
+ return new RegExp(src + '$');
69
+ }
70
+
71
+ // #225:bulk 载荷二进制安全。合法 UTF-8 仍按字符串保存(与历史行为/测试一致),
72
+ // 非法字节用 \u0001 前缀 + latin1 保真;回包时还原原始字节。
73
+ const BIN_PREFIX = '\u0001';
74
+ function decodeBulk(buf) {
75
+ const s = buf.toString('utf8');
76
+ if (Buffer.from(s, 'utf8').equals(buf)) return s;
77
+ return BIN_PREFIX + buf.toString('latin1');
78
+ }
79
+ function bulkToBuffer(v) {
80
+ const s = String(v);
81
+ if (s.startsWith(BIN_PREFIX)) return Buffer.from(s.slice(BIN_PREFIX.length), 'latin1');
82
+ return Buffer.from(s, 'utf8');
83
+ }
84
+
33
85
  const TYPE_SIGNATURES = {
34
86
  PING: 0, ECHO: 1, SET: -2, SETNX: 2, GET: 1, DEL: -1, EXISTS: -1, KEYS: 1,
35
87
  TYPE: 1, EXPIRE: 2, TTL: 1, PERSIST: 1,
@@ -42,6 +94,9 @@ const TYPE_SIGNATURES = {
42
94
  DBSIZE: 0, FLUSHALL: 0, FLUSHDB: 0, SELECT: 1, INFO: 0, AUTH: 1, QUIT: 0,
43
95
  };
44
96
 
97
+ // #177:这些命令的成功回复是 RESP simple string;其余字符串结果一律走 bulk。
98
+ const SIMPLE_STRING_CMDS = new Set(['SET', 'MSET', 'SELECT', 'AUTH', 'FLUSHALL', 'FLUSHDB', 'TYPE']);
99
+
45
100
  class RedisServer {
46
101
  constructor(opts = {}) {
47
102
  this.port = opts.port ?? 6379;
@@ -69,7 +124,9 @@ class RedisServer {
69
124
  }
70
125
 
71
126
  snapshotPath() {
72
- return this.dataDir ? path.join(this.dataDir, 'data.rdb.json') : null;
127
+ // #187:':memory:' 是统一的纯内存哨兵,不能当成字面目录落盘
128
+ if (!this.dataDir || this.dataDir === ':memory:') return null;
129
+ return path.join(this.dataDir, 'data.rdb.json');
73
130
  }
74
131
 
75
132
  _restoreEntry(map, k, v) {
@@ -79,24 +136,64 @@ class RedisServer {
79
136
  else map.set(k, v);
80
137
  }
81
138
 
139
+ _applySnapshot(raw) {
140
+ if (raw && raw.__jsql_redis__ === 2 && raw.databases && typeof raw.databases === 'object') {
141
+ // v2:多 DB 快照 { __jsql_redis__: 2, databases: { "0": {...}, "1": {...} } }
142
+ for (const [idxStr, entries] of Object.entries(raw.databases)) {
143
+ const idx = Number(idxStr);
144
+ const map = this._dbs.get(idx);
145
+ if (!map || !entries || typeof entries !== 'object') continue;
146
+ for (const [k, v] of Object.entries(entries)) this._restoreEntry(map, k, v);
147
+ }
148
+ } else {
149
+ // v1:旧版只有单个 db,全部落到 0 号库
150
+ for (const [k, v] of Object.entries(raw || {})) this._restoreEntry(this._dbs.get(0), k, v);
151
+ }
152
+ }
153
+
154
+ _reportLoadError(message) {
155
+ const err = new Error(message);
156
+ if (this.onError) {
157
+ try { this.onError(err); } catch (_) { /* 回调失败不影响启动 */ }
158
+ }
159
+ console.error('[jsql-neo] ' + message);
160
+ }
161
+
82
162
  _load() {
83
163
  const p = this.snapshotPath();
84
- if (!p || !fs.existsSync(p)) return;
85
- try {
86
- const raw = JSON.parse(fs.readFileSync(p, 'utf8'));
87
- if (raw && raw.__jsql_redis__ === 2 && raw.databases && typeof raw.databases === 'object') {
88
- // v2:多 DB 快照 { __jsql_redis__: 2, databases: { "0": {...}, "1": {...} } }
89
- for (const [idxStr, entries] of Object.entries(raw.databases)) {
90
- const idx = Number(idxStr);
91
- const map = this._dbs.get(idx);
92
- if (!map || !entries || typeof entries !== 'object') continue;
93
- for (const [k, v] of Object.entries(entries)) this._restoreEntry(map, k, v);
94
- }
95
- } else {
96
- // v1:旧版只有单个 db,全部落到 0 号库
97
- for (const [k, v] of Object.entries(raw || {})) this._restoreEntry(this._dbs.get(0), k, v);
164
+ if (!p) return;
165
+ const tmp = p + '.tmp';
166
+ let raw = null;
167
+ let source = null;
168
+
169
+ if (fs.existsSync(p)) {
170
+ try {
171
+ raw = JSON.parse(fs.readFileSync(p, 'utf8'));
172
+ source = p;
173
+ } catch (e) {
174
+ // #179:快照损坏不能静默当空库;先保留现场,再尝试 .tmp
175
+ const backup = p + '.corrupt-' + Date.now();
176
+ try { fs.renameSync(p, backup); } catch (_) { /* 备份失败也要继续报告 */ }
177
+ this._reportLoadError(`redis snapshot corrupt (${p}): ${e.message}; backed up to ${backup}`);
98
178
  }
99
- } catch (_) {}
179
+ }
180
+
181
+ if (!raw && fs.existsSync(tmp)) {
182
+ try {
183
+ raw = JSON.parse(fs.readFileSync(tmp, 'utf8'));
184
+ source = tmp;
185
+ } catch (e) {
186
+ const backup = tmp + '.corrupt-' + Date.now();
187
+ try { fs.renameSync(tmp, backup); } catch (_) {}
188
+ this._reportLoadError(`redis snapshot temp corrupt (${tmp}): ${e.message}; backed up to ${backup}`);
189
+ }
190
+ }
191
+
192
+ if (!raw) return;
193
+ this._applySnapshot(raw);
194
+ if (source === tmp) {
195
+ try { fs.renameSync(tmp, p); } catch (_) { /* 恢复失败不影响已加载数据 */ }
196
+ }
100
197
  }
101
198
 
102
199
  _scheduleSnapshot() {
@@ -149,8 +246,9 @@ class RedisServer {
149
246
  execute(cmd, args) {
150
247
  const sig = TYPE_SIGNATURES[cmd];
151
248
  if (sig === undefined) throw new Error(`ERR unknown command '${cmd}'`);
152
- if (sig > 0 && args.length < sig) throw new Error(`ERR wrong number of arguments for '${cmd}' command`);
153
- if (sig === -1 && args.length < 1) throw new Error(`ERR wrong number of arguments for '${cmd}' command`);
249
+ // #172:负 arity 表示最少参数个数,-2/-3 等也必须校验
250
+ if (sig >= 0 && args.length < sig) throw new Error(`ERR wrong number of arguments for '${cmd}' command`);
251
+ if (sig < 0 && args.length < -sig) throw new Error(`ERR wrong number of arguments for '${cmd}' command`);
154
252
  switch (cmd) {
155
253
  case 'PING': return args.length ? args[0] : 'PONG';
156
254
  case 'ECHO': return args[0];
@@ -239,7 +337,7 @@ class RedisServer {
239
337
  return Buffer.byteLength(v.val, 'utf8');
240
338
  }
241
339
  case 'INCR': case 'DECR': case 'INCRBY': case 'DECRBY': {
242
- const by = cmd === 'INCRBY' || cmd === 'DECRBY' ? parseInt(args[1], 10) : 1;
340
+ const by = cmd === 'INCRBY' || cmd === 'DECRBY' ? parseRedisInt(args[1]) : 1;
243
341
  if (isNaN(by)) throw new Error('ERR value is not an integer or out of range');
244
342
  const dir = cmd === 'DECR' || cmd === 'DECRBY' ? -1 : 1;
245
343
  const v = this._get(args[0]);
@@ -253,8 +351,13 @@ class RedisServer {
253
351
  return n;
254
352
  }
255
353
  case 'DEL': {
354
+ // #176:过期但尚未清理的键不应计入删除数
256
355
  let n = 0;
257
- for (const k of args) if (this.db.delete(k)) n++;
356
+ for (const k of args) {
357
+ if (!this._get(k)) continue;
358
+ this.db.delete(k);
359
+ n++;
360
+ }
258
361
  this._scheduleSnapshot();
259
362
  return n;
260
363
  }
@@ -266,7 +369,8 @@ class RedisServer {
266
369
  }
267
370
  case 'KEYS': {
268
371
  const pat = args[0];
269
- const re = new RegExp('^' + pat.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.') + '$');
372
+ // #228:完整 glob(含 [abc]/[!abc]/[a-c]),与 Cache.keys 语义一致
373
+ const re = globToRegex(pat);
270
374
  const keys = [];
271
375
  for (const k of this.db.keys()) {
272
376
  if (re.test(k) && this._get(k)) keys.push(k);
@@ -280,7 +384,7 @@ class RedisServer {
280
384
  case 'EXPIRE': {
281
385
  const v = this._get(args[0]);
282
386
  if (!v) return 0;
283
- const secs = parseInt(args[1], 10);
387
+ const secs = parseRedisInt(args[1]);
284
388
  if (isNaN(secs)) throw new Error('ERR value is not an integer or out of range');
285
389
  v.ttl = Date.now() + secs * 1000;
286
390
  this._scheduleSnapshot();
@@ -306,7 +410,8 @@ class RedisServer {
306
410
  const h = v ? { ...v.val } : {};
307
411
  let n = 0;
308
412
  for (let i = 1; i < args.length; i += 2) {
309
- if (!(args[i] in h)) n++;
413
+ // #226:in 会遍历原型链,必须只判断自有字段
414
+ if (!Object.prototype.hasOwnProperty.call(h, args[i])) n++;
310
415
  h[args[i]] = args[i + 1];
311
416
  }
312
417
  this.db.set(args[0], { type: 'hash', val: h, ttl: v ? v.ttl : null });
@@ -331,24 +436,30 @@ class RedisServer {
331
436
  if (v.type !== 'hash') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
332
437
  let n = 0;
333
438
  for (const f of args.slice(1)) if (v.val[f] !== undefined) { delete v.val[f]; n++; }
439
+ // #173:最后一个 field 删除后整个键也要删除
440
+ if (Object.keys(v.val).length === 0) this.db.delete(args[0]);
334
441
  this._scheduleSnapshot();
335
442
  return n;
336
443
  }
337
444
  case 'HEXISTS': {
338
445
  const v = this._get(args[0]);
339
- return (v && v.type === 'hash' && v.val[args[1]] !== undefined) ? 1 : 0;
446
+ if (v && v.type !== 'hash') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
447
+ return (v && v.val[args[1]] !== undefined) ? 1 : 0;
340
448
  }
341
449
  case 'HLEN': {
342
450
  const v = this._get(args[0]);
343
- return v && v.type === 'hash' ? Object.keys(v.val).length : 0;
451
+ if (v && v.type !== 'hash') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
452
+ return v ? Object.keys(v.val).length : 0;
344
453
  }
345
454
  case 'HKEYS': {
346
455
  const v = this._get(args[0]);
347
- return v && v.type === 'hash' ? Object.keys(v.val) : [];
456
+ if (v && v.type !== 'hash') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
457
+ return v ? Object.keys(v.val) : [];
348
458
  }
349
459
  case 'HVALS': {
350
460
  const v = this._get(args[0]);
351
- return v && v.type === 'hash' ? Object.values(v.val) : [];
461
+ if (v && v.type !== 'hash') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
462
+ return v ? Object.values(v.val) : [];
352
463
  }
353
464
  case 'LPUSH': case 'RPUSH': {
354
465
  const v = this._get(args[0]);
@@ -395,7 +506,7 @@ class RedisServer {
395
506
  const v = this._get(args[0]);
396
507
  if (!v) return [];
397
508
  if (v.type !== 'list') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
398
- let start = parseInt(args[1], 10), stop = parseInt(args[2], 10);
509
+ let start = parseRedisInt(args[1]), stop = parseRedisInt(args[2]);
399
510
  const len = v.val.length;
400
511
  if (start < 0) start = Math.max(0, len + start);
401
512
  if (stop < 0) stop = len + stop;
@@ -406,7 +517,7 @@ class RedisServer {
406
517
  const v = this._get(args[0]);
407
518
  if (!v) return null;
408
519
  if (v.type !== 'list') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
409
- let i = parseInt(args[1], 10);
520
+ let i = parseRedisInt(args[1]);
410
521
  if (i < 0) i = v.val.length + i;
411
522
  return v.val[i] === undefined ? null : v.val[i];
412
523
  }
@@ -414,7 +525,7 @@ class RedisServer {
414
525
  const v = this._get(args[0]);
415
526
  if (!v) return 0;
416
527
  if (v.type !== 'list') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
417
- const count = parseInt(args[1], 10);
528
+ const count = parseRedisInt(args[1]);
418
529
  const target = args[2];
419
530
  const out = [];
420
531
  let removed = 0;
@@ -440,6 +551,8 @@ class RedisServer {
440
551
  }
441
552
  }
442
553
  v.val = out;
554
+ // #173:列表删空后键也要删除
555
+ if (out.length === 0) this.db.delete(args[0]);
443
556
  this._scheduleSnapshot();
444
557
  return removed;
445
558
  }
@@ -459,25 +572,27 @@ class RedisServer {
459
572
  }
460
573
  case 'SMEMBERS': {
461
574
  const v = this._get(args[0]);
462
- return v && v.type === 'set' ? [...v.val] : [];
575
+ if (v && v.type !== 'set') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
576
+ return v ? [...v.val] : [];
463
577
  }
464
578
  case 'SISMEMBER': {
465
579
  const v = this._get(args[0]);
466
- return (v && v.type === 'set' && v.val.includes(args[1])) ? 1 : 0;
580
+ if (v && v.type !== 'set') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
581
+ return (v && v.val.includes(args[1])) ? 1 : 0;
467
582
  }
468
583
  case 'SCARD': {
469
584
  const v = this._get(args[0]);
470
- return v && v.type === 'set' ? v.val.length : 0;
585
+ if (v && v.type !== 'set') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
586
+ return v ? v.val.length : 0;
471
587
  }
472
588
  case 'ZADD': {
473
589
  const key = args[0];
474
590
  const v = this._get(key);
475
- let zset;
476
- if (v && v.type === 'zset') zset = v.val;
477
- else if (v) throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
478
- else { this.db.set(key, { type: 'zset', val: {} }); zset = this.db.get(key).val; }
591
+ if (v && v.type !== 'zset') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
479
592
  const rest = args.slice(1);
480
593
  if (rest.length % 2 !== 0) throw new Error('ERR syntax error');
594
+ // #174:先完整校验所有 (score, member),任一非法则整条命令不产生变更
595
+ const zset = v ? { ...v.val } : {};
481
596
  let added = 0;
482
597
  for (let i = 0; i < rest.length; i += 2) {
483
598
  const score = parseRedisFloat(rest[i]);
@@ -485,6 +600,7 @@ class RedisServer {
485
600
  if (!(member in zset)) added++;
486
601
  zset[member] = score;
487
602
  }
603
+ this.db.set(key, { type: 'zset', val: zset, ttl: v ? v.ttl : null });
488
604
  this._scheduleSnapshot();
489
605
  return added;
490
606
  }
@@ -492,8 +608,8 @@ class RedisServer {
492
608
  const v = this._get(args[0]);
493
609
  if (!v) return [];
494
610
  if (v.type !== 'zset') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
495
- const start = parseInt(args[1], 10);
496
- const stop = parseInt(args[2], 10);
611
+ const start = parseRedisInt(args[1]);
612
+ const stop = parseRedisInt(args[2]);
497
613
  const withScores = args[3] && args[3].toUpperCase() === 'WITHSCORES';
498
614
  const entries = Object.entries(v.val).sort((a, b) => a[1] - b[1] || (a[0] < b[0] ? -1 : 1));
499
615
  const from = start < 0 ? Math.max(0, entries.length + start) : start;
@@ -509,8 +625,8 @@ class RedisServer {
509
625
  const v = this._get(args[0]);
510
626
  if (!v) return [];
511
627
  if (v.type !== 'zset') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
512
- const start = parseInt(args[1], 10);
513
- const stop = parseInt(args[2], 10);
628
+ const start = parseRedisInt(args[1]);
629
+ const stop = parseRedisInt(args[2]);
514
630
  const withScores = args[3] && args[3].toUpperCase() === 'WITHSCORES';
515
631
  const entries = Object.entries(v.val).sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? 1 : -1));
516
632
  const from = start < 0 ? Math.max(0, entries.length + start) : start;
@@ -524,7 +640,8 @@ class RedisServer {
524
640
  }
525
641
  case 'ZSCORE': {
526
642
  const v = this._get(args[0]);
527
- if (!v || v.type !== 'zset' || !(args[1] in v.val)) return null;
643
+ if (v && v.type !== 'zset') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
644
+ if (!v || !(args[1] in v.val)) return null;
528
645
  // ZSCORE 的分数恒为 bulk string(含整数分数),不能落进 integer reply(#67)
529
646
  return String(v.val[args[1]]);
530
647
  }
@@ -542,6 +659,8 @@ class RedisServer {
542
659
  for (const m of args.slice(1)) {
543
660
  if (m in v.val) { delete v.val[m]; n++; }
544
661
  }
662
+ // #173:最后一个成员删除后键也要删除
663
+ if (Object.keys(v.val).length === 0) this.db.delete(args[0]);
545
664
  this._scheduleSnapshot();
546
665
  return n;
547
666
  }
@@ -704,7 +823,8 @@ class RedisServer {
704
823
  if (len === -1) { parts.push(null); off = start; continue; } // $-1 null bulk
705
824
  if (len < -1) throw new Error('ERR Protocol error: invalid bulk length');
706
825
  if (buf.length < start + len + 2) return null; // 按字节判断
707
- parts.push(buf.slice(start, start + len).toString('utf8'));
826
+ // #225:非法 UTF-8 字节用 latin1 保真,合法文本仍保持字符串
827
+ parts.push(decodeBulk(buf.slice(start, start + len)));
708
828
  off = start + len + 2;
709
829
  }
710
830
  const cmd = String(parts[0] || '').toUpperCase();
@@ -725,26 +845,38 @@ class RedisServer {
725
845
  if (this.password && !this._authedSockets.get(socket)) {
726
846
  if (cmd === 'AUTH') {
727
847
  const ok = this.execute('AUTH', args);
728
- if (ok === 'OK') this._authedSockets.set(socket, true);
729
- return this._send(socket, ok);
848
+ if (ok === 'OK') {
849
+ this._authedSockets.set(socket, true);
850
+ socket.write('+OK\r\n');
851
+ } else {
852
+ this._send(socket, ok);
853
+ }
854
+ return;
730
855
  }
731
856
  return this._send(socket, new Error('NOAUTH Authentication required.'));
732
857
  }
733
- if (cmd === 'QUIT') { this._send(socket, 'OK'); socket.end(); return; }
858
+ if (cmd === 'QUIT') { socket.write('+OK\r\n'); socket.end(); return; }
734
859
  if (cmd === 'GET') {
735
860
  const r = this.execute(cmd, args);
736
861
  if (r === null) {
737
862
  this._send(socket, null);
738
863
  } else {
739
864
  // GET 返回值必须是 bulk string,即使内容是 "OK" 或 "PONG"
740
- const buf = Buffer.from(String(r), 'utf8');
741
- socket.write('$' + buf.length + '\r\n' + r + '\r\n');
865
+ const buf = bulkToBuffer(r);
866
+ socket.write(Buffer.concat([Buffer.from('$' + buf.length + '\r\n'), buf, Buffer.from('\r\n')]));
742
867
  }
743
868
  return;
744
869
  }
745
870
  const r = this.execute(cmd, args);
746
871
  if (cmd === 'SELECT' && r === 'OK') this._selected.set(socket, this.selected);
747
- this._send(socket, r);
872
+ // #177:只有命令级状态回复用 simple string;数据内容(ECHO/HGET/...)一律 bulk
873
+ if (cmd === 'PING' && args.length === 0) {
874
+ socket.write('+PONG\r\n');
875
+ } else if (typeof r === 'string' && SIMPLE_STRING_CMDS.has(cmd)) {
876
+ socket.write('+' + r + '\r\n');
877
+ } else {
878
+ this._send(socket, r);
879
+ }
748
880
  } catch (e) {
749
881
  this._send(socket, e);
750
882
  } finally {
@@ -757,33 +889,32 @@ class RedisServer {
757
889
  }
758
890
 
759
891
  _send(socket, val) {
892
+ const CRLF = Buffer.from('\r\n');
893
+ const bulk = (v) => {
894
+ const b = bulkToBuffer(v);
895
+ return Buffer.concat([Buffer.from('$' + b.length + '\r\n', 'latin1'), b, CRLF]);
896
+ };
760
897
  let out;
761
898
  if (val instanceof Error) {
762
- out = '-' + val.message + '\r\n';
899
+ out = Buffer.from('-' + val.message + '\r\n', 'utf8');
763
900
  } else if (val === null) {
764
- out = '$-1\r\n';
901
+ out = Buffer.from('$-1\r\n');
765
902
  } else if (typeof val === 'number') {
766
903
  // RESP integer reply 只能是十进制整数;小数必须走 bulk string(#67)。
767
- // ZSCORE / ZINCRBY 的分数已在 handler 里转成字符串,这里是非整数数字的最后兜底。
768
904
  out = Number.isInteger(val)
769
- ? ':' + val + '\r\n'
770
- : '$' + Buffer.byteLength(String(val), 'utf8') + '\r\n' + val + '\r\n';
905
+ ? Buffer.from(':' + val + '\r\n')
906
+ : bulk(val);
771
907
  } else if (Array.isArray(val)) {
772
- // 长度用字节数,不能用 String.length —— 否则中文等多字节值会让客户端解帧错位。
773
- // 批量回复里缺失的键必须是 nil bulk ($-1),不能是 "null" 字符串(#66)。
774
- out = '*' + val.length + '\r\n' + val.map(v =>
775
- (v === null || v === undefined)
776
- ? '$-1\r\n'
777
- : '$' + Buffer.byteLength(String(v), 'utf8') + '\r\n' + v + '\r\n'
778
- ).join('');
779
- } else if (typeof val === 'string') {
780
- if (val === 'OK' || val === 'PONG') {
781
- out = '+' + val + '\r\n';
782
- } else {
783
- out = '$' + Buffer.byteLength(val, 'utf8') + '\r\n' + val + '\r\n';
908
+ const parts = [Buffer.from('*' + val.length + '\r\n')];
909
+ for (const v of val) {
910
+ parts.push((v === null || v === undefined) ? Buffer.from('$-1\r\n') : bulk(v));
784
911
  }
912
+ out = Buffer.concat(parts);
913
+ } else if (typeof val === 'string') {
914
+ // 由调用方决定是否 simple string;这里默认按数据 bulk 编码
915
+ out = bulk(val);
785
916
  } else {
786
- out = '$-1\r\n';
917
+ out = Buffer.from('$-1\r\n');
787
918
  }
788
919
  socket.write(out);
789
920
  }