nemu-cli 1.5.0 → 1.6.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.
@@ -0,0 +1,204 @@
1
+ import { z } from "zod";
2
+ import { CliError } from "../errors.js";
3
+ const note_schema = z.object({
4
+ id: z.string(),
5
+ path: z.string(),
6
+ kind: z.string(),
7
+ version: z.number().int(),
8
+ hash: z.string(),
9
+ size: z.number(),
10
+ revision: z.number(),
11
+ deleted: z.boolean(),
12
+ });
13
+ const vault_schema = z.object({
14
+ id: z.string(),
15
+ name: z.string(),
16
+ revision: z.number(),
17
+ notes: z.number().optional(),
18
+ stored_bytes: z.number().optional(),
19
+ created_at: z.string().optional(),
20
+ updated_at: z.string().optional(),
21
+ });
22
+ const info_schema = z.object({
23
+ data: vault_schema,
24
+ workspace_id: z.string().optional(),
25
+ limits: z
26
+ .object({
27
+ max_file_bytes: z.number(),
28
+ max_storage_bytes: z.number().nullable(),
29
+ })
30
+ .optional(),
31
+ });
32
+ const version_schema = z.object({
33
+ version: z.number().int(),
34
+ path: z.string(),
35
+ hash: z.string(),
36
+ size: z.number(),
37
+ deleted: z.boolean(),
38
+ origin: z.string(),
39
+ origin_id: z.string().nullable(),
40
+ client: z.string().nullable(),
41
+ created_at: z.string(),
42
+ });
43
+ const failure_schema = z.object({
44
+ error: z.string().optional(),
45
+ code: z.string().optional(),
46
+ reference: z.string().optional(),
47
+ retry_after: z.number().optional(),
48
+ current: note_schema.nullable().optional(),
49
+ });
50
+ export class RemoteError extends CliError {
51
+ current;
52
+ constructor(message, code, status, current, reference) {
53
+ super(message, code, { status, reference });
54
+ this.name = "RemoteError";
55
+ this.current = current;
56
+ }
57
+ }
58
+ const MAX_WAIT_MS = 60_000;
59
+ const ATTEMPTS = 4;
60
+ function wait(ms) {
61
+ return new Promise((resolve) => setTimeout(resolve, ms));
62
+ }
63
+ async function error_of(response) {
64
+ const parsed = failure_schema.safeParse(await response.json().catch(() => null));
65
+ const body = parsed.success ? parsed.data : {};
66
+ return new RemoteError(body.error ?? `Request failed with status ${response.status}`, body.code ?? `http_${response.status}`, response.status, body.current, body.reference ?? response.headers.get("x-nemu-reference") ?? undefined);
67
+ }
68
+ function retry_delay(response, attempt) {
69
+ const header = Number(response.headers.get("retry-after") ?? "");
70
+ const seconds = Number.isFinite(header) && header > 0 ? header : 2 ** attempt;
71
+ return Math.min(MAX_WAIT_MS, seconds * 1000);
72
+ }
73
+ function parse(schema, value) {
74
+ const parsed = schema.safeParse(value);
75
+ if (!parsed.success) {
76
+ throw new CliError("Nemu sent an answer this CLI does not understand. Update nemu-cli.", "invalid_response");
77
+ }
78
+ return parsed.data;
79
+ }
80
+ export class VaultApi {
81
+ transport;
82
+ vault_id;
83
+ client_label;
84
+ constructor(transport, vault_id, client_label) {
85
+ this.transport = transport;
86
+ this.vault_id = vault_id;
87
+ this.client_label = client_label;
88
+ }
89
+ async call(method, path, options = {}) {
90
+ for (let attempt = 1;; attempt += 1) {
91
+ const response = await this.transport(method, path, options);
92
+ if (response.status !== 429 || attempt >= ATTEMPTS) {
93
+ if (!response.ok)
94
+ throw await error_of(response);
95
+ return response;
96
+ }
97
+ await response.body?.cancel().catch(() => undefined);
98
+ await wait(retry_delay(response, attempt));
99
+ }
100
+ }
101
+ base() {
102
+ return `/api/v1/vaults/${encodeURIComponent(this.vault_id)}`;
103
+ }
104
+ async info() {
105
+ const response = await this.call("GET", this.base());
106
+ return parse(info_schema, await response.json());
107
+ }
108
+ async notes(trash = false) {
109
+ const response = await this.call("GET", `${this.base()}/notes`, {
110
+ query: trash ? { trash: "true" } : {},
111
+ });
112
+ const body = parse(z.object({ vault: vault_schema, data: z.array(note_schema) }), await response.json());
113
+ return { revision: body.vault.revision, notes: body.data };
114
+ }
115
+ async changes(since) {
116
+ const response = await this.call("GET", `${this.base()}/changes`, {
117
+ query: { since },
118
+ });
119
+ const body = parse(z.object({ data: z.array(note_schema), revision: z.number(), has_more: z.boolean() }), await response.json());
120
+ return { notes: body.data, revision: body.revision, has_more: body.has_more };
121
+ }
122
+ async read(path) {
123
+ const response = await this.call("GET", `${this.base()}/files`, {
124
+ query: { path },
125
+ timeout_ms: 120_000,
126
+ });
127
+ const content = Buffer.from(await response.arrayBuffer());
128
+ const id = response.headers.get("x-nemu-note-id");
129
+ const version = Number(response.headers.get("x-nemu-version"));
130
+ const hash = response.headers.get("x-nemu-hash");
131
+ if (id === null || hash === null || !Number.isInteger(version)) {
132
+ throw new CliError("Nemu sent a file without its version. Update nemu-cli.", "invalid_response");
133
+ }
134
+ return { content, id, version, hash };
135
+ }
136
+ async write(path, content, base_version) {
137
+ const response = await this.call("PUT", `${this.base()}/files`, {
138
+ query: { path },
139
+ headers: {
140
+ "content-type": "application/octet-stream",
141
+ "x-nemu-client": this.client_label,
142
+ ...(base_version === null ? { "if-none-match": "*" } : { "if-match": `"${base_version}"` }),
143
+ },
144
+ body: content,
145
+ timeout_ms: 120_000,
146
+ });
147
+ return parse(z.object({ data: note_schema }), await response.json()).data;
148
+ }
149
+ async remove(path, version) {
150
+ const response = await this.call("DELETE", `${this.base()}/files`, {
151
+ query: { path, version },
152
+ headers: { "x-nemu-client": this.client_label },
153
+ });
154
+ return parse(z.object({ data: note_schema }), await response.json()).data;
155
+ }
156
+ async move(from, to, base_version) {
157
+ const response = await this.call("POST", `${this.base()}/files/move`, {
158
+ headers: { "content-type": "application/json", "x-nemu-client": this.client_label },
159
+ body: JSON.stringify({ from, to, base_version }),
160
+ });
161
+ return parse(z.object({ data: note_schema }), await response.json()).data;
162
+ }
163
+ async record_merge(input) {
164
+ await this.call("POST", `${this.base()}/merges`, {
165
+ headers: { "content-type": "application/json", "x-nemu-client": this.client_label },
166
+ body: JSON.stringify({
167
+ path: input.path,
168
+ merged_version: input.merged_version,
169
+ remote_version: input.remote_version,
170
+ content: Buffer.from(input.local).toString("base64"),
171
+ client: this.client_label,
172
+ }),
173
+ timeout_ms: 120_000,
174
+ });
175
+ }
176
+ async read_version(note_id, version) {
177
+ const response = await this.call("GET", `${this.base()}/history/version`, {
178
+ query: { note_id, version },
179
+ timeout_ms: 120_000,
180
+ });
181
+ return Buffer.from(await response.arrayBuffer());
182
+ }
183
+ async history(note_id, limit = 200) {
184
+ const response = await this.call("GET", `${this.base()}/history`, {
185
+ query: { note_id, limit },
186
+ });
187
+ return parse(z.object({ data: z.array(version_schema) }), await response.json()).data;
188
+ }
189
+ }
190
+ export async function list_vaults(transport) {
191
+ const response = await transport("GET", "/api/v1/vaults", {});
192
+ if (!response.ok)
193
+ throw await error_of(response);
194
+ return parse(z.object({ data: z.array(vault_schema) }), await response.json()).data;
195
+ }
196
+ export async function create_vault(transport, name) {
197
+ const response = await transport("POST", "/api/v1/vaults", {
198
+ headers: { "content-type": "application/json" },
199
+ body: JSON.stringify({ name }),
200
+ });
201
+ if (!response.ok)
202
+ throw await error_of(response);
203
+ return parse(z.object({ data: vault_schema }), await response.json()).data;
204
+ }
@@ -0,0 +1,41 @@
1
+ import { read_credentials } from "../config.js";
2
+ import { device_name } from "../device.js";
3
+ import { CliError } from "../errors.js";
4
+ import { send } from "../http.js";
5
+ import { VERSION } from "../version.js";
6
+ import { VaultApi } from "./api.js";
7
+ import { state_path_for } from "./state.js";
8
+ export function cli_transport(workspace) {
9
+ return async (method, path, options) => {
10
+ const { response } = await send(method, path, {
11
+ ...options,
12
+ workspace: workspace ?? undefined,
13
+ });
14
+ return response;
15
+ };
16
+ }
17
+ export function client_label() {
18
+ return `nemu-sync/${VERSION} ${device_name()}`.replace(/[^\x20-\x7e]/g, "").slice(0, 64);
19
+ }
20
+ export async function signed_in() {
21
+ const credentials = await read_credentials();
22
+ if (credentials === null)
23
+ throw new CliError("Not signed in. Run nemu login.", "not_signed_in");
24
+ return credentials;
25
+ }
26
+ export async function open_linked(marker) {
27
+ const credentials = await signed_in();
28
+ if (credentials.api_url !== marker.server) {
29
+ throw new CliError(`This folder is linked to a vault on ${marker.server}, but you are signed in to ${credentials.api_url}. Nothing was synced.`, "server_mismatch");
30
+ }
31
+ if (credentials.kind === "key" &&
32
+ credentials.workspace !== undefined &&
33
+ marker.workspace_id !== null &&
34
+ credentials.workspace.id !== marker.workspace_id) {
35
+ throw new CliError(`This folder belongs to another workspace than the API key you signed in with (${credentials.workspace.name}). Nothing was synced.`, "workspace_mismatch");
36
+ }
37
+ return {
38
+ api: new VaultApi(cli_transport(marker.workspace_id), marker.vault_id, client_label()),
39
+ state_path: state_path_for(marker.vault_id),
40
+ };
41
+ }