simcast-host 0.0.0-stage → 0.9.1

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/common.js ADDED
@@ -0,0 +1,119 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+
4
+ export const VERSION = '0.9.1';
5
+ // The agent's protocol range: it serves clients of protocol MIN_CLIENT_PROTOCOL
6
+ // to PROTOCOL, and reports the one it agrees on with each client (see
7
+ // negotiateProtocol). PROTOCOL must match the Rust core's (crates/core/src/version.rs,
8
+ // which also has MIN_AGENT_PROTOCOL, the client's half of the rule).
9
+ // test/version.test.js checks both. See "Versioning" in docs/protocol.md.
10
+ export const PROTOCOL = 2;
11
+ export const MIN_CLIENT_PROTOCOL = 2;
12
+ // Clients send their protocol with every request and upgrade.
13
+ export const PROTOCOL_HEADER = 'x-simcast-protocol';
14
+
15
+ // The protocol the agent reports to a client (`protocol` in /health and the
16
+ // hellos): min(header, max), where a missing or malformed header means 1 (a
17
+ // client too old to send it). Below `min` the agent reports `max`, so the
18
+ // client says "update this PC".
19
+ export function negotiateProtocol(header, { min = MIN_CLIENT_PROTOCOL, max = PROTOCOL } = {}) {
20
+ const raw = Array.isArray(header) ? header[0] : header;
21
+ const n = typeof raw === 'string' && /^\s*\d+\s*$/.test(raw) ? Number(raw) : 1;
22
+ const p = Math.min(n, max);
23
+ return p < min ? max : p;
24
+ }
25
+ export const DEFAULT_PORT = 7878;
26
+ export const DEFAULT_METRO_PORT = 8081;
27
+
28
+ // Never synced, at any depth.
29
+ export const IGNORE_ANYWHERE = new Set([
30
+ 'node_modules', '.git', '.expo', '.simcast', '.turbo', '.next',
31
+ 'coverage', 'Pods', '.DS_Store', 'Thumbs.db', '.gradle', '.idea',
32
+ ]);
33
+ // Never synced when they sit at the project root. ("ios" is added in prebuild mode.)
34
+ export const IGNORE_AT_ROOT = new Set(['android', 'dist', 'web-build']);
35
+
36
+ export const LOCKFILES = [
37
+ ['bun.lock', ['bun', 'install', '--frozen-lockfile']],
38
+ ['bun.lockb', ['bun', 'install', '--frozen-lockfile']],
39
+ ['pnpm-lock.yaml', ['pnpm', 'install', '--frozen-lockfile']],
40
+ ['yarn.lock', ['yarn', 'install', '--frozen-lockfile']],
41
+ ['package-lock.json', ['npm', 'ci']],
42
+ ];
43
+
44
+ export function sha1(data) {
45
+ return crypto.createHash('sha1').update(data).digest('hex');
46
+ }
47
+
48
+ export function sha1File(file) {
49
+ return new Promise((resolve, reject) => {
50
+ const hash = crypto.createHash('sha1');
51
+ fs.createReadStream(file)
52
+ .on('data', (chunk) => hash.update(chunk))
53
+ .on('end', () => resolve(hash.digest('hex')))
54
+ .on('error', reject);
55
+ });
56
+ }
57
+
58
+ export function globToRegExp(glob) {
59
+ const body = glob
60
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
61
+ .replace(/\*\*/g, '\u0000')
62
+ .replace(/\*/g, '[^/]*')
63
+ .replace(/\?/g, '[^/]')
64
+ .replace(/\u0000/g, '.*');
65
+ return new RegExp(`^${body}$`);
66
+ }
67
+
68
+ export function isValidProjectId(id) {
69
+ return typeof id === 'string' && /^[A-Za-z0-9._-]{1,120}$/.test(id) && id !== '.' && id !== '..';
70
+ }
71
+
72
+ // Relative POSIX path that cannot escape the project folder.
73
+ export function isSafeRelPath(p) {
74
+ if (typeof p !== 'string' || !p || p.includes('\0') || p.includes('\\')) return false;
75
+ if (p.startsWith('/') || /^[A-Za-z]:/.test(p)) return false;
76
+ return !p.split('/').some((seg) => seg === '..' || seg === '' || seg === '.');
77
+ }
78
+
79
+ const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
80
+ const paint = (code) => (s) => (useColor ? `\x1b[${code}m${s}\x1b[0m` : String(s));
81
+ export const color = {
82
+ bold: paint('1'), dim: paint('2'), red: paint('31'),
83
+ green: paint('32'), yellow: paint('33'), cyan: paint('36'),
84
+ };
85
+
86
+ // Pings a WebSocket and ends it when the other side stops answering, so a pulled
87
+ // cable, a dropped Wi-Fi link or a sleeping machine is noticed in seconds rather
88
+ // than when TCP gives up minutes later. Any incoming data also counts as a sign of life.
89
+ export const HEARTBEAT_MS = 1000;
90
+ export const HEARTBEAT_TIMEOUT_MS = 3000;
91
+ export function heartbeat(ws, { onDead } = {}) {
92
+ let lastSeen = Date.now();
93
+ const alive = () => { lastSeen = Date.now(); };
94
+ ws.on('pong', alive);
95
+ ws.on('message', alive);
96
+ const timer = setInterval(() => {
97
+ if (ws.readyState !== 1) return;
98
+ if (Date.now() - lastSeen > HEARTBEAT_TIMEOUT_MS) {
99
+ clearInterval(timer);
100
+ onDead?.();
101
+ ws.terminate();
102
+ return;
103
+ }
104
+ try { ws.ping(); } catch { /* closing */ }
105
+ }, HEARTBEAT_MS);
106
+ ws.on('close', () => clearInterval(timer));
107
+ return { lastSeen: () => lastSeen };
108
+ }
109
+
110
+ export async function mapLimit(items, limit, fn) {
111
+ let i = 0;
112
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
113
+ while (i < items.length) {
114
+ const idx = i++;
115
+ await fn(items[idx], idx);
116
+ }
117
+ });
118
+ await Promise.all(workers);
119
+ }