dsh-session-relocate 0.0.0-stage → 0.2.0

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/src/zstd.js ADDED
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Zstandard 拼接帧容器的**帧级**外科手术。
3
+ *
4
+ * DSH 的会话日志是「一串彼此独立的 Zstandard 帧」,第一帧的第一行就是 header。
5
+ * 要改 header 里的 cwd,最安全的做法是只重编第一帧,其余字节原样保留 ——
6
+ * 这样连尾部未写完的(torn)帧都不会被我们碰坏,重建后的文件与后端自己的
7
+ * 写入路径完全同构。
8
+ *
9
+ * scanZstdFrames 是从 @deepseek-ai/dsh-session-persistence-jsonl 内部移植的
10
+ * 结构扫描器(只读帧头,不解压块),压缩参数也与后端一致
11
+ * (ZSTD_c_checksumFlag: 1,即带校验和的帧)。
12
+ *
13
+ * @module dsh-session-relocate/zstd
14
+ */
15
+ import { constants, zstdCompressSync, zstdDecompressSync } from 'node:zlib';
16
+
17
+ /** Zstandard 魔数(小端读取:0xFD2FB528)。 */
18
+ const ZSTD_MAGIC = 4247762216;
19
+
20
+ /** 与后端一致的压缩参数:写校验和,让读路径能校验帧完整性。 */
21
+ const CHECKSUM_PARAM = constants.ZSTD_c_checksumFlag;
22
+ const CHECKSUM_OPTIONS = CHECKSUM_PARAM === undefined ? undefined : { params: { [CHECKSUM_PARAM]: 1 } };
23
+
24
+ /** 该 Node 版本是否支持后端期望的校验和参数。 */
25
+ export const CHECKSUM_SUPPORTED = CHECKSUM_PARAM !== undefined;
26
+
27
+ /**
28
+ * 结构扫描拼接的 Zstandard 流,不解压任何块。
29
+ * 完整帧按其字节范围返回;EOF 落在最后一帧中途时,返回该帧起点供修复。
30
+ *
31
+ * @param buffer - 会话文件当前的全部字节。
32
+ * @param maxFrames - 最多扫描多少个完整帧(默认不限)。
33
+ * @returns 完整帧范围,外加可选的未完成末帧起点。
34
+ */
35
+ export function scanZstdFrames(buffer, maxFrames = Number.POSITIVE_INFINITY) {
36
+ const frames = [];
37
+ let offset = 0;
38
+ while (offset < buffer.length) {
39
+ const start = offset;
40
+ if (buffer.length - offset < 4) return { frames, tornStart: start };
41
+ if (buffer.readUInt32LE(offset) !== ZSTD_MAGIC) {
42
+ throw new Error('corrupt Zstandard session log: invalid frame magic at byte ' + String(offset));
43
+ }
44
+ offset += 4;
45
+ if (offset === buffer.length) return { frames, tornStart: start };
46
+ const descriptor = buffer.readUInt8(offset);
47
+ offset += 1;
48
+ if ((descriptor & 24) !== 0) {
49
+ throw new Error('corrupt Zstandard session log: reserved frame-header bit at byte ' + String(offset - 1));
50
+ }
51
+ const contentSizeFlag = descriptor >>> 6;
52
+ const singleSegment = (descriptor & 32) !== 0;
53
+ const checksum = (descriptor & 4) !== 0;
54
+ const dictionaryFlag = descriptor & 3;
55
+ const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag;
56
+ const contentSizeBytes = contentSizeFlag === 0 ? (singleSegment ? 1 : 0) : 1 << contentSizeFlag;
57
+ const remainingHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes;
58
+ if (buffer.length - offset < remainingHeaderBytes) return { frames, tornStart: start };
59
+ offset += remainingHeaderBytes;
60
+ for (;;) {
61
+ if (buffer.length - offset < 3) return { frames, tornStart: start };
62
+ const blockHeader = buffer.readUIntLE(offset, 3);
63
+ offset += 3;
64
+ const lastBlock = (blockHeader & 1) !== 0;
65
+ const blockType = (blockHeader >>> 1) & 3;
66
+ const blockSize = blockHeader >>> 3;
67
+ if (blockType === 3) {
68
+ throw new Error('corrupt Zstandard session log: reserved block type at byte ' + String(offset - 3));
69
+ }
70
+ const payloadBytes = blockType === 1 ? 1 : blockSize;
71
+ if (buffer.length - offset < payloadBytes) return { frames, tornStart: start };
72
+ offset += payloadBytes;
73
+ if (lastBlock) break;
74
+ }
75
+ if (checksum) {
76
+ if (buffer.length - offset < 4) return { frames, tornStart: start };
77
+ offset += 4;
78
+ }
79
+ frames.push({ start, end: offset });
80
+ if (frames.length === maxFrames) return { frames };
81
+ }
82
+ return { frames };
83
+ }
84
+
85
+ /**
86
+ * 文件是否以 Zstandard 帧开头(即 compression 为 zstd)。
87
+ *
88
+ * @param buffer - 文件字节。
89
+ * @returns 是否是 zstd 会话日志。
90
+ */
91
+ export function isZstdArtifact(buffer) {
92
+ return buffer.length >= 4 && buffer.readUInt32LE(0) === ZSTD_MAGIC;
93
+ }
94
+
95
+ /** 解出第一帧的明文(header 就住在它的第一行)。 */
96
+ function firstFramePlaintext(buffer) {
97
+ const scan = scanZstdFrames(buffer, 1);
98
+ const first = scan.frames[0];
99
+ if (first === undefined) {
100
+ throw new Error('session log carries no complete Zstandard frame (torn at byte ' + String(scan.tornStart ?? 0) + ')');
101
+ }
102
+ return { first, plain: zstdDecompressSync(buffer.subarray(first.start, first.end)) };
103
+ }
104
+
105
+ /**
106
+ * 读出会话日志的第一行(header 行)。zstd 与未压缩两种编码都支持。
107
+ *
108
+ * @param buffer - 会话文件字节。
109
+ * @returns 第一行的 UTF-8 文本。
110
+ */
111
+ export function readFirstLine(buffer) {
112
+ if (isZstdArtifact(buffer)) {
113
+ const { plain } = firstFramePlaintext(buffer);
114
+ const nl = plain.indexOf(10);
115
+ if (nl < 0) throw new Error('the first Zstandard frame carries no complete line');
116
+ return plain.subarray(0, nl).toString('utf8');
117
+ }
118
+ const nl = buffer.indexOf(10);
119
+ if (nl < 0) throw new Error('the session log carries no complete line');
120
+ return buffer.subarray(0, nl).toString('utf8');
121
+ }
122
+
123
+ /**
124
+ * 只替换第一行,其余字节原样保留。
125
+ *
126
+ * 对 zstd:只重编第一帧(带校验和,与后端写入一致),从第二帧开始的原始字节
127
+ * —— 包括任何 torn 尾帧 —— 一个字节都不动。
128
+ * 对未压缩:直接在字节层面替换首个换行符之前的内容。
129
+ *
130
+ * @param buffer - 原文件字节。
131
+ * @param newFirstLine - 新的第一行(不含换行符)。
132
+ * @returns 新的文件字节。
133
+ */
134
+ export function replaceFirstLine(buffer, newFirstLine) {
135
+ const encoded = Buffer.from(newFirstLine, 'utf8');
136
+ if (encoded.includes(10)) throw new Error('the replacement first line must not contain a newline');
137
+ if (isZstdArtifact(buffer)) {
138
+ const { first, plain } = firstFramePlaintext(buffer);
139
+ const nl = plain.indexOf(10);
140
+ if (nl < 0) throw new Error('the first Zstandard frame carries no complete line');
141
+ const rebuilt = CHECKSUM_OPTIONS === undefined
142
+ ? zstdCompressSync(Buffer.concat([encoded, plain.subarray(nl)]))
143
+ : zstdCompressSync(Buffer.concat([encoded, plain.subarray(nl)]), CHECKSUM_OPTIONS);
144
+ return Buffer.concat([buffer.subarray(0, first.start), rebuilt, buffer.subarray(first.end)]);
145
+ }
146
+ const nl = buffer.indexOf(10);
147
+ if (nl < 0) throw new Error('the session log carries no complete line');
148
+ return Buffer.concat([encoded, buffer.subarray(nl)]);
149
+ }
150
+
151
+ /**
152
+ * 把整份日志按帧解压并顺序拼接成明文字节,用于搬移后的逐字节自校验。
153
+ *
154
+ * @param buffer - 会话文件字节。
155
+ * @returns 全部完整帧的明文拼接。
156
+ */
157
+ export function decodeAllFrames(buffer) {
158
+ if (!isZstdArtifact(buffer)) return Buffer.from(buffer);
159
+ const { frames } = scanZstdFrames(buffer);
160
+ const parts = [];
161
+ for (const frame of frames) {
162
+ parts.push(zstdDecompressSync(buffer.subarray(frame.start, frame.end)));
163
+ }
164
+ return Buffer.concat(parts);
165
+ }