remotessd 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.
- package/README.md +60 -2
- package/package.json +10 -4
- package/remotessd.mjs +359 -0
package/README.md
CHANGED
|
@@ -1,3 +1,61 @@
|
|
|
1
|
-
#
|
|
1
|
+
# remotessd
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Command-line client for [remoteSSD](https://remotessd.com), a shared drive for people and AI agents.
|
|
4
|
+
Node 20 or later (`watch` needs Node 22), no dependencies.
|
|
5
|
+
|
|
6
|
+
AI agents setting up a drive for someone: follow https://remotessd.com/join.txt.
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
npm install -g remotessd # or run it without installing: npx -y remotessd <command>
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Log in with a key
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
remotessd login --key rssd_... # or leave out --key and paste it on stdin
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
The key is checked and saved to `~/.config/remotessd/config.json` (mode 600). Instead of logging in you
|
|
21
|
+
can set the settings per command, which override the saved login:
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
REMOTESSD_URL=https://app.remotessd.com REMOTESSD_DRIVE=- REMOTESSD_KEY=rssd_... npx -y remotessd ls /
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
`REMOTESSD_URL` defaults to `https://app.remotessd.com` and `REMOTESSD_DRIVE` to `-` (the drive the key
|
|
28
|
+
belongs to). `login` also takes `--url` and `--drive`.
|
|
29
|
+
|
|
30
|
+
## Commands
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
remotessd ls [-l] [--json] [PATH] list a folder (default /)
|
|
34
|
+
remotessd stat [--json] PATH size, version, kind, mode and time
|
|
35
|
+
remotessd cat [-v] [--range A-B] PATH print a file; -v prints "version N" to stderr
|
|
36
|
+
remotessd cp ./big.iso :/isos/big.iso copy; the drive side starts with a colon, - is stdin/stdout
|
|
37
|
+
remotessd put PATH [FILE|-] [--if-unchanged V | --if-absent]
|
|
38
|
+
write FILE or stdin; safe writes refuse if the file changed
|
|
39
|
+
remotessd mv SRC DST move or rename (atomic)
|
|
40
|
+
remotessd rm [-r] PATH delete a file or folder
|
|
41
|
+
remotessd mkdir [-p] PATH create a folder
|
|
42
|
+
remotessd search [--path DIR] [--in name|content] [--limit N] [--json] QUERY
|
|
43
|
+
remotessd watch [--json] print changes as they happen
|
|
44
|
+
remotessd help
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Safe update loop: `remotessd cat -v F > f 2> ver`, edit `f`, then
|
|
48
|
+
`remotessd put F f --if-unchanged "$(cut -d' ' -f2 ver)"`; on exit code 4, read again and retry.
|
|
49
|
+
|
|
50
|
+
## Exit codes
|
|
51
|
+
|
|
52
|
+
| Code | Meaning |
|
|
53
|
+
| --- | --- |
|
|
54
|
+
| 0 | OK |
|
|
55
|
+
| 1 | Other error |
|
|
56
|
+
| 2 | Bad usage or not logged in |
|
|
57
|
+
| 3 | Not found (also `search` with no results) |
|
|
58
|
+
| 4 | Conflict: safe write refused, already exists, or folder not empty |
|
|
59
|
+
| 5 | Key refused |
|
|
60
|
+
| 6 | Network or server error |
|
|
61
|
+
| 7 | Request limit reached |
|
package/package.json
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "remotessd",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Command-line client for remoteSSD, a shared drive for people and AI agents",
|
|
5
|
+
"keywords": ["remotessd", "drive", "storage", "cli", "agents"],
|
|
6
|
+
"homepage": "https://remotessd.com",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"bin": { "remotessd": "remotessd.mjs" },
|
|
9
|
+
"files": ["remotessd.mjs", "README.md"],
|
|
10
|
+
"engines": { "node": ">=20" },
|
|
11
|
+
"license": "UNLICENSED"
|
|
12
|
+
}
|
package/remotessd.mjs
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// remotessd: command-line client for a remoteSSD drive. Node 20+ (watch needs 22+), no dependencies.
|
|
3
|
+
// Run `remotessd help` for usage. Exit codes are listed in HELP below.
|
|
4
|
+
import { readFileSync, writeFileSync, mkdirSync, existsSync, createReadStream, statSync, renameSync, unlinkSync, chmodSync } from "node:fs";
|
|
5
|
+
import { open } from "node:fs/promises";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
import { join, dirname, basename } from "node:path";
|
|
8
|
+
|
|
9
|
+
const VERSION = "0.1.0";
|
|
10
|
+
const CHUNK = 4 * 1024 * 1024; // the drive stores big files in 4 MB chunks
|
|
11
|
+
const SMALL = 8 * 1024 * 1024; // files up to this size go up and down in one request
|
|
12
|
+
const PAR = 4; // chunk requests in flight
|
|
13
|
+
const DEFAULT_URL = "https://app.remotessd.com";
|
|
14
|
+
|
|
15
|
+
const EXIT = { OK: 0, ERROR: 1, USAGE: 2, NOTFOUND: 3, CONFLICT: 4, AUTH: 5, NETWORK: 6, QUOTA: 7 };
|
|
16
|
+
const HELP = `remotessd ${VERSION}: use a remoteSSD drive from scripts.
|
|
17
|
+
|
|
18
|
+
Usage: remotessd <command> [options]
|
|
19
|
+
|
|
20
|
+
login [--key KEY] [--url URL] [--drive NAME] check a key and save it (key is read from stdin if not given)
|
|
21
|
+
ls [-l] [--json] [PATH] list a folder (default /)
|
|
22
|
+
stat [--json] PATH show size, version, kind, mode and time
|
|
23
|
+
cat [-v] [--range A-B] PATH print a file; -v prints "version N" to stderr
|
|
24
|
+
cp SRC DST copy; mark the drive side with a leading colon:
|
|
25
|
+
remotessd cp ./big.iso :/isos/big.iso
|
|
26
|
+
remotessd cp :/isos/big.iso ./big.iso
|
|
27
|
+
use - for stdin or stdout. Big files move in 4 MB parts.
|
|
28
|
+
put PATH [FILE|-] [--if-unchanged V | --if-absent]
|
|
29
|
+
write FILE (or stdin) to PATH. --if-unchanged V saves only
|
|
30
|
+
if PATH is still at version V; --if-absent only if it doesn't exist
|
|
31
|
+
mv SRC DST move or rename a file or folder (atomic)
|
|
32
|
+
rm [-r] PATH delete a file, or an empty folder; -r deletes a folder tree
|
|
33
|
+
mkdir [-p] PATH create a folder; -p creates parents and accepts an existing folder
|
|
34
|
+
search [--path DIR] [--in name|content] [--limit N] [--json] QUERY
|
|
35
|
+
watch [--json] print changes made to the drive as they happen
|
|
36
|
+
|
|
37
|
+
Settings come from ~/.config/remotessd/config.json (written by login), overridden by
|
|
38
|
+
REMOTESSD_URL, REMOTESSD_DRIVE and REMOTESSD_KEY. The URL defaults to ${DEFAULT_URL} and the
|
|
39
|
+
drive to "-" (the drive the key belongs to). Agents: see https://remotessd.com/join.txt
|
|
40
|
+
|
|
41
|
+
Exit codes: 0 ok, 1 other error, 2 bad usage, 3 not found, 4 conflict (safe write refused,
|
|
42
|
+
already exists, folder not empty), 5 key refused, 6 network or server error, 7 request limit reached.`;
|
|
43
|
+
|
|
44
|
+
class Fail extends Error { constructor(code, msg) { super(msg); this.code = code; } }
|
|
45
|
+
|
|
46
|
+
// ---------- settings ----------
|
|
47
|
+
const cfgDir = process.env.REMOTESSD_CONFIG_DIR || join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "remotessd");
|
|
48
|
+
const cfgFile = join(cfgDir, "config.json");
|
|
49
|
+
function loadCfg() {
|
|
50
|
+
let c = {};
|
|
51
|
+
try { c = JSON.parse(readFileSync(cfgFile, "utf8")); } catch {}
|
|
52
|
+
return {
|
|
53
|
+
url: (process.env.REMOTESSD_URL || c.url || DEFAULT_URL).replace(/\/+$/, ""),
|
|
54
|
+
drive: process.env.REMOTESSD_DRIVE || c.drive || "-",
|
|
55
|
+
key: process.env.REMOTESSD_KEY || c.key || "",
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// ---------- HTTP ----------
|
|
60
|
+
function client(cfg) {
|
|
61
|
+
if (!cfg.url || !cfg.key) throw new Fail(EXIT.USAGE, "not logged in: run `remotessd login` or set REMOTESSD_KEY");
|
|
62
|
+
const call = async (op, q = {}, init = {}) => {
|
|
63
|
+
const qs = new URLSearchParams(Object.entries(q).filter(([, v]) => v != null).map(([k, v]) => [k, String(v)]));
|
|
64
|
+
let r;
|
|
65
|
+
for (let attempt = 0; ; attempt++) {
|
|
66
|
+
try {
|
|
67
|
+
r = await fetch(`${cfg.url}/d/${encodeURIComponent(cfg.drive)}/${op}?${qs}`, { ...init, headers: { authorization: `Bearer ${cfg.key}`, "x-client": "cli", ...(init.headers || {}) } });
|
|
68
|
+
} catch (e) {
|
|
69
|
+
if (attempt < 2 && init.method !== "POST") { await new Promise((s) => setTimeout(s, 300 * (attempt + 1))); continue; }
|
|
70
|
+
throw new Fail(EXIT.NETWORK, `network error: ${e.cause?.code || e.message}`);
|
|
71
|
+
}
|
|
72
|
+
// Retry server errors on reads only; a write may have been applied.
|
|
73
|
+
if (r.status >= 500 && attempt < 2 && (init.method || "GET") === "GET") { await new Promise((s) => setTimeout(s, 300 * (attempt + 1))); continue; }
|
|
74
|
+
return r;
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
const check = async (r, what) => {
|
|
78
|
+
if (r.ok) return r;
|
|
79
|
+
let b = {};
|
|
80
|
+
const t = await r.text();
|
|
81
|
+
try { b = JSON.parse(t); } catch { b = { error: t.slice(0, 200) }; }
|
|
82
|
+
const e = b.errno || "";
|
|
83
|
+
if (r.status === 401 || r.status === 403) throw new Fail(EXIT.AUTH, "key refused");
|
|
84
|
+
if (r.status === 429) throw new Fail(EXIT.QUOTA, "request limit reached");
|
|
85
|
+
if (r.status === 404) throw new Fail(EXIT.NOTFOUND, `${what}: not found`);
|
|
86
|
+
if (r.status === 409) {
|
|
87
|
+
const err = new Fail(EXIT.CONFLICT, e === "ECONFLICT" ? `${what}: changed since version given (now version ${b.version})`
|
|
88
|
+
: e === "EEXIST" ? `${what}: already exists${b.version != null ? ` (version ${b.version})` : ""}` : `${what}: ${e || "conflict"}`);
|
|
89
|
+
err.version = b.version; err.errno = e; throw err;
|
|
90
|
+
}
|
|
91
|
+
if (r.status >= 500) throw new Fail(EXIT.NETWORK, `${what}: server error ${r.status} ${b.error || ""}`.trim());
|
|
92
|
+
throw new Fail(EXIT.ERROR, `${what}: ${e || r.status} ${b.error || ""}`.trim());
|
|
93
|
+
};
|
|
94
|
+
const json = async (op, q, init, what = q?.path) => (await check(await call(op, q, init), what)).json();
|
|
95
|
+
return { call, check, json };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function pool(n, total, fn) {
|
|
99
|
+
let i = 0;
|
|
100
|
+
await Promise.all(Array.from({ length: Math.min(n, total) }, async () => { while (i < total) await fn(i++); }));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ---------- helpers ----------
|
|
104
|
+
const rpath = (p) => "/" + String(p || "/").replace(/^:/, "").split("/").filter(Boolean).join("/");
|
|
105
|
+
const kindName = { f: "file", d: "dir", l: "link" };
|
|
106
|
+
function parseArgs(argv, spec) {
|
|
107
|
+
// spec: { flag: "bool" | "value" }, aliases as "-l": "long"
|
|
108
|
+
const opts = {}, pos = [];
|
|
109
|
+
for (let i = 0; i < argv.length; i++) {
|
|
110
|
+
const a = argv[i];
|
|
111
|
+
if (a === "--") { pos.push(...argv.slice(i + 1)); break; }
|
|
112
|
+
if (a.startsWith("-") && a !== "-") {
|
|
113
|
+
let [name, val] = a.replace(/^--?/, "").split(/=(.*)/s);
|
|
114
|
+
name = spec.alias?.[name] || name;
|
|
115
|
+
if (!(name in spec)) throw new Fail(EXIT.USAGE, `unknown option ${a}`);
|
|
116
|
+
if (spec[name] === "bool") opts[name] = true;
|
|
117
|
+
else { if (val === undefined) { val = argv[++i]; if (val === undefined) throw new Fail(EXIT.USAGE, `${a} needs a value`); } opts[name] = val; }
|
|
118
|
+
} else pos.push(a);
|
|
119
|
+
}
|
|
120
|
+
return { opts, pos };
|
|
121
|
+
}
|
|
122
|
+
const need = (pos, n, usage) => { if (pos.length < n) throw new Fail(EXIT.USAGE, `usage: remotessd ${usage}`); };
|
|
123
|
+
const fmtTime = (ms) => new Date(ms).toISOString().replace("T", " ").slice(0, 19);
|
|
124
|
+
const out = (s) => process.stdout.write(s);
|
|
125
|
+
|
|
126
|
+
async function readStdin() { const parts = []; for await (const c of process.stdin) parts.push(c); return Buffer.concat(parts); }
|
|
127
|
+
|
|
128
|
+
// Uploads a local file (or a buffer) to PATH. Small data goes in one write request; bigger files go as
|
|
129
|
+
// 4 MB chunks (PAR at a time) followed by one commit. ifVersion makes it a safe write.
|
|
130
|
+
async function upload(c, path, src, ifVersion) {
|
|
131
|
+
const q = { path, ifVersion };
|
|
132
|
+
if (Buffer.isBuffer(src) && src.length <= SMALL) return c.json("write", q, { method: "POST", body: src });
|
|
133
|
+
const size = Buffer.isBuffer(src) ? src.length : statSync(src).size;
|
|
134
|
+
if (size <= SMALL) return c.json("write", q, { method: "POST", body: readFileSync(src) });
|
|
135
|
+
const n = Math.ceil(size / CHUNK), keys = new Array(n);
|
|
136
|
+
const fh = Buffer.isBuffer(src) ? null : await open(src, "r");
|
|
137
|
+
try {
|
|
138
|
+
await pool(PAR, n, async (i) => {
|
|
139
|
+
const len = Math.min(CHUNK, size - i * CHUNK);
|
|
140
|
+
let part;
|
|
141
|
+
if (fh) { part = Buffer.alloc(len); await fh.read(part, 0, len, i * CHUNK); } else part = src.subarray(i * CHUNK, i * CHUNK + len);
|
|
142
|
+
keys[i] = (await c.json("chunk", { path }, { method: "PUT", body: part })).key;
|
|
143
|
+
});
|
|
144
|
+
} finally { await fh?.close(); }
|
|
145
|
+
return c.json("commit", q, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ size, chunks: keys }) });
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Downloads PATH to a local file (or stdout with "-"). Big files come down as 4 MB ranges, PAR at a
|
|
149
|
+
// time, written in place into a temporary file that is renamed when complete.
|
|
150
|
+
async function download(c, path, dest) {
|
|
151
|
+
const st = await c.json("stat", { path });
|
|
152
|
+
if (st.kind === "d") throw new Fail(EXIT.ERROR, `${path}: is a folder`);
|
|
153
|
+
if (dest === "-" && st.size <= SMALL) {
|
|
154
|
+
const r = await c.check(await c.call("read", { path }), path);
|
|
155
|
+
out(Buffer.from(await r.arrayBuffer())); return st;
|
|
156
|
+
}
|
|
157
|
+
const tmp = dest === "-" ? null : join(dirname(dest), `.${basename(dest)}.remotessd-${process.pid}`);
|
|
158
|
+
const fh = tmp ? await open(tmp, "w") : null;
|
|
159
|
+
const n = Math.max(1, Math.ceil(st.size / CHUNK));
|
|
160
|
+
const done = new Map(); let next = 0; // for stdout: write parts in order
|
|
161
|
+
try {
|
|
162
|
+
await pool(PAR, n, async (i) => {
|
|
163
|
+
const a = i * CHUNK, b = Math.min(st.size, a + CHUNK) - 1;
|
|
164
|
+
const r = await c.check(await c.call("read", { path }, st.size ? { headers: { range: `bytes=${a}-${b}` } } : {}), path);
|
|
165
|
+
const md = JSON.parse(r.headers.get("x-meta") || "{}");
|
|
166
|
+
if (md.version !== st.version) throw new Fail(EXIT.CONFLICT, `${path}: changed while copying (version ${st.version} -> ${md.version}); try again`);
|
|
167
|
+
const buf = Buffer.from(await r.arrayBuffer());
|
|
168
|
+
if (fh) await fh.write(buf, 0, buf.length, a);
|
|
169
|
+
else { done.set(i, buf); while (done.has(next)) { out(done.get(next)); done.delete(next++); } }
|
|
170
|
+
});
|
|
171
|
+
if (fh) { await fh.close(); renameSync(tmp, dest); }
|
|
172
|
+
} catch (e) { if (fh) { await fh.close().catch(() => {}); try { unlinkSync(tmp); } catch {} } throw e; }
|
|
173
|
+
return st;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// ---------- commands ----------
|
|
177
|
+
const cmds = {
|
|
178
|
+
async login(argv) {
|
|
179
|
+
const { opts } = parseArgs(argv, { url: "value", drive: "value", key: "value" });
|
|
180
|
+
const cur = loadCfg();
|
|
181
|
+
const cfg = { url: (opts.url || cur.url).replace(/\/+$/, ""), drive: opts.drive || cur.drive, key: opts.key || "" };
|
|
182
|
+
if (!cfg.key) {
|
|
183
|
+
if (process.stdin.isTTY) process.stderr.write("Paste the drive key and press Enter: ");
|
|
184
|
+
cfg.key = (await readStdin()).toString().trim().split("\n")[0].trim();
|
|
185
|
+
}
|
|
186
|
+
if (!cfg.key) throw new Fail(EXIT.USAGE, "no key given");
|
|
187
|
+
await client(cfg).json("stat", { path: "/" }, {}, "/");
|
|
188
|
+
mkdirSync(cfgDir, { recursive: true, mode: 0o700 });
|
|
189
|
+
writeFileSync(cfgFile, JSON.stringify(cfg, null, 2) + "\n", { mode: 0o600 });
|
|
190
|
+
chmodSync(cfgFile, 0o600);
|
|
191
|
+
process.stderr.write(`Key works. Saved to ${cfgFile}\n`);
|
|
192
|
+
},
|
|
193
|
+
async ls(argv, c) {
|
|
194
|
+
const { opts, pos } = parseArgs(argv, { l: "bool", json: "bool", alias: { long: "l" } });
|
|
195
|
+
const path = rpath(pos[0]);
|
|
196
|
+
let b;
|
|
197
|
+
try { b = await c.json("list", { path }); }
|
|
198
|
+
catch (e) { if (e.code !== EXIT.ERROR) throw e; const s = await c.json("stat", { path }); b = { entries: [s] }; } // ls of a file
|
|
199
|
+
const es = b.entries.map(({ data, chunks, ...e }) => e).sort((x, y) => x.path.localeCompare(y.path));
|
|
200
|
+
if (opts.json) return out(JSON.stringify(es, null, 2) + "\n");
|
|
201
|
+
for (const e of es) {
|
|
202
|
+
const name = e.path === path ? basename(e.path) : e.path.slice(path === "/" ? 1 : path.length + 1);
|
|
203
|
+
out(opts.l ? `${kindName[e.kind].padEnd(4)} ${String(e.size).padStart(12)} v${String(e.version).padEnd(5)} ${fmtTime(e.mtime)} ${name}${e.kind === "d" ? "/" : ""}\n`
|
|
204
|
+
: `${name}${e.kind === "d" ? "/" : ""}\n`);
|
|
205
|
+
}
|
|
206
|
+
},
|
|
207
|
+
async stat(argv, c) {
|
|
208
|
+
const { opts, pos } = parseArgs(argv, { json: "bool" });
|
|
209
|
+
need(pos, 1, "stat PATH");
|
|
210
|
+
const { chunks, inline, hash, ...s } = await c.json("stat", { path: rpath(pos[0]) });
|
|
211
|
+
if (opts.json) return out(JSON.stringify(s, null, 2) + "\n");
|
|
212
|
+
out(`path: ${s.path}\nkind: ${kindName[s.kind]}\nsize: ${s.size}\nversion: ${s.version}\nmode: ${(s.mode & 0o7777).toString(8)}\nmodified: ${new Date(s.mtime).toISOString()}\n`);
|
|
213
|
+
},
|
|
214
|
+
async cat(argv, c) {
|
|
215
|
+
const { opts, pos } = parseArgs(argv, { v: "bool", range: "value", alias: { "with-version": "v" } });
|
|
216
|
+
need(pos, 1, "cat [-v] [--range A-B] PATH");
|
|
217
|
+
const path = rpath(pos[0]);
|
|
218
|
+
if (opts.range) {
|
|
219
|
+
if (!/^\d*-\d*$/.test(opts.range)) throw new Fail(EXIT.USAGE, "--range is A-B, A- or -N (bytes, B included)");
|
|
220
|
+
const r = await c.call("read", { path }, { headers: { range: `bytes=${opts.range}` } });
|
|
221
|
+
if (r.status === 416) return;
|
|
222
|
+
await c.check(r, path);
|
|
223
|
+
if (opts.v) process.stderr.write(`version ${JSON.parse(r.headers.get("x-meta")).version}\n`);
|
|
224
|
+
return out(Buffer.from(await r.arrayBuffer()));
|
|
225
|
+
}
|
|
226
|
+
// One request (one consistent version) unless the file is big.
|
|
227
|
+
const r = await c.check(await c.call("read", { path }, { headers: { range: `bytes=0-${SMALL - 1}` } }), path);
|
|
228
|
+
const md = JSON.parse(r.headers.get("x-meta"));
|
|
229
|
+
if (md.kind === "d") throw new Fail(EXIT.ERROR, `${path}: is a folder`);
|
|
230
|
+
if (md.size <= SMALL) {
|
|
231
|
+
if (opts.v) process.stderr.write(`version ${md.version}\n`);
|
|
232
|
+
return out(Buffer.from(await r.arrayBuffer()));
|
|
233
|
+
}
|
|
234
|
+
await r.body?.cancel();
|
|
235
|
+
const st = await download(c, path, "-");
|
|
236
|
+
if (opts.v) process.stderr.write(`version ${st.version}\n`);
|
|
237
|
+
},
|
|
238
|
+
async cp(argv, c) {
|
|
239
|
+
const { pos } = parseArgs(argv, {});
|
|
240
|
+
need(pos, 2, "cp SRC DST (prefix the drive path with a colon)");
|
|
241
|
+
const [src, dst] = pos;
|
|
242
|
+
const rs = src.startsWith(":"), rd = dst.startsWith(":");
|
|
243
|
+
if (rs === rd) throw new Fail(EXIT.USAGE, "cp: exactly one side must be a drive path starting with a colon, e.g. :/docs/a.txt");
|
|
244
|
+
if (rd) {
|
|
245
|
+
let path = rpath(dst);
|
|
246
|
+
if (dst.endsWith("/")) path = rpath(`${path}/${basename(src)}`);
|
|
247
|
+
if (src !== "-" && !existsSync(src)) throw new Fail(EXIT.NOTFOUND, `${src}: no such local file`);
|
|
248
|
+
const m = await upload(c, path, src === "-" ? await readStdin() : src);
|
|
249
|
+
process.stderr.write(`${path}: ${m.size} bytes, version ${m.version}\n`);
|
|
250
|
+
} else {
|
|
251
|
+
let dest = dst;
|
|
252
|
+
if (dst !== "-" && existsSync(dst) && statSync(dst).isDirectory()) dest = join(dst, basename(rpath(src)));
|
|
253
|
+
await download(c, rpath(src), dest);
|
|
254
|
+
}
|
|
255
|
+
},
|
|
256
|
+
async put(argv, c) {
|
|
257
|
+
const { opts, pos } = parseArgs(argv, { "if-unchanged": "value", "if-absent": "bool", "if-version": "value" });
|
|
258
|
+
need(pos, 1, "put PATH [FILE|-] [--if-unchanged VERSION | --if-absent]");
|
|
259
|
+
const iv = opts["if-unchanged"] ?? opts["if-version"];
|
|
260
|
+
if (iv != null && !/^\d+$/.test(iv)) throw new Fail(EXIT.USAGE, "--if-unchanged takes a version number");
|
|
261
|
+
const ifVersion = opts["if-absent"] ? 0 : iv != null ? Number(iv) : undefined;
|
|
262
|
+
const src = pos[1] && pos[1] !== "-" ? pos[1] : await readStdin();
|
|
263
|
+
if (!Buffer.isBuffer(src) && !existsSync(src)) throw new Fail(EXIT.NOTFOUND, `${src}: no such local file`);
|
|
264
|
+
const m = await upload(c, rpath(pos[0]), src, ifVersion);
|
|
265
|
+
out(`version ${m.version}\n`);
|
|
266
|
+
},
|
|
267
|
+
async mv(argv, c) {
|
|
268
|
+
const { pos } = parseArgs(argv, {});
|
|
269
|
+
need(pos, 2, "mv SRC DST");
|
|
270
|
+
await c.json("mv", { path: rpath(pos[0]), to: rpath(pos[1]) });
|
|
271
|
+
},
|
|
272
|
+
async rm(argv, c) {
|
|
273
|
+
const { opts, pos } = parseArgs(argv, { r: "bool", f: "bool", alias: { recursive: "r", force: "f", rf: "r" } });
|
|
274
|
+
need(pos, 1, "rm [-r] PATH");
|
|
275
|
+
for (const p of pos) {
|
|
276
|
+
const path = rpath(p);
|
|
277
|
+
try {
|
|
278
|
+
const r = await c.call("rm", { path });
|
|
279
|
+
if (r.ok) continue;
|
|
280
|
+
const b = await r.clone().json().catch(() => ({}));
|
|
281
|
+
if (b.errno !== "EISDIR") await c.check(r, path);
|
|
282
|
+
if (opts.r) await rmTree(c, path);
|
|
283
|
+
else await c.json("rmdir", { path }, {}, path);
|
|
284
|
+
} catch (e) { if (!(opts.f && e.code === EXIT.NOTFOUND)) throw e; }
|
|
285
|
+
}
|
|
286
|
+
},
|
|
287
|
+
async mkdir(argv, c) {
|
|
288
|
+
const { opts, pos } = parseArgs(argv, { p: "bool", alias: { parents: "p" } });
|
|
289
|
+
need(pos, 1, "mkdir [-p] PATH");
|
|
290
|
+
for (const p of pos) {
|
|
291
|
+
const parts = rpath(p).split("/").filter(Boolean);
|
|
292
|
+
for (let i = opts.p ? 1 : parts.length; i <= parts.length; i++) {
|
|
293
|
+
const path = "/" + parts.slice(0, i).join("/");
|
|
294
|
+
try { await c.json("mkdir", { path }); }
|
|
295
|
+
catch (e) {
|
|
296
|
+
if (!(opts.p && e.code === EXIT.CONFLICT)) throw e;
|
|
297
|
+
if ((await c.json("stat", { path })).kind !== "d") throw new Fail(EXIT.CONFLICT, `${path}: exists and is not a folder`);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
},
|
|
302
|
+
async search(argv, c) {
|
|
303
|
+
const { opts, pos } = parseArgs(argv, { path: "value", in: "value", limit: "value", json: "bool" });
|
|
304
|
+
need(pos, 1, "search [--path DIR] [--in name|content] [--limit N] QUERY");
|
|
305
|
+
if (opts.in && !["name", "content", "both"].includes(opts.in)) throw new Fail(EXIT.USAGE, "--in is name, content or both");
|
|
306
|
+
const b = await c.json("search", { q: pos.join(" "), path: rpath(opts.path), in: opts.in === "both" ? undefined : opts.in, limit: opts.limit }, {}, "search");
|
|
307
|
+
if (opts.json) return out(JSON.stringify(b, null, 2) + "\n");
|
|
308
|
+
for (const x of b.results) {
|
|
309
|
+
if (x.match === "name") out(`${x.path}${x.kind === "d" ? "/" : ""}\n`);
|
|
310
|
+
else for (const l of x.lines) out(`${x.path}:${l.line}:${l.text}\n`);
|
|
311
|
+
}
|
|
312
|
+
if (b.truncated) process.stderr.write(`(more results exist; use --limit or --path)\n`);
|
|
313
|
+
if (!b.results.length) process.exitCode = EXIT.NOTFOUND;
|
|
314
|
+
},
|
|
315
|
+
async watch(argv, c, cfg) {
|
|
316
|
+
const { opts } = parseArgs(argv, { json: "bool" });
|
|
317
|
+
if (typeof WebSocket !== "function") throw new Fail(EXIT.ERROR, `watch needs Node 22 or later (this is ${process.version})`);
|
|
318
|
+
const u = `${cfg.url.replace(/^http/, "ws")}/d/${encodeURIComponent(cfg.drive)}/watch?key=${encodeURIComponent(cfg.key)}`;
|
|
319
|
+
await new Promise((res, rej) => {
|
|
320
|
+
const ws = new WebSocket(u);
|
|
321
|
+
const ping = setInterval(() => { try { ws.send("ping"); } catch {} }, 30000);
|
|
322
|
+
ws.onopen = () => process.stderr.write("watching; Ctrl-C to stop\n");
|
|
323
|
+
ws.onmessage = (m) => {
|
|
324
|
+
if (m.data === "pong") return;
|
|
325
|
+
const ev = JSON.parse(m.data);
|
|
326
|
+
out(opts.json ? m.data + "\n" : `${new Date(ev.t).toISOString()} ${ev.type} ${ev.path}${ev.to ? " -> " + ev.to : ""}${ev.version ? " v" + ev.version : ""}\n`);
|
|
327
|
+
};
|
|
328
|
+
ws.onerror = () => { clearInterval(ping); rej(new Fail(EXIT.NETWORK, "change feed connection failed")); };
|
|
329
|
+
ws.onclose = () => { clearInterval(ping); res(); };
|
|
330
|
+
});
|
|
331
|
+
},
|
|
332
|
+
};
|
|
333
|
+
|
|
334
|
+
async function rmTree(c, dir) {
|
|
335
|
+
const { entries } = await c.json("list", { path: dir });
|
|
336
|
+
await pool(8, entries.length, async (i) => {
|
|
337
|
+
const e = entries[i];
|
|
338
|
+
if (e.kind === "d") await rmTree(c, e.path);
|
|
339
|
+
else await c.json("rm", { path: e.path });
|
|
340
|
+
});
|
|
341
|
+
await c.json("rmdir", { path: dir });
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
async function main() {
|
|
345
|
+
const [cmd, ...argv] = process.argv.slice(2);
|
|
346
|
+
if (!cmd || cmd === "help" || cmd === "--help" || cmd === "-h") { out(HELP + "\n"); return; }
|
|
347
|
+
if (cmd === "--version" || cmd === "version") { out(VERSION + "\n"); return; }
|
|
348
|
+
const fn = cmds[cmd];
|
|
349
|
+
if (cmd === "mount") throw new Fail(EXIT.USAGE, "this CLI does not mount; the mount needs the native client: curl -fsSL https://remotessd.com/install.sh | sh");
|
|
350
|
+
if (!fn) throw new Fail(EXIT.USAGE, `unknown command "${cmd}"; run remotessd help`);
|
|
351
|
+
if (cmd === "login") return fn(argv);
|
|
352
|
+
const cfg = loadCfg();
|
|
353
|
+
await fn(argv, client(cfg), cfg);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
main().catch((e) => {
|
|
357
|
+
process.stderr.write(`remotessd: ${e.message}\n`);
|
|
358
|
+
process.exitCode = e instanceof Fail ? e.code : EXIT.ERROR;
|
|
359
|
+
});
|