jsql-neo 6.8.4 → 6.8.6

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,52 @@ 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
+ if (c === '*') { src += '.*'; continue; }
49
+ if (c === '?') { src += '.'; continue; }
50
+ if (c === '[') {
51
+ const close = p.indexOf(']', i + 1);
52
+ if (close > i + 1) {
53
+ let body = p.slice(i + 1, close).replace(/\\/g, '\\\\');
54
+ if (body[0] === '!' || body[0] === '^') body = '^' + body.slice(1);
55
+ src += '[' + body + ']';
56
+ i = close;
57
+ continue;
58
+ }
59
+ }
60
+ src += c.replace(/[.+^${}()|[\]\\]/g, '\\$&');
61
+ }
62
+ return new RegExp(src + '$');
63
+ }
64
+
65
+ // #225:bulk 载荷二进制安全。合法 UTF-8 仍按字符串保存(与历史行为/测试一致),
66
+ // 非法字节用 \u0001 前缀 + latin1 保真;回包时还原原始字节。
67
+ const BIN_PREFIX = '\u0001';
68
+ function decodeBulk(buf) {
69
+ const s = buf.toString('utf8');
70
+ if (Buffer.from(s, 'utf8').equals(buf)) return s;
71
+ return BIN_PREFIX + buf.toString('latin1');
72
+ }
73
+ function bulkToBuffer(v) {
74
+ const s = String(v);
75
+ if (s.startsWith(BIN_PREFIX)) return Buffer.from(s.slice(BIN_PREFIX.length), 'latin1');
76
+ return Buffer.from(s, 'utf8');
77
+ }
78
+
33
79
  const TYPE_SIGNATURES = {
34
80
  PING: 0, ECHO: 1, SET: -2, SETNX: 2, GET: 1, DEL: -1, EXISTS: -1, KEYS: 1,
35
81
  TYPE: 1, EXPIRE: 2, TTL: 1, PERSIST: 1,
@@ -42,6 +88,9 @@ const TYPE_SIGNATURES = {
42
88
  DBSIZE: 0, FLUSHALL: 0, FLUSHDB: 0, SELECT: 1, INFO: 0, AUTH: 1, QUIT: 0,
43
89
  };
44
90
 
91
+ // #177:这些命令的成功回复是 RESP simple string;其余字符串结果一律走 bulk。
92
+ const SIMPLE_STRING_CMDS = new Set(['SET', 'MSET', 'SELECT', 'AUTH', 'FLUSHALL', 'FLUSHDB', 'TYPE']);
93
+
45
94
  class RedisServer {
46
95
  constructor(opts = {}) {
47
96
  this.port = opts.port ?? 6379;
@@ -69,7 +118,9 @@ class RedisServer {
69
118
  }
70
119
 
71
120
  snapshotPath() {
72
- return this.dataDir ? path.join(this.dataDir, 'data.rdb.json') : null;
121
+ // #187:':memory:' 是统一的纯内存哨兵,不能当成字面目录落盘
122
+ if (!this.dataDir || this.dataDir === ':memory:') return null;
123
+ return path.join(this.dataDir, 'data.rdb.json');
73
124
  }
74
125
 
75
126
  _restoreEntry(map, k, v) {
@@ -79,24 +130,64 @@ class RedisServer {
79
130
  else map.set(k, v);
80
131
  }
81
132
 
133
+ _applySnapshot(raw) {
134
+ if (raw && raw.__jsql_redis__ === 2 && raw.databases && typeof raw.databases === 'object') {
135
+ // v2:多 DB 快照 { __jsql_redis__: 2, databases: { "0": {...}, "1": {...} } }
136
+ for (const [idxStr, entries] of Object.entries(raw.databases)) {
137
+ const idx = Number(idxStr);
138
+ const map = this._dbs.get(idx);
139
+ if (!map || !entries || typeof entries !== 'object') continue;
140
+ for (const [k, v] of Object.entries(entries)) this._restoreEntry(map, k, v);
141
+ }
142
+ } else {
143
+ // v1:旧版只有单个 db,全部落到 0 号库
144
+ for (const [k, v] of Object.entries(raw || {})) this._restoreEntry(this._dbs.get(0), k, v);
145
+ }
146
+ }
147
+
148
+ _reportLoadError(message) {
149
+ const err = new Error(message);
150
+ if (this.onError) {
151
+ try { this.onError(err); } catch (_) { /* 回调失败不影响启动 */ }
152
+ }
153
+ console.error('[jsql-neo] ' + message);
154
+ }
155
+
82
156
  _load() {
83
157
  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);
158
+ if (!p) return;
159
+ const tmp = p + '.tmp';
160
+ let raw = null;
161
+ let source = null;
162
+
163
+ if (fs.existsSync(p)) {
164
+ try {
165
+ raw = JSON.parse(fs.readFileSync(p, 'utf8'));
166
+ source = p;
167
+ } catch (e) {
168
+ // #179:快照损坏不能静默当空库;先保留现场,再尝试 .tmp
169
+ const backup = p + '.corrupt-' + Date.now();
170
+ try { fs.renameSync(p, backup); } catch (_) { /* 备份失败也要继续报告 */ }
171
+ this._reportLoadError(`redis snapshot corrupt (${p}): ${e.message}; backed up to ${backup}`);
98
172
  }
99
- } catch (_) {}
173
+ }
174
+
175
+ if (!raw && fs.existsSync(tmp)) {
176
+ try {
177
+ raw = JSON.parse(fs.readFileSync(tmp, 'utf8'));
178
+ source = tmp;
179
+ } catch (e) {
180
+ const backup = tmp + '.corrupt-' + Date.now();
181
+ try { fs.renameSync(tmp, backup); } catch (_) {}
182
+ this._reportLoadError(`redis snapshot temp corrupt (${tmp}): ${e.message}; backed up to ${backup}`);
183
+ }
184
+ }
185
+
186
+ if (!raw) return;
187
+ this._applySnapshot(raw);
188
+ if (source === tmp) {
189
+ try { fs.renameSync(tmp, p); } catch (_) { /* 恢复失败不影响已加载数据 */ }
190
+ }
100
191
  }
101
192
 
102
193
  _scheduleSnapshot() {
@@ -149,8 +240,9 @@ class RedisServer {
149
240
  execute(cmd, args) {
150
241
  const sig = TYPE_SIGNATURES[cmd];
151
242
  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`);
243
+ // #172:负 arity 表示最少参数个数,-2/-3 等也必须校验
244
+ if (sig >= 0 && args.length < sig) throw new Error(`ERR wrong number of arguments for '${cmd}' command`);
245
+ if (sig < 0 && args.length < -sig) throw new Error(`ERR wrong number of arguments for '${cmd}' command`);
154
246
  switch (cmd) {
155
247
  case 'PING': return args.length ? args[0] : 'PONG';
156
248
  case 'ECHO': return args[0];
@@ -239,7 +331,7 @@ class RedisServer {
239
331
  return Buffer.byteLength(v.val, 'utf8');
240
332
  }
241
333
  case 'INCR': case 'DECR': case 'INCRBY': case 'DECRBY': {
242
- const by = cmd === 'INCRBY' || cmd === 'DECRBY' ? parseInt(args[1], 10) : 1;
334
+ const by = cmd === 'INCRBY' || cmd === 'DECRBY' ? parseRedisInt(args[1]) : 1;
243
335
  if (isNaN(by)) throw new Error('ERR value is not an integer or out of range');
244
336
  const dir = cmd === 'DECR' || cmd === 'DECRBY' ? -1 : 1;
245
337
  const v = this._get(args[0]);
@@ -253,8 +345,13 @@ class RedisServer {
253
345
  return n;
254
346
  }
255
347
  case 'DEL': {
348
+ // #176:过期但尚未清理的键不应计入删除数
256
349
  let n = 0;
257
- for (const k of args) if (this.db.delete(k)) n++;
350
+ for (const k of args) {
351
+ if (!this._get(k)) continue;
352
+ this.db.delete(k);
353
+ n++;
354
+ }
258
355
  this._scheduleSnapshot();
259
356
  return n;
260
357
  }
@@ -266,7 +363,8 @@ class RedisServer {
266
363
  }
267
364
  case 'KEYS': {
268
365
  const pat = args[0];
269
- const re = new RegExp('^' + pat.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.') + '$');
366
+ // #228:完整 glob(含 [abc]/[!abc]/[a-c]),与 Cache.keys 语义一致
367
+ const re = globToRegex(pat);
270
368
  const keys = [];
271
369
  for (const k of this.db.keys()) {
272
370
  if (re.test(k) && this._get(k)) keys.push(k);
@@ -280,7 +378,7 @@ class RedisServer {
280
378
  case 'EXPIRE': {
281
379
  const v = this._get(args[0]);
282
380
  if (!v) return 0;
283
- const secs = parseInt(args[1], 10);
381
+ const secs = parseRedisInt(args[1]);
284
382
  if (isNaN(secs)) throw new Error('ERR value is not an integer or out of range');
285
383
  v.ttl = Date.now() + secs * 1000;
286
384
  this._scheduleSnapshot();
@@ -306,7 +404,8 @@ class RedisServer {
306
404
  const h = v ? { ...v.val } : {};
307
405
  let n = 0;
308
406
  for (let i = 1; i < args.length; i += 2) {
309
- if (!(args[i] in h)) n++;
407
+ // #226:in 会遍历原型链,必须只判断自有字段
408
+ if (!Object.prototype.hasOwnProperty.call(h, args[i])) n++;
310
409
  h[args[i]] = args[i + 1];
311
410
  }
312
411
  this.db.set(args[0], { type: 'hash', val: h, ttl: v ? v.ttl : null });
@@ -331,24 +430,30 @@ class RedisServer {
331
430
  if (v.type !== 'hash') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
332
431
  let n = 0;
333
432
  for (const f of args.slice(1)) if (v.val[f] !== undefined) { delete v.val[f]; n++; }
433
+ // #173:最后一个 field 删除后整个键也要删除
434
+ if (Object.keys(v.val).length === 0) this.db.delete(args[0]);
334
435
  this._scheduleSnapshot();
335
436
  return n;
336
437
  }
337
438
  case 'HEXISTS': {
338
439
  const v = this._get(args[0]);
339
- return (v && v.type === 'hash' && v.val[args[1]] !== undefined) ? 1 : 0;
440
+ if (v && v.type !== 'hash') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
441
+ return (v && v.val[args[1]] !== undefined) ? 1 : 0;
340
442
  }
341
443
  case 'HLEN': {
342
444
  const v = this._get(args[0]);
343
- return v && v.type === 'hash' ? Object.keys(v.val).length : 0;
445
+ if (v && v.type !== 'hash') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
446
+ return v ? Object.keys(v.val).length : 0;
344
447
  }
345
448
  case 'HKEYS': {
346
449
  const v = this._get(args[0]);
347
- return v && v.type === 'hash' ? Object.keys(v.val) : [];
450
+ if (v && v.type !== 'hash') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
451
+ return v ? Object.keys(v.val) : [];
348
452
  }
349
453
  case 'HVALS': {
350
454
  const v = this._get(args[0]);
351
- return v && v.type === 'hash' ? Object.values(v.val) : [];
455
+ if (v && v.type !== 'hash') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
456
+ return v ? Object.values(v.val) : [];
352
457
  }
353
458
  case 'LPUSH': case 'RPUSH': {
354
459
  const v = this._get(args[0]);
@@ -395,7 +500,7 @@ class RedisServer {
395
500
  const v = this._get(args[0]);
396
501
  if (!v) return [];
397
502
  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);
503
+ let start = parseRedisInt(args[1]), stop = parseRedisInt(args[2]);
399
504
  const len = v.val.length;
400
505
  if (start < 0) start = Math.max(0, len + start);
401
506
  if (stop < 0) stop = len + stop;
@@ -406,7 +511,7 @@ class RedisServer {
406
511
  const v = this._get(args[0]);
407
512
  if (!v) return null;
408
513
  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);
514
+ let i = parseRedisInt(args[1]);
410
515
  if (i < 0) i = v.val.length + i;
411
516
  return v.val[i] === undefined ? null : v.val[i];
412
517
  }
@@ -414,7 +519,7 @@ class RedisServer {
414
519
  const v = this._get(args[0]);
415
520
  if (!v) return 0;
416
521
  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);
522
+ const count = parseRedisInt(args[1]);
418
523
  const target = args[2];
419
524
  const out = [];
420
525
  let removed = 0;
@@ -440,6 +545,8 @@ class RedisServer {
440
545
  }
441
546
  }
442
547
  v.val = out;
548
+ // #173:列表删空后键也要删除
549
+ if (out.length === 0) this.db.delete(args[0]);
443
550
  this._scheduleSnapshot();
444
551
  return removed;
445
552
  }
@@ -459,25 +566,27 @@ class RedisServer {
459
566
  }
460
567
  case 'SMEMBERS': {
461
568
  const v = this._get(args[0]);
462
- return v && v.type === 'set' ? [...v.val] : [];
569
+ if (v && v.type !== 'set') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
570
+ return v ? [...v.val] : [];
463
571
  }
464
572
  case 'SISMEMBER': {
465
573
  const v = this._get(args[0]);
466
- return (v && v.type === 'set' && v.val.includes(args[1])) ? 1 : 0;
574
+ if (v && v.type !== 'set') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
575
+ return (v && v.val.includes(args[1])) ? 1 : 0;
467
576
  }
468
577
  case 'SCARD': {
469
578
  const v = this._get(args[0]);
470
- return v && v.type === 'set' ? v.val.length : 0;
579
+ if (v && v.type !== 'set') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
580
+ return v ? v.val.length : 0;
471
581
  }
472
582
  case 'ZADD': {
473
583
  const key = args[0];
474
584
  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; }
585
+ if (v && v.type !== 'zset') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
479
586
  const rest = args.slice(1);
480
587
  if (rest.length % 2 !== 0) throw new Error('ERR syntax error');
588
+ // #174:先完整校验所有 (score, member),任一非法则整条命令不产生变更
589
+ const zset = v ? { ...v.val } : {};
481
590
  let added = 0;
482
591
  for (let i = 0; i < rest.length; i += 2) {
483
592
  const score = parseRedisFloat(rest[i]);
@@ -485,6 +594,7 @@ class RedisServer {
485
594
  if (!(member in zset)) added++;
486
595
  zset[member] = score;
487
596
  }
597
+ this.db.set(key, { type: 'zset', val: zset, ttl: v ? v.ttl : null });
488
598
  this._scheduleSnapshot();
489
599
  return added;
490
600
  }
@@ -492,8 +602,8 @@ class RedisServer {
492
602
  const v = this._get(args[0]);
493
603
  if (!v) return [];
494
604
  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);
605
+ const start = parseRedisInt(args[1]);
606
+ const stop = parseRedisInt(args[2]);
497
607
  const withScores = args[3] && args[3].toUpperCase() === 'WITHSCORES';
498
608
  const entries = Object.entries(v.val).sort((a, b) => a[1] - b[1] || (a[0] < b[0] ? -1 : 1));
499
609
  const from = start < 0 ? Math.max(0, entries.length + start) : start;
@@ -509,8 +619,8 @@ class RedisServer {
509
619
  const v = this._get(args[0]);
510
620
  if (!v) return [];
511
621
  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);
622
+ const start = parseRedisInt(args[1]);
623
+ const stop = parseRedisInt(args[2]);
514
624
  const withScores = args[3] && args[3].toUpperCase() === 'WITHSCORES';
515
625
  const entries = Object.entries(v.val).sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? 1 : -1));
516
626
  const from = start < 0 ? Math.max(0, entries.length + start) : start;
@@ -524,7 +634,8 @@ class RedisServer {
524
634
  }
525
635
  case 'ZSCORE': {
526
636
  const v = this._get(args[0]);
527
- if (!v || v.type !== 'zset' || !(args[1] in v.val)) return null;
637
+ if (v && v.type !== 'zset') throw new Error('WRONGTYPE Operation against a key holding the wrong kind of value');
638
+ if (!v || !(args[1] in v.val)) return null;
528
639
  // ZSCORE 的分数恒为 bulk string(含整数分数),不能落进 integer reply(#67)
529
640
  return String(v.val[args[1]]);
530
641
  }
@@ -542,6 +653,8 @@ class RedisServer {
542
653
  for (const m of args.slice(1)) {
543
654
  if (m in v.val) { delete v.val[m]; n++; }
544
655
  }
656
+ // #173:最后一个成员删除后键也要删除
657
+ if (Object.keys(v.val).length === 0) this.db.delete(args[0]);
545
658
  this._scheduleSnapshot();
546
659
  return n;
547
660
  }
@@ -704,7 +817,8 @@ class RedisServer {
704
817
  if (len === -1) { parts.push(null); off = start; continue; } // $-1 null bulk
705
818
  if (len < -1) throw new Error('ERR Protocol error: invalid bulk length');
706
819
  if (buf.length < start + len + 2) return null; // 按字节判断
707
- parts.push(buf.slice(start, start + len).toString('utf8'));
820
+ // #225:非法 UTF-8 字节用 latin1 保真,合法文本仍保持字符串
821
+ parts.push(decodeBulk(buf.slice(start, start + len)));
708
822
  off = start + len + 2;
709
823
  }
710
824
  const cmd = String(parts[0] || '').toUpperCase();
@@ -725,26 +839,38 @@ class RedisServer {
725
839
  if (this.password && !this._authedSockets.get(socket)) {
726
840
  if (cmd === 'AUTH') {
727
841
  const ok = this.execute('AUTH', args);
728
- if (ok === 'OK') this._authedSockets.set(socket, true);
729
- return this._send(socket, ok);
842
+ if (ok === 'OK') {
843
+ this._authedSockets.set(socket, true);
844
+ socket.write('+OK\r\n');
845
+ } else {
846
+ this._send(socket, ok);
847
+ }
848
+ return;
730
849
  }
731
850
  return this._send(socket, new Error('NOAUTH Authentication required.'));
732
851
  }
733
- if (cmd === 'QUIT') { this._send(socket, 'OK'); socket.end(); return; }
852
+ if (cmd === 'QUIT') { socket.write('+OK\r\n'); socket.end(); return; }
734
853
  if (cmd === 'GET') {
735
854
  const r = this.execute(cmd, args);
736
855
  if (r === null) {
737
856
  this._send(socket, null);
738
857
  } else {
739
858
  // GET 返回值必须是 bulk string,即使内容是 "OK" 或 "PONG"
740
- const buf = Buffer.from(String(r), 'utf8');
741
- socket.write('$' + buf.length + '\r\n' + r + '\r\n');
859
+ const buf = bulkToBuffer(r);
860
+ socket.write(Buffer.concat([Buffer.from('$' + buf.length + '\r\n'), buf, Buffer.from('\r\n')]));
742
861
  }
743
862
  return;
744
863
  }
745
864
  const r = this.execute(cmd, args);
746
865
  if (cmd === 'SELECT' && r === 'OK') this._selected.set(socket, this.selected);
747
- this._send(socket, r);
866
+ // #177:只有命令级状态回复用 simple string;数据内容(ECHO/HGET/...)一律 bulk
867
+ if (cmd === 'PING' && args.length === 0) {
868
+ socket.write('+PONG\r\n');
869
+ } else if (typeof r === 'string' && SIMPLE_STRING_CMDS.has(cmd)) {
870
+ socket.write('+' + r + '\r\n');
871
+ } else {
872
+ this._send(socket, r);
873
+ }
748
874
  } catch (e) {
749
875
  this._send(socket, e);
750
876
  } finally {
@@ -757,33 +883,32 @@ class RedisServer {
757
883
  }
758
884
 
759
885
  _send(socket, val) {
886
+ const CRLF = Buffer.from('\r\n');
887
+ const bulk = (v) => {
888
+ const b = bulkToBuffer(v);
889
+ return Buffer.concat([Buffer.from('$' + b.length + '\r\n', 'latin1'), b, CRLF]);
890
+ };
760
891
  let out;
761
892
  if (val instanceof Error) {
762
- out = '-' + val.message + '\r\n';
893
+ out = Buffer.from('-' + val.message + '\r\n', 'utf8');
763
894
  } else if (val === null) {
764
- out = '$-1\r\n';
895
+ out = Buffer.from('$-1\r\n');
765
896
  } else if (typeof val === 'number') {
766
897
  // RESP integer reply 只能是十进制整数;小数必须走 bulk string(#67)。
767
- // ZSCORE / ZINCRBY 的分数已在 handler 里转成字符串,这里是非整数数字的最后兜底。
768
898
  out = Number.isInteger(val)
769
- ? ':' + val + '\r\n'
770
- : '$' + Buffer.byteLength(String(val), 'utf8') + '\r\n' + val + '\r\n';
899
+ ? Buffer.from(':' + val + '\r\n')
900
+ : bulk(val);
771
901
  } 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';
902
+ const parts = [Buffer.from('*' + val.length + '\r\n')];
903
+ for (const v of val) {
904
+ parts.push((v === null || v === undefined) ? Buffer.from('$-1\r\n') : bulk(v));
784
905
  }
906
+ out = Buffer.concat(parts);
907
+ } else if (typeof val === 'string') {
908
+ // 由调用方决定是否 simple string;这里默认按数据 bulk 编码
909
+ out = bulk(val);
785
910
  } else {
786
- out = '$-1\r\n';
911
+ out = Buffer.from('$-1\r\n');
787
912
  }
788
913
  socket.write(out);
789
914
  }