@twinsearth/timemachine-dsh-plugin 0.0.0-stage → 0.1.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,123 @@
1
+ /**
2
+ * Reading and validating DSH v4 session logs (multi-frame zstd).
3
+ */
4
+
5
+ import fs from 'node:fs';
6
+
7
+ import { decodeSessionLog, decompressFrame, scanFrames, scanFramesFromFile, rewriteSessionHeader } from './archive/zstd.mjs';
8
+
9
+ const HEADER_WINDOW = 512 * 1024;
10
+ const FULL_READ_LIMIT = 64 * 1024 * 1024;
11
+
12
+ function parseFirstLine(text) {
13
+ const newline = text.indexOf('\n');
14
+ const line = newline === -1 ? text : text.slice(0, newline);
15
+ try {
16
+ const parsed = JSON.parse(line);
17
+ return parsed !== null && typeof parsed === 'object' ? parsed : null;
18
+ } catch {
19
+ return null;
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Read only enough of a session log to learn its header, plus a header-only
25
+ * frame walk for the frame count and torn tail.
26
+ * @param {string} file
27
+ * @returns {{header: object|null, error: string|null, frame_count: number, torn_tail: boolean}}
28
+ */
29
+ export function readSessionHeader(file) {
30
+ let walk = null;
31
+ try {
32
+ walk = scanFramesFromFile(file);
33
+ } catch (error) {
34
+ return { header: null, error: error instanceof Error ? error.message : String(error), frame_count: 0, torn_tail: false };
35
+ }
36
+ let fd = null;
37
+ try {
38
+ fd = fs.openSync(file, 'r');
39
+ const size = fs.fstatSync(fd).size;
40
+ if (walk.frames.length === 0) {
41
+ return { header: null, error: 'no complete zstd frame', frame_count: 0, torn_tail: walk.tornStart !== undefined };
42
+ }
43
+ const first = walk.frames[0];
44
+ const length = Math.min(size, Math.max(HEADER_WINDOW, first.end));
45
+ const buffer = Buffer.allocUnsafe(length);
46
+ const read = fs.readSync(fd, buffer, 0, length, 0);
47
+ const prefix = buffer.subarray(0, read);
48
+ const frames = scanFrames(prefix, 1).frames;
49
+ if (frames.length === 0) {
50
+ return { header: null, error: 'first frame is incomplete within the header window', frame_count: walk.frames.length, torn_tail: walk.tornStart !== undefined };
51
+ }
52
+ const text = decompressFrame(prefix.subarray(frames[0].start, frames[0].end));
53
+ const header = parseFirstLine(text);
54
+ return {
55
+ header,
56
+ error: header?.type === 'session' ? null : 'first line is not a session header',
57
+ frame_count: walk.frames.length,
58
+ torn_tail: walk.tornStart !== undefined,
59
+ };
60
+ } catch (error) {
61
+ return { header: null, error: error instanceof Error ? error.message : String(error), frame_count: walk.frames.length, torn_tail: walk.tornStart !== undefined };
62
+ } finally {
63
+ if (fd !== null) {
64
+ try { fs.closeSync(fd); } catch { /* already closed */ }
65
+ }
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Fully decode a session log and report structural problems without throwing.
71
+ * A torn tail (a crash during append) is tolerated; a bad frame in the middle
72
+ * is an error.
73
+ * @param {Buffer} buffer
74
+ */
75
+ export function inspectSessionBuffer(buffer) {
76
+ try {
77
+ const decoded = decodeSessionLog(buffer);
78
+ if (decoded.header === null) {
79
+ return { ok: false, reason: 'session header missing or not JSON', decoded };
80
+ }
81
+ return {
82
+ ok: true,
83
+ header: decoded.header,
84
+ events: decoded.events.length,
85
+ frame_count: decoded.frameCount,
86
+ torn_tail: decoded.tornStart !== null,
87
+ bytes: decoded.bytes,
88
+ };
89
+ } catch (error) {
90
+ return { ok: false, reason: error instanceof Error ? error.message : String(error), decoded: null };
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Rewrite `header.cwd` for a cross-platform restore and keep all later frames.
96
+ * @param {Buffer} buffer
97
+ * @param {string} cwd
98
+ */
99
+ export function remapSessionCwd(buffer, cwd) {
100
+ return rewriteSessionHeader(buffer, (header) => ({ ...header, cwd }));
101
+ }
102
+
103
+ /**
104
+ * Read a session file with a size ceiling.
105
+ * @param {string} file
106
+ * @param {number} maxBytes
107
+ */
108
+ export function readSessionFile(file, maxBytes) {
109
+ const stat = fs.statSync(file);
110
+ if (!stat.isFile()) return { ok: false, reason: 'not a regular file', size: 0 };
111
+ if (stat.size > maxBytes) return { ok: false, reason: `file is ${stat.size} bytes, over the ${maxBytes} byte ceiling`, size: stat.size };
112
+ return { ok: true, buffer: fs.readFileSync(file), size: stat.size };
113
+ }
114
+
115
+ /** Whether a session header looks like the v4 shape DSH writes. */
116
+ export function isV4Header(header) {
117
+ return header !== null
118
+ && typeof header === 'object'
119
+ && header.type === 'session'
120
+ && header.version === 4
121
+ && typeof header.id === 'string'
122
+ && typeof header.cwd === 'string';
123
+ }
@@ -0,0 +1,92 @@
1
+ import { createHash } from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ /** SHA-256 of a Buffer, lowercase hex. */
6
+ export function sha256(data) {
7
+ return createHash('sha256').update(data).digest('hex');
8
+ }
9
+
10
+ /** Read JSON, returning `fallback` for a missing or malformed file. */
11
+ export function readJson(file, fallback = null) {
12
+ try {
13
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
14
+ } catch {
15
+ return fallback;
16
+ }
17
+ }
18
+
19
+ /** Create a directory and return it. */
20
+ export function ensureDir(dir) {
21
+ fs.mkdirSync(dir, { recursive: true });
22
+ return dir;
23
+ }
24
+
25
+ /** Write a file through a sibling temp file and rename, so a crash cannot leave half a config. */
26
+ export function atomicWriteFile(file, data, mode = 0o600) {
27
+ ensureDir(path.dirname(file));
28
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
29
+ fs.writeFileSync(tmp, data, { mode });
30
+ try {
31
+ fs.renameSync(tmp, file);
32
+ } catch (error) {
33
+ try { fs.rmSync(tmp, { force: true }); } catch { /* best effort */ }
34
+ throw error;
35
+ }
36
+ return file;
37
+ }
38
+
39
+ /** Atomic JSON write with a trailing newline. */
40
+ export function atomicWriteJson(file, value, mode = 0o600) {
41
+ return atomicWriteFile(file, `${JSON.stringify(value, null, 2)}\n`, mode);
42
+ }
43
+
44
+ /** Whether `child` is inside `parent` (or equal to it). Both paths must be absolute. */
45
+ export function isInside(parent, child) {
46
+ const rel = path.relative(path.resolve(parent), path.resolve(child));
47
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
48
+ }
49
+
50
+ /** Reject archive entry names that could escape the extraction root. */
51
+ export function isSafeArchiveName(name) {
52
+ if (typeof name !== 'string' || name === '' || name.length > 4096) return false;
53
+ if (name.includes('\0')) return false;
54
+ const normalized = name.replaceAll('\\', '/');
55
+ if (normalized.startsWith('/') || /^[A-Za-z]:/u.test(normalized)) return false;
56
+ const parts = normalized.split('/');
57
+ return parts.every((part) => part !== '' && part !== '.' && part !== '..');
58
+ }
59
+
60
+ /** A filesystem-safe single path segment from a display name. */
61
+ export function safeSegment(value, fallback = 'item') {
62
+ const text = String(value ?? '').replace(/[<>:"/\\|?*\u0000-\u001f]/gu, '_').replace(/[. ]+$/u, '').trim();
63
+ const clipped = text.slice(0, 120);
64
+ return clipped === '' || clipped === '.' || clipped === '..' ? fallback : clipped;
65
+ }
66
+
67
+ /** Human byte count used by CLI logs and README generation. */
68
+ export function formatBytes(bytes) {
69
+ const value = Number(bytes);
70
+ if (!Number.isFinite(value) || value <= 0) return '0 B';
71
+ if (value >= 1024 ** 3) return `${(value / 1024 ** 3).toFixed(2)} GB`;
72
+ if (value >= 1024 ** 2) return `${(value / 1024 ** 2).toFixed(1)} MB`;
73
+ if (value >= 1024) return `${(value / 1024).toFixed(1)} KB`;
74
+ return `${value} B`;
75
+ }
76
+
77
+ /** Local compact timestamp: 20261203-221500. */
78
+ export function stamp(now = new Date()) {
79
+ const pad = (value) => String(value).padStart(2, '0');
80
+ return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
81
+ }
82
+
83
+ /** Copy a file preserving mtime, creating parent directories. */
84
+ export function copyFileDurable(source, target) {
85
+ ensureDir(path.dirname(target));
86
+ fs.copyFileSync(source, target);
87
+ try {
88
+ const stat = fs.statSync(source);
89
+ fs.utimesSync(target, stat.atime, stat.mtime);
90
+ } catch { /* mtime is cosmetic */ }
91
+ return target;
92
+ }
@@ -0,0 +1,82 @@
1
+ import os from 'node:os';
2
+ import path from 'node:path';
3
+
4
+ /** Resolve this machine's DSH home. `DSH_HOME` wins; otherwise `~/.dsh`. */
5
+ export function resolveDshHome(explicit) {
6
+ if (typeof explicit === 'string' && explicit.trim() !== '') return path.resolve(explicit.trim());
7
+ const env = process.env.DSH_HOME;
8
+ if (typeof env === 'string' && env.trim() !== '') return path.resolve(env.trim());
9
+ return path.join(os.homedir(), '.dsh');
10
+ }
11
+
12
+ /** The profile directory under a DSH home. */
13
+ export function profileDir(dshHome, profile = 'desktop') {
14
+ return path.join(dshHome, 'profiles', profile);
15
+ }
16
+
17
+ /**
18
+ * DSH's project directory key (dsh-session-persistence-jsonl/src/format.ts).
19
+ * Kept byte-for-byte compatible: separators collapse to one `-`, unsafe code
20
+ * units become `~XXXX`, leading dashes are dropped, and the slug is bounded.
21
+ */
22
+ export function projectKey(cwd) {
23
+ if (typeof cwd !== 'string' || cwd.length === 0) throw new Error('cannot encode an empty project path');
24
+ let readable = '';
25
+ let separatorRun = false;
26
+ for (let i = 0; i < cwd.length; i += 1) {
27
+ const code = cwd.charCodeAt(i);
28
+ const ch = String.fromCharCode(code);
29
+ if (ch === '/' || ch === '\\' || ch === ':') {
30
+ if (!separatorRun) readable += '-';
31
+ separatorRun = true;
32
+ } else if (ch !== '~' && /^[A-Za-z0-9._-]$/u.test(ch)) {
33
+ readable += ch;
34
+ separatorRun = false;
35
+ } else {
36
+ readable += `~${code.toString(16).toUpperCase().padStart(4, '0')}`;
37
+ separatorRun = false;
38
+ }
39
+ }
40
+ const slug = readable.replace(/^-+/u, '') || 'root';
41
+ return `--${slug.slice(0, 251)}--`;
42
+ }
43
+
44
+ /** DSH's session-id path segment encoder. */
45
+ export function encodeSegment(raw) {
46
+ const text = String(raw ?? '');
47
+ if (text.length === 0) throw new Error('cannot encode an empty path segment');
48
+ if (text === '.') return '~002E';
49
+ if (text === '..') return '~002E~002E';
50
+ let out = '';
51
+ for (let i = 0; i < text.length; i += 1) {
52
+ const code = text.charCodeAt(i);
53
+ const ch = String.fromCharCode(code);
54
+ if (ch !== '~' && /^[A-Za-z0-9._-]$/u.test(ch)) out += ch;
55
+ else out += `~${code.toString(16).toUpperCase().padStart(4, '0')}`;
56
+ }
57
+ return out;
58
+ }
59
+
60
+ /** `~/.dsh/sessions/<project-key>/<encoded-session-id>`. */
61
+ export function sessionDir(dshHome, cwd, sessionId) {
62
+ return path.join(dshHome, 'sessions', projectKey(cwd), encodeSegment(sessionId));
63
+ }
64
+
65
+ /** The session log file name used by DSH 0.2.x. */
66
+ export const SESSION_LOG = 'session.v4.jsonl.zstd';
67
+
68
+ /** Platform label used by the UI. */
69
+ export function platformLabel(platform = process.platform) {
70
+ return platform === 'win32' ? 'Windows' : platform === 'darwin' ? 'macOS' : 'Linux';
71
+ }
72
+
73
+ /** True when a path is a Windows drive path (imported from a Windows machine). */
74
+ export function isWindowsPath(value) {
75
+ return typeof value === 'string' && (/^[A-Za-z]:[\\/]/u.test(value) || value.startsWith('\\\\'));
76
+ }
77
+
78
+ /** Normalize a user-entered path for comparisons; case-insensitive on Windows. */
79
+ export function pathKey(value) {
80
+ const resolved = path.resolve(value);
81
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
82
+ }