Repository navigation
Expand file tree
/
Copy pathapi.html
More file actions
311 lines (286 loc) · 23.8 KB
/
Copy pathapi.html
File metadata and controls
311 lines (286 loc) · 23.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'self'; img-src 'self'; base-uri 'none'; form-action 'none'">
<meta name="description" content="Use the cmd-sync-servers engine from your own program: sites, sessions, plans, progress, cancellation and errors.">
<title>Library API | cmd-sync-servers</title>
<link rel="stylesheet" href="assets/site.css">
</head>
<body>
<a class="skip" href="#main">Skip to the content</a>
<header class="site-header">
<div class="inner">
<a class="brand" href="index.html">cmd-sync-servers</a>
<nav aria-label="Pages">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="quickstart.html">Quickstart</a></li>
<li><a href="getting-started.html">Getting started</a></li>
<li><a href="examples.html">Examples</a></li>
<li><a href="cheatsheets.html">Cheatsheets</a></li>
<li><a href="configuration.html">Configuration</a></li>
<li><a href="cli.html">Command line</a></li>
<li><a href="options.html">Options</a></li>
<li><a href="synchronization.html">Synchronization</a></li>
<li><a href="api.html" aria-current="page">Library API</a></li>
<li><a href="security.html">Security</a></li>
<li><a href="troubleshooting.html">Troubleshooting</a></li>
</ul>
</nav>
</div>
</header>
<main id="main">
<h1>Library API</h1>
<p class="lead">The engine behind the command line is a library. The VS Code extension uses it in-process, and so can your own program.</p>
<p>The <a href="api/index.html">API reference</a> lists every export with its types. This page shows how the parts fit.</p>
<h2 id="install">Install and import</h2>
<pre><code>npm install @isocialpractice/cmd-sync-servers</code></pre>
<p>The package is ESM only and needs Node.js 22.14 or later. It has one entry point, plus an optional one for the operating system's credential store:</p>
<table>
<caption>What the package exports</caption>
<thead><tr><th scope="col">Import</th><th scope="col">Holds</th></tr></thead>
<tbody>
<tr><td><code>@isocialpractice/cmd-sync-servers</code></td><td>Everything else: the site registry, sessions, plans, credentials, errors and the logger.</td></tr>
<tr><td><code>@isocialpractice/cmd-sync-servers/credentials/keyring</code></td><td>The credential store backed by Windows Credential Manager, the macOS Keychain or the Secret Service keyring.</td></tr>
<tr><td><code>@isocialpractice/cmd-sync-servers/schema/site.schema.json</code></td><td>The JSON Schema of <code>sites.json</code>.</td></tr>
</tbody>
</table>
<div class="note">
<p><strong>Stability.</strong> The API follows semantic versioning: a breaking change to it, or to <code>sites.json</code>, comes only in a new major version. Names marked <em>experimental</em> in the reference, such as the transports, the connection pool and the classification helpers, are outside that promise and may change in a minor version. <code>SiteRegistry</code>, <code>SyncSession</code> and <code>SyncPlan</code> are the parts to build on.</p>
</div>
<h2 id="first-run">A first synchronization</h2>
<p>This program puts newer local files of <em>My Site</em> to its Remote server and prints what happened. Save it as <code>put.mjs</code> and run it with <code>node put.mjs</code>.</p>
<pre><code>import { MemoryCredentialStore, SiteRegistry, SyncSession, isSyncError } from '@isocialpractice/cmd-sync-servers';
const registry = await SiteRegistry.open();
const site = registry.resolve({ name: 'My Site' }) ?? registry.resolve({ path: process.cwd() });
if (site === undefined) {
throw new Error('Add the site first: sync-servers site add');
}
// What the engine needs from the program around it.
const host = {
credentials: new MemoryCredentialStore(),
interactive: false, // never ask: unknown host keys are refused
confirmHostKey: async () => 'reject',
promptSecret: async () => undefined, // the password comes from SYNC_SERVERS_PASSWORD
};
const controller = new AbortController();
process.once('SIGINT', () => controller.abort());
const session = await SyncSession.open({ registry, siteId: site.id, host });
try {
const plan = await session.plan({ direction: 'put', signal: controller.signal });
console.log(plan.summaryLine());
const result = await session.execute(plan, {
signal: controller.signal,
onProgress: (event) => {
if (event.type === 'transfer') {
console.log(`${event.completed}/${event.total} ${event.outcome} ${event.path}`);
}
},
});
console.log(`${result.done} done, ${result.failed} failed, ${result.unresolved} waiting for a decision`);
} catch (error) {
if (isSyncError(error, 'E_HOST_KEY_MISMATCH')) {
console.error('The server is not the one that was trusted. Check its host key.');
}
throw error;
} finally {
await session.close();
}</code></pre>
<p>Run it after trusting the server's host key once with <code>sync-servers server test</code>, which pins it in <code>sites.json</code>.</p>
<h2 id="registry">Sites and servers</h2>
<p><code>SiteRegistry</code> reads and writes <code>sites.json</code>, the same list the command line and the extension use. Every write takes the lock file, re-reads the file, validates the result and replaces the file atomically, so concurrent programs never lose each other's changes.</p>
<pre><code>const registry = await SiteRegistry.open(); // or open({ configDir, stateDir })
const site = await registry.add({ name: 'My Site', localRoot: '/home/<user>/sites/my-site' });
const server = await registry.addServer(site.id, {
name: 'Production',
protocol: 'sftp',
host: 'sftp.example.com',
username: 'demo-user',
remoteRoot: '/var/www/my-site',
});
await registry.update(site.id, (draft) => {
draft.cloaking.patterns.push('.psd');
});
console.log(registry.list().map((item) => item.name));</code></pre>
<p>A site's first server becomes its Remote server. <code>resolve()</code> finds a site by id, by name ignoring case, or by a path inside its local folder.</p>
<p>The global cloaking patterns, which every site uses before its own unless its <code>cloaking.useGlobalPatterns</code> is <code>false</code>, are a <code>GlobalCloaking</code>: <code>registry.globalCloaking</code> reads them and <code>updateGlobalCloaking()</code> changes them through the same safe write. <code>siteCloak()</code> takes them as its third argument and answers whether a site-relative path is cloaked; a session passes them for you.</p>
<pre><code>import { siteCloak } from '@isocialpractice/cmd-sync-servers';
await registry.updateGlobalCloaking((cloaking) => {
cloaking.patterns.push('.git/', 'node_modules/');
});
const cloak = siteCloak(site, process.platform, registry.globalCloaking.patterns);
console.log(cloak.isCloaked('node_modules', true)); // true, unless the site re-includes it</code></pre>
<h2 id="host">The host adapter</h2>
<p>A <code>HostAdapter</code> is what the engine asks of the program it runs in:</p>
<table>
<caption>Members of HostAdapter</caption>
<thead><tr><th scope="col">Member</th><th scope="col">Answers</th></tr></thead>
<tbody>
<tr><td><code>credentials</code></td><td>Where saved passwords and key passphrases are read and kept.</td></tr>
<tr><td><code>confirmHostKey(info)</code></td><td>Whether to trust an SSH host key seen for the first time: <code>'accept-and-pin'</code>, <code>'accept-once'</code> or <code>'reject'</code>.</td></tr>
<tr><td><code>confirmCertificate(info)</code></td><td>Optional. What to do about an FTPS certificate that did not verify, given a <code>CertificateInfo</code>: a <code>CertificateDecision</code>, described below. Without it, such a certificate is refused.</td></tr>
<tr><td><code>promptSecret(request)</code></td><td>A password typed by a person, or <code>undefined</code>. <code>request.note</code>, when set, says why it is asked, such as a saved password that was not sent because the server changed.</td></tr>
<tr><td><code>secretAccepted(request, secret)</code></td><td>Optional. Called once after the server accepts a secret a person typed, so the program may offer to save it. Never called for a secret from the store or the environment.</td></tr>
<tr><td><code>interactive</code></td><td><code>false</code> when nobody can answer, so new host keys and unverified certificates are refused without asking.</td></tr>
<tr><td><code>logger</code></td><td>Where the engine logs, with every secret already removed.</td></tr>
</tbody>
</table>
<p>A <code>CertificateInfo</code> carries the host and port, the names the certificate lists, its issuer and validity dates, its SHA-256 fingerprint, the <code>problem</code> (<code>name-mismatch</code>, <code>untrusted-issuer</code>, <code>self-signed</code>, <code>expired</code>, <code>not-yet-valid</code>, <code>changed</code> or <code>other</code>), and <code>coveredNames</code>: host names that lead to the same machine and that the certificate covers. Every string from the certificate is already escaped. The decision is one of:</p>
<table>
<caption>Certificate decisions</caption>
<thead><tr><th scope="col">Decision</th><th scope="col">Does</th></tr></thead>
<tbody>
<tr><td><code>{ action: 'use-host', host }</code></td><td>Connects to a name from <code>coveredNames</code> instead, with full verification, and saves it as the server's host.</td></tr>
<tr><td><code>{ action: 'check-as', servername }</code></td><td>Keeps the host and checks the certificate as a name from <code>coveredNames</code>, saved as <code>options.tls.servername</code>.</td></tr>
<tr><td><code>{ action: 'accept-and-pin' }</code></td><td>Trusts this certificate and pins its fingerprint in <code>options.tls.trustedCertificate</code>.</td></tr>
<tr><td><code>{ action: 'accept-once' }</code></td><td>Trusts it for this session only.</td></tr>
<tr><td><code>{ action: 'reject' }</code></td><td>Refuses it with <code>E_TLS_CERT</code>.</td></tr>
</tbody>
</table>
<p>Expired and not-yet-valid certificates are refused before the adapter is asked. Every decision is made before the user name or password is sent.</p>
<p>To use the operating system's credential store, as the command line does:</p>
<pre><code>import { openKeyringStore } from '@isocialpractice/cmd-sync-servers/credentials/keyring';
import { MemoryCredentialStore } from '@isocialpractice/cmd-sync-servers';
const credentials = (await openKeyringStore()) ?? new MemoryCredentialStore();</code></pre>
<p><code>openKeyringStore()</code> resolves <code>undefined</code> when the optional <code>@napi-rs/keyring</code> package has no build for the platform.</p>
<h2 id="plans">Plans</h2>
<p><code>session.plan()</code> scans both sides and returns a <code>SyncPlan</code>; it transfers nothing. The plan holds one row per file with a difference, as the preview shows them, and can be changed before it runs:</p>
<pre><code>const plan = await session.plan({ direction: 'both', deleteOrphans: false, scope: { kind: 'paths', paths: ['css'] } });
plan.summary; // { update: 3, delete: 0, skip: 41, resolve: 1, guarded: 0, errors: 0 }
for (const item of plan.items) {
console.log(item.id, item.action, item.checked, item.path, item.status);
}
plan.allowedActions('css/site.css'); // ['put', 'get', 'skip', 'synced', ...]
plan.setAction('css/site.css', 'get'); // a Resolve row needs an action before it can run
plan.setChecked('css/print.css', false);
const saved = JSON.stringify(plan.toJSON()); // run it later with SyncPlan.fromJSON and applySaved</code></pre>
<p><a href="synchronization.html#actions">Synchronization</a> explains which action each change gets.</p>
<h2 id="range">The files of a time range</h2>
<p>A plan with <code>changedSince</code> compares only the local files created or last modified at or after that moment, and looks only them up on the server. It is a Put without the delete option: another direction, or <code>deleteOrphans</code>, rejects with <code>E_PLAN_INVALID</code>. The plan is the plan of those files as single paths, so <code>plan.scope.paths</code> lists them, an empty list means no file was recent and nothing connected, and <code>plan.unlisted</code> counts the recent files already in sync. It never holds a delete, a Get, or a file only the server has.</p>
<pre><code>import { noRecentFiles, parseRange, rangeStart, rangeTitle } from '@isocialpractice/cmd-sync-servers';
const range = parseRange('2d'); // { value: 2, unit: 'd' }, or undefined for text that is not a range
if (range === undefined) {
throw new Error('A range is a number and a unit, such as 90m, 24h, 2d or 1w.');
}
const plan = await session.plan({ direction: 'put', changedSince: rangeStart(range) });
if (plan.scope.kind === 'paths' && plan.scope.paths.length === 0) {
console.log(noRecentFiles(range, session.site.name)); // No file of "My Site" was created or modified in the last 2 days.
} else {
console.log(rangeTitle(range)); // Put files from the last 2 days
console.log(plan.summaryLine());
}</code></pre>
<p>A range is a number and one unit in lower case: <code>m</code> for minutes, <code>h</code> for hours, <code>d</code> for days or <code>w</code> for weeks, as in <code>90m</code>, <code>24h</code>, <code>2d</code> and <code>1w</code>. It counts back from this computer's clock, and a file is judged by the dates its file system keeps for it. <code>changedSince</code> takes any <code>Date</code>, so a program can also count from a moment of its own. A scope narrows the files looked through, as in any plan, and a plan saved with <code>toJSON()</code> runs again like any saved plan of paths. These exports are experimental.</p>
<table>
<caption>Exports for a time range</caption>
<thead><tr><th scope="col">Export</th><th scope="col">Does</th></tr></thead>
<tbody>
<tr><td><code>parseRange(text)</code>, <code>formatRange(range)</code></td><td>Read a range from text, with <code>undefined</code> for anything that is not one, and write a <code>TimeRange</code> back as it is typed.</td></tr>
<tr><td><code>rangeStart(range)</code></td><td>The moment a range starts: that long before this computer's clock.</td></tr>
<tr><td><code>fileChangedSince(file, since)</code></td><td>Whether a local file was created or last modified at or after a moment. <code>false</code> for a file that cannot be read.</td></tr>
<tr><td><code>TimeRange</code>, <code>RangeUnit</code></td><td>A range as <code>{ value, unit }</code>, and its four units.</td></tr>
<tr><td><code>DEFAULT_RANGE</code></td><td><code>1d</code>, the range a question offers when nothing is typed.</td></tr>
<tr><td><code>RANGE_TITLE</code></td><td><code>Put files from a time range</code>, the name of the choice in every front end.</td></tr>
<tr><td><code>RANGE_TEXT</code>, <code>rangeWords(range)</code>, <code>rangeTitle(range)</code>, <code>noRecentFiles(range, siteName)</code></td><td>The sentences every front end shows: how a range is written, the question that asks for one, a range in words, the title of its preview, and what to say when no file is recent.</td></tr>
</tbody>
</table>
<h2 id="session">Other session calls</h2>
<table>
<caption>SyncSession methods</caption>
<thead><tr><th scope="col">Method</th><th scope="col">Does</th></tr></thead>
<tbody>
<tr><td><code>testConnection(signal)</code></td><td>Connects, signs in, checks the root directory and reports what the server offers, including <code>startingFolder</code>, the folder the account opens in.</td></tr>
<tr><td><code>status(options)</code></td><td>What changed on each side since the last sync, without a plan.</td></tr>
<tr><td><code>put(paths)</code>, <code>get(paths)</code></td><td>Moves single files or folders at once; returns a plan instead when a decision is needed.</td></tr>
<tr><td><code>compare(path, signal)</code></td><td>Both copies of a file for a diff; the server copy is a private temporary file removed by <code>dispose()</code>.</td></tr>
<tr><td><code>markSynchronized(paths, signal)</code></td><td>Records files as in sync without moving them.</td></tr>
<tr><td><code>settle(plan)</code></td><td>Saves what a plan found without a transfer: files both sides hold as the same copy are recorded, and records of files gone on both sides are dropped. <code>execute</code> does this itself; call it for a plan with nothing to run.</td></tr>
<tr><td><code>resetState(options)</code></td><td>Forgets the sync records of the site and server. With <code>{ dreamweaver: true }</code> it also removes the server's entries from every <code>_notes/dwsync.xml</code> of the site.</td></tr>
<tr><td><code>close()</code></td><td>Saves the records and closes every connection.</td></tr>
</tbody>
</table>
<h2 id="dreamweaver">Dreamweaver's records</h2>
<p>A site with <code>sync.dreamweaver.enabled</code> on reads and updates the synchronization records Dreamweaver keeps in each folder as <code>_notes/dwsync.xml</code>. The session does that by itself: <code>plan.adopted</code> counts the files a plan took as in sync on the word of those records, and <code>status()</code> reports the same count with whether the way Dreamweaver reads the server's clock is known yet. These exports are for a program that sets a site up or looks at the files itself; all are experimental.</p>
<table>
<caption>Exports for Dreamweaver's records</caption>
<thead><tr><th scope="col">Export</th><th scope="col">Does</th></tr></thead>
<tbody>
<tr><td><code>hasDreamweaverRecords(localRoot, options)</code></td><td>True when a local folder, or a folder below it, holds a readable <code>_notes/dwsync.xml</code>.</td></tr>
<tr><td><code>findDreamweaverServers(localRoot, options)</code></td><td>The servers Dreamweaver synchronized the folder with, as it names them, each with the number of entries that carry the name.</td></tr>
<tr><td><code>dreamweaverServerName(server)</code></td><td>The name Dreamweaver gives a server: the one its <code>options.dreamweaverServer</code> sets, or the host, <code>/</code>, and the remote root ending in <code>/</code>.</td></tr>
<tr><td><code>parseDwsync(text)</code>, <code>serializeDwsync(document)</code></td><td>Read and write the text of a <code>dwsync.xml</code>. A text that is not understood in full parses to <code>undefined</code>.</td></tr>
<tr><td><code>isDwsyncPath(path, caseInsensitive)</code></td><td>True for <code>_notes/dwsync.xml</code> in any folder of a site: the file no synchronization lists.</td></tr>
<tr><td><code>withEntry(state, hasRecord, match)</code></td><td>The state of a file both sides have, given which sides are as an entry of another program's records says.</td></tr>
<tr><td><code>RecordMirror</code></td><td>The interface of a second copy of the sync records, which <code>SyncRecords.load</code> takes as its last argument.</td></tr>
<tr><td><code>session.dreamweaverClock</code></td><td><code>'known'</code> or <code>'unknown'</code> after a plan, and <code>undefined</code> for a site that does not use the records. Until the clock is known, the records are not used.</td></tr>
<tr><td><code>DREAMWEAVER_TEXT</code>, <code>dreamweaverInSync(count)</code>, <code>dreamweaverTakeOver(adopted, clock)</code></td><td>The sentences every front end shows: the question setup asks, why the records are not used yet, and what a plan took from them.</td></tr>
</tbody>
</table>
<h2 id="setup">Setting up a server</h2>
<p>Two exports help a program set a server up before it is saved. <code>parseServerAddress</code> reads what a person typed in a Host field: a host name or IP address, <code>host:port</code>, <code>[IPv6]:port</code>, <code>user@host</code>, or an <code>sftp://</code>, <code>ftpes://</code>, <code>ftps://</code> or <code>ftp://</code> address.</p>
<pre><code>import { parseServerAddress } from '@isocialpractice/cmd-sync-servers';
const result = parseServerAddress('demo-user@example.com@server1.hosting.example.net:21');
if (result.ok) {
// { host: 'server1.hosting.example.net', port: 21, username: 'demo-user@example.com' }
console.log(result.address, result.address.warning ?? '');
} else {
console.error(result.problem); // such as: That is a web address. Enter the FTP or SFTP host ...
}</code></pre>
<p><code>ServerProbe</code> <em>(experimental)</em> connects with settings that are not saved yet, goes through the host key and certificate decisions, and lists folders by absolute path, so the remote root can be picked from what the server shows. Give a new server its final id up front, so a password typed now can be saved under it once the server accepts it.</p>
<pre><code>import { randomUUID } from 'node:crypto';
import { ServerProbe, serverSchema } from '@isocialpractice/cmd-sync-servers';
const server = serverSchema.parse({
id: randomUUID(),
name: 'Production',
protocol: 'ftps',
host: 'server1.hosting.example.net',
username: 'demo-user@example.com',
remoteRoot: '/',
});
const probe = await ServerProbe.open({ site: { id: site.id, name: site.name }, server, host });
try {
const start = probe.startingFolder ?? '/'; // where the account opens, such as "/"
const listing = await probe.folders(start); // { path: '/', folders: ['css', 'images', 'js'], files: 3 }
console.log(listing.folders, await probe.exists('/images'));
const settings = probe.server; // the settings, with any decision applied
} finally {
await probe.close();
}</code></pre>
<h2 id="progress">Progress and cancelling</h2>
<p>Every call that can take long takes an <code>AbortSignal</code>. Aborting a run starts no new transfer, removes partial files and records what finished; the result says <code>cancelled: true</code>. Aborting a scan rejects with <code>E_CANCELLED</code>.</p>
<p>Progress events carry counts and bytes, never file contents:</p>
<table>
<caption>Progress events</caption>
<thead><tr><th scope="col">Type</th><th scope="col">Carries</th></tr></thead>
<tbody>
<tr><td><code>scan-local</code></td><td><code>files</code> found so far</td></tr>
<tr><td><code>scan-remote</code></td><td><code>files</code> and <code>folders</code> found so far</td></tr>
<tr><td><code>compare</code></td><td><code>files</code> compared</td></tr>
<tr><td><code>transfer</code></td><td><code>path</code>, <code>action</code>, <code>outcome</code>, <code>completed</code>, <code>total</code> and <code>bytes</code></td></tr>
<tr><td><code>done</code></td><td><code>completed</code> and <code>failed</code></td></tr>
</tbody>
</table>
<h2 id="errors">Errors</h2>
<p>Failures are <code>SyncError</code> instances. Their <code>code</code> is stable across versions and their message never contains a secret. <code>transient</code> says whether trying again on a fresh connection may help. <code>details</code> holds facts to act on: for <code>E_AUTH</code>, <code>reason</code> is <code>rejected</code>, <code>missing</code> or <code>saved-for-elsewhere</code>; for <code>E_TLS_CERT</code>, <code>certificate</code> is the <code>CertificateInfo</code>; for <code>E_REMOTE_ROOT</code>, <code>startingFolder</code> and <code>folders</code> name where the account opens and what it holds.</p>
<pre><code>import { isSyncError } from '@isocialpractice/cmd-sync-servers';
try {
await session.testConnection();
} catch (error) {
if (isSyncError(error, 'E_AUTH') && error.details?.reason === 'rejected') {
// the server refused it: ask for the user name and password again
} else if (isSyncError(error) && error.transient) {
// try again later
} else {
throw error;
}
}</code></pre>
<p>Every code, with what to do about it, is listed in <a href="troubleshooting.html#error-codes">Troubleshooting</a>.</p>
</main>
<footer class="site-footer">
<div class="inner">
<p>cmd-sync-servers is open source under the MIT license. Source, issues and releases are on <a href="https://github.com/isocialPractice/cmd-sync-servers">GitHub</a>.</p>
</div>
</footer>
</body>
</html>