// A reply as RESP2 writes it (https://redis.io/docs/latest/develop/reference/protocol-spec/): a status as a simple string, // an error as a simple error, an integer as an integer, a string as a bulk string (its length in bytes), a null as the // null bulk string, an array as an array of its elements' replies. RESP2 has no float or double: a number that is not an // integer is its bulk string, as Redis sends INCRBYFLOAT's. "Simple strings never contain carriage return ( \r ) or line // feed ( \n ) characters" (the page), and an error is a simple string's form: Redis writes a status's text with each CR // and LF mapped to a space (script_lua.c, `sdsmapchars(ok,"\r\n"," ",2)` before `addReplyStatusLength`), and an // error's with the CRs and LFs at its ends trimmed and each one left inside mapped to a space (networking.c, // `addReplyErrorFormatInternal`: `sdstrim(s, "\r\n")`, then `sdsmapchars(s, "\r\n", " ", 2)`), so a message holding // one never ends the reply early. Source: https://raw.githubusercontent.com/redis/redis/7.4.0/src/networking.c and // https://raw.githubusercontent.com/redis/redis/7.4.0/src/script_lua.c. // Shared by every wire that answers a Redis reply as RESP2 bytes. import { RedisInteger, RedisStatus, type RedisValue } from './engine.ts'; const spaced = (text: string): string => text.replace(/[\r\n]/g, ' '); const trimmed = (text: string): string => text.replace(/^[\r\n]+|[\r\n]+$/g, ''); export function resp2(value: RedisValue | { error: string }): string { if (value instanceof RedisInteger) return `:${value.integer}\r\n`; if (value === null) return '$-1\r\n'; if (value instanceof RedisStatus) return `+${spaced(value.value)}\r\n`; if (Array.isArray(value)) return `*${value.length}\r\n${value.map((v) => resp2(v)).join('')}`; if (typeof value === 'number') return Number.isInteger(value) ? `:${value}\r\n` : resp2(String(value)); if (typeof value === 'string') return `$${new TextEncoder().encode(value).length}\r\n${value}\r\n`; return `-${spaced(trimmed(value.error))}\r\n`; }