@wwwfz/dsh-agent-bridge 0.9.0 → 0.10.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.
@@ -0,0 +1,198 @@
1
+ import { open, realpath, stat } from 'node:fs/promises';
2
+ import { Readable } from 'node:stream';
3
+ import { pipeline } from 'node:stream/promises';
4
+ import zlib from 'node:zlib';
5
+
6
+ // A single JSON value must be parsed in memory. Stream between records and
7
+ // report a gap for an exceptionally large value instead of dropping it silently.
8
+ export const sourceValueLimit = 32 * 1024 * 1024;
9
+ const chunkSize = 64 * 1024;
10
+ const utf8 = new TextDecoder('utf-8', { fatal: true });
11
+
12
+ function sourceChanged() {
13
+ return Object.assign(new Error('Source changed while being read'), { sourceReason: 'source-changed' });
14
+ }
15
+
16
+ function sameFile(left, right) {
17
+ return left.dev === right.dev && left.ino === right.ino
18
+ && left.birthtimeNs === right.birthtimeNs;
19
+ }
20
+
21
+ export async function* sourceChunks(file, signal) {
22
+ signal?.throwIfAborted();
23
+ const expected = await stat(file, { bigint: true });
24
+ const handle = await open(file, 'r');
25
+ try {
26
+ const start = await handle.stat({ bigint: true });
27
+ if (!start.isFile() || !sameFile(start, expected) || await realpath(file) !== file) throw sourceChanged();
28
+ const end = Number(start.size);
29
+ if (!Number.isSafeInteger(end)) throw Object.assign(new Error('Source is too large'), { sourceReason: 'source-too-large' });
30
+ let position = 0;
31
+ while (position < end) {
32
+ signal?.throwIfAborted();
33
+ const buffer = Buffer.allocUnsafe(Math.min(chunkSize, end - position));
34
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, position);
35
+ if (!bytesRead) throw sourceChanged();
36
+ position += bytesRead;
37
+ yield buffer.subarray(0, bytesRead);
38
+ }
39
+ const current = await handle.stat({ bigint: true });
40
+ const currentPath = await stat(file, { bigint: true }).catch(() => undefined);
41
+ if (!currentPath || !sameFile(start, currentPath) || await realpath(file) !== file
42
+ || current.size < start.size || (current.size === start.size && current.mtimeNs !== start.mtimeNs)) {
43
+ throw sourceChanged();
44
+ }
45
+ } finally {
46
+ await handle.close();
47
+ }
48
+ }
49
+
50
+ function corruptCompressed(cause) {
51
+ return Object.assign(new Error('Compressed history cannot be decoded', { cause }),
52
+ { sourceReason: 'corrupt-compressed-source' });
53
+ }
54
+
55
+ // Node's Zstandard stream can return successfully at the end of a truncated
56
+ // frame. Check the framing as the bytes pass through the native decoder.
57
+ // The decoder still validates compressed blocks and content checksums.
58
+ class ZstdFrames {
59
+ header = Buffer.alloc(4);
60
+ state = 'magic';
61
+ fill = 0;
62
+ headerSize = 4;
63
+ skip = 0;
64
+ checksum = false;
65
+ frames = 0;
66
+
67
+ next(state, headerSize, skip = 0) {
68
+ this.state = state;
69
+ this.headerSize = headerSize;
70
+ this.skip = skip;
71
+ this.fill = 0;
72
+ }
73
+
74
+ headerReady() {
75
+ if (this.state === 'magic') {
76
+ const magic = this.header.readUInt32LE();
77
+ if (magic === 0xfd2fb528) this.next('frame', 1);
78
+ else if (magic >= 0x184d2a50 && magic <= 0x184d2a5f) this.next('skippable', 4);
79
+ else throw corruptCompressed();
80
+ } else if (this.state === 'skippable') {
81
+ this.next('magic', 4, this.header.readUInt32LE());
82
+ } else if (this.state === 'frame') {
83
+ const descriptor = this.header[0];
84
+ if (descriptor & 8) throw corruptCompressed();
85
+ const singleSegment = Boolean(descriptor & 32);
86
+ const sizeFlag = descriptor >>> 6;
87
+ const frameSizeBytes = sizeFlag ? (2 ** sizeFlag) : Number(singleSegment);
88
+ const dictionaryBytes = [0, 1, 2, 4][descriptor & 3];
89
+ this.checksum = Boolean(descriptor & 4);
90
+ this.next('block', 3, Number(!singleSegment) + frameSizeBytes + dictionaryBytes);
91
+ } else {
92
+ const bits = this.header.readUIntLE(0, 3);
93
+ const type = (bits >>> 1) & 3;
94
+ if (type === 3) throw corruptCompressed();
95
+ const payload = type === 1 ? 1 : bits >>> 3;
96
+ if (bits & 1) {
97
+ this.frames++;
98
+ this.next('magic', 4, payload + (this.checksum ? 4 : 0));
99
+ } else this.next('block', 3, payload);
100
+ }
101
+ }
102
+
103
+ update(chunk) {
104
+ let offset = 0;
105
+ while (offset < chunk.length) {
106
+ if (this.skip) {
107
+ const advance = Math.min(this.skip, chunk.length - offset);
108
+ this.skip -= advance;
109
+ offset += advance;
110
+ continue;
111
+ }
112
+ const size = Math.min(this.headerSize - this.fill, chunk.length - offset);
113
+ chunk.copy(this.header, this.fill, offset, offset + size);
114
+ this.fill += size;
115
+ offset += size;
116
+ if (this.fill === this.headerSize) this.headerReady();
117
+ }
118
+ }
119
+
120
+ finish() {
121
+ if (this.state !== 'magic' || this.fill || this.skip || !this.frames) throw corruptCompressed();
122
+ }
123
+ }
124
+
125
+ async function* checkedCompressedSource(file, signal) {
126
+ const structure = new ZstdFrames();
127
+ for await (const chunk of sourceChunks(file, signal)) {
128
+ structure.update(chunk);
129
+ yield chunk;
130
+ }
131
+ structure.finish();
132
+ }
133
+
134
+ async function* decompressedSource(file, signal) {
135
+ const input = Readable.from(checkedCompressedSource(file, signal), { objectMode: false });
136
+ const decoder = zlib.createZstdDecompress();
137
+ const done = pipeline(input, decoder).catch(error => error);
138
+ try {
139
+ yield* decoder;
140
+ const error = await done;
141
+ if (error) throw error;
142
+ } catch (error) {
143
+ if (signal?.aborted || error.sourceReason) throw error;
144
+ throw corruptCompressed(error);
145
+ } finally {
146
+ input.destroy();
147
+ decoder.destroy();
148
+ }
149
+ }
150
+
151
+ function parseRecord(parts, bytes) {
152
+ if (bytes > sourceValueLimit) return { gap: 'record-too-large' };
153
+ if (bytes === 0) return {};
154
+ try {
155
+ const text = utf8.decode(Buffer.concat(parts, bytes));
156
+ if (!text.trim()) return {};
157
+ const row = JSON.parse(text);
158
+ return row && typeof row === 'object' && !Array.isArray(row) ? { row, bytes } : { gap: 'malformed-record' };
159
+ } catch {
160
+ return { gap: 'malformed-record' };
161
+ }
162
+ }
163
+
164
+ export async function* sourceJsonl(file, { compressed, signal }) {
165
+ let parts = [];
166
+ let bytes = 0;
167
+ const chunks = compressed ? decompressedSource(file, signal) : sourceChunks(file, signal);
168
+ for await (const chunk of chunks) {
169
+ signal?.throwIfAborted();
170
+ let offset = 0;
171
+ while (offset < chunk.length) {
172
+ const newline = chunk.indexOf(10, offset);
173
+ const end = newline === -1 ? chunk.length : newline;
174
+ bytes += end - offset;
175
+ if (bytes <= sourceValueLimit) parts.push(chunk.subarray(offset, end));
176
+ else parts = [];
177
+ if (newline === -1) break;
178
+ const record = parseRecord(parts, bytes);
179
+ if (record.row || record.gap) yield record;
180
+ bytes = 0;
181
+ parts = [];
182
+ offset = newline + 1;
183
+ }
184
+ }
185
+ const record = parseRecord(parts, bytes);
186
+ if (record.row || record.gap) yield record;
187
+ }
188
+
189
+ export async function sourceJson(file, signal) {
190
+ const parts = [];
191
+ let bytes = 0;
192
+ for await (const chunk of sourceChunks(file, signal)) {
193
+ bytes += chunk.length;
194
+ if (bytes > sourceValueLimit) return { gap: 'record-too-large' };
195
+ parts.push(chunk);
196
+ }
197
+ return parseRecord(parts, bytes);
198
+ }