@feralfile/cli 2.2.3 → 2.4.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 CHANGED
@@ -12,15 +12,7 @@ ff-cli is a set of deterministic commands for building DP-1–conformant playlis
12
12
  npm i -g @feralfile/cli
13
13
  ```
14
14
 
15
- This is the recommended path and the most reliable for the agent workflow — it installs a complete package (including `config.json.example` and the bundled `dp1-js`). Requires Node.js 22+.
16
-
17
- ## Install (curl)
18
-
19
- ```bash
20
- curl -fsSL https://feralfile.com/ff-cli-install | bash
21
- ```
22
-
23
- Installs a prebuilt binary for macOS/Linux. Node.js 22+ must still be on your PATH (the bundle runs under `node`). If a command fails right after install, prefer the npm install above.
15
+ This installs a complete package (including `config.json.example` and the bundled `dp1-js`). Requires Node.js 22+.
24
16
 
25
17
  ## One-off Usage (npx)
26
18
 
@@ -138,8 +130,7 @@ Run the same command locally before opening a PR. It checks formatting, lint, te
138
130
 
139
131
  Other GitHub Actions workflows:
140
132
 
141
- - `.github/workflows/build.yml` builds release assets when called by release automation or manually dispatched.
142
- - `.github/workflows/release.yml` reuses CI, verifies the release version, publishes npm, uploads assets, and checks the published release.
133
+ - `.github/workflows/release.yml` reuses CI, verifies the release version, publishes to npm, and checks the published package.
143
134
  - `.github/workflows/dependency-review.yml` reviews dependency changes on pull requests.
144
135
  - `.github/workflows/codeql.yml` runs CodeQL analysis on pull requests and pushes to `main`/`master`.
145
136
 
package/dist/index.js CHANGED
@@ -28,6 +28,7 @@ const play_1 = require("./src/commands/play");
28
28
  const publish_1 = require("./src/commands/publish");
29
29
  const find_1 = require("./src/commands/find");
30
30
  const build_1 = require("./src/commands/build");
31
+ const enrich_1 = require("./src/commands/enrich");
31
32
  const config_1 = require("./src/commands/config");
32
33
  const ssh_1 = require("./src/commands/ssh");
33
34
  const device_1 = require("./src/commands/device");
@@ -55,6 +56,7 @@ program.addCommand(sign_1.signCommand);
55
56
  program.addCommand(play_1.playCommand);
56
57
  program.addCommand(publish_1.publishCommand);
57
58
  program.addCommand(find_1.findCommand);
59
+ program.addCommand(enrich_1.enrichCommand);
58
60
  program.addCommand(build_1.buildCommand);
59
61
  program.addCommand(config_1.configCommand);
60
62
  program.addCommand(ssh_1.sshCommand);
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@feralfile/cli",
3
- "version": "2.2.3",
3
+ "version": "2.4.0",
4
4
  "description": "CLI for building, signing, and playing DP-1 playlists of digital art on Feral File devices",
5
5
  "repository": {
6
6
  "type": "git",
@@ -58,14 +58,14 @@
58
58
  "author": "",
59
59
  "license": "MIT",
60
60
  "dependencies": {
61
- "@napi-rs/keyring": "1.3.0",
62
61
  "@feralfile/source-resolver": "^1.0.0",
62
+ "@napi-rs/keyring": "1.3.0",
63
63
  "axios": "^1.6.2",
64
64
  "bonjour-service": "^1.3.0",
65
65
  "chalk": "^4.1.2",
66
66
  "commander": "^11.1.0",
67
67
  "dotenv": "^16.3.1",
68
- "dp1-js": "2.0.0",
68
+ "dp1-js": "2.3.1",
69
69
  "ff1": "^1.0.0",
70
70
  "fuzzysort": "^3.1.0",
71
71
  "viem": "^2.38.2"
@@ -0,0 +1,315 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.enrichCommand = void 0;
7
+ const commander_1 = require("commander");
8
+ const chalk_1 = __importDefault(require("chalk"));
9
+ const fs_1 = require("fs");
10
+ const crypto_1 = require("crypto");
11
+ const path_1 = require("path");
12
+ const enrich_playlist_1 = require("../utilities/enrich-playlist");
13
+ const playlist_verifier_1 = require("../utilities/playlist-verifier");
14
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
15
+ const { getNFTTokenInfoBatch } = require('../utilities/nft-indexer');
16
+ /**
17
+ * writePlaylistAtomically replaces a file only once the new bytes are safely on
18
+ * disk.
19
+ *
20
+ * The default destination is the input file, and a plain write truncates it
21
+ * first. Enrichment runs after a lookup that can take minutes while the indexer
22
+ * warms tokens, so the window between truncation and a complete write is a
23
+ * window in which an interruption, a full disk, or an I/O error leaves the
24
+ * curator with an empty or half-written playlist and no copy of what they had.
25
+ * A rename within the same directory is atomic, so the original file survives
26
+ * intact until the replacement is complete.
27
+ *
28
+ * The temporary file is created alongside the destination rather than in the
29
+ * system temp directory: rename is only atomic within a filesystem, and those
30
+ * are not guaranteed to be the same one.
31
+ */
32
+ async function writePlaylistAtomically(destination, contents, expectedDigest) {
33
+ // Follow a symlink to its target before replacing anything. rename() would
34
+ // replace the link itself, silently detaching a playlist that other paths
35
+ // reach through that name while reporting success.
36
+ let target = destination;
37
+ const existing = await fs_1.promises.lstat(destination).catch(() => null);
38
+ if (existing?.isSymbolicLink()) {
39
+ target = await fs_1.promises.realpath(destination);
40
+ }
41
+ const temporary = (0, path_1.join)((0, path_1.dirname)(target), `.${(0, path_1.basename)(target)}.${process.pid}.${(0, crypto_1.randomBytes)(4).toString('hex')}.tmp`);
42
+ // The destination's mode has to be known before the file exists, not after
43
+ // it holds the contents. Creating at the default 0o666-minus-umask and
44
+ // chmod'ing afterwards leaves the enriched playlist readable by other local
45
+ // users for the length of the write — short, but a disclosure window on a
46
+ // file the curator deliberately restricted.
47
+ const current = await fs_1.promises.stat(target).catch(() => null);
48
+ const mode = current ? current.mode & 0o7777 : undefined;
49
+ try {
50
+ // 'wx' fails rather than truncating if the name somehow exists, so a
51
+ // collision can never destroy another process's work in progress.
52
+ const handle = await fs_1.promises.open(temporary, 'wx', mode);
53
+ try {
54
+ // open() applies the mode through umask, which can strip bits the
55
+ // destination had. chmod is not subject to umask, so this restores the
56
+ // exact mode — still before any bytes are written.
57
+ if (mode !== undefined) {
58
+ await handle.chmod(mode);
59
+ }
60
+ // A replacement is a new inode, so it carries this process's ownership
61
+ // rather than the destination's. Silently reassigning a playlist that
62
+ // belongs to another user or a shared group can lock collaborators out
63
+ // of it, or widen who can reach it. Carry the ownership across, and when
64
+ // that is not permitted refuse the in-place replacement instead of
65
+ // completing it with different access than the file had.
66
+ if (current && (current.uid !== process.getuid?.() || current.gid !== process.getgid?.())) {
67
+ try {
68
+ await handle.chown(current.uid, current.gid);
69
+ }
70
+ catch {
71
+ await fs_1.promises.rm(temporary, { force: true }).catch(() => undefined);
72
+ throw new OwnershipError(target);
73
+ }
74
+ }
75
+ await handle.writeFile(contents);
76
+ // rename() is atomic against concurrent readers but says nothing about
77
+ // power loss: the directory entry can reach disk before the data it
78
+ // points at. Without this a crash mid-write can leave the playlist
79
+ // present and empty, which is the outcome the temporary file exists to
80
+ // prevent. Sync the contents first, then the directory entry after.
81
+ await handle.sync();
82
+ }
83
+ finally {
84
+ await handle.close();
85
+ }
86
+ // Checked here, as late as the sequence allows: everything expensive is
87
+ // already done, so the interval between this read and the rename below is
88
+ // a few syscalls rather than the minutes a lookup takes.
89
+ //
90
+ // It narrows the race; it cannot close it. Comparing and then replacing is
91
+ // not atomic against an editor that does not participate in any protocol,
92
+ // and nothing available in userspace makes it so — every tool that edits a
93
+ // file in place carries this. Passing no digest (a distinct --output) opts
94
+ // out entirely, which is the safe path when a file is being actively
95
+ // edited.
96
+ if (expectedDigest !== undefined) {
97
+ const current = await fs_1.promises.readFile(target).catch(() => null);
98
+ const digest = current && (0, crypto_1.createHash)('sha256').update(current).digest('hex');
99
+ if (digest !== expectedDigest) {
100
+ await fs_1.promises.rm(temporary, { force: true }).catch(() => undefined);
101
+ return false;
102
+ }
103
+ }
104
+ await fs_1.promises.rename(temporary, target);
105
+ await syncDirectory((0, path_1.dirname)(target));
106
+ return true;
107
+ }
108
+ catch (error) {
109
+ await fs_1.promises.rm(temporary, { force: true }).catch(() => undefined);
110
+ throw error;
111
+ }
112
+ }
113
+ /**
114
+ * OwnershipError marks a refusal to replace a file whose ownership this
115
+ * process cannot reproduce, so the caller can explain it rather than print a
116
+ * bare errno.
117
+ */
118
+ class OwnershipError extends Error {
119
+ target;
120
+ constructor(target) {
121
+ super(`cannot preserve ownership of ${target}`);
122
+ this.target = target;
123
+ this.name = 'OwnershipError';
124
+ }
125
+ }
126
+ /**
127
+ * isSameFile reports whether two paths name the same file on disk.
128
+ *
129
+ * Compares resolved paths rather than the strings the caller typed, so
130
+ * `-o ./playlist.json` against `playlist.json`, and a symlink against its
131
+ * target, are recognized as the in-place case they are.
132
+ */
133
+ async function isSameFile(a, b) {
134
+ if (a === b) {
135
+ return true;
136
+ }
137
+ const [left, right] = await Promise.all([
138
+ fs_1.promises.realpath(a).catch(() => null),
139
+ fs_1.promises.realpath(b).catch(() => null),
140
+ ]);
141
+ return left !== null && left === right;
142
+ }
143
+ /**
144
+ * syncDirectory flushes a directory entry so a rename survives power loss.
145
+ *
146
+ * Best-effort by design. Directory fsync is not portable — Windows rejects it
147
+ * outright — and a durability barrier that cannot be raised is not a reason to
148
+ * fail a write that has already succeeded. The data itself was synced before
149
+ * the rename, so the worst case here is the old name surviving a crash, not a
150
+ * corrupt file.
151
+ */
152
+ async function syncDirectory(directory) {
153
+ try {
154
+ const handle = await fs_1.promises.open(directory, 'r');
155
+ try {
156
+ await handle.sync();
157
+ }
158
+ finally {
159
+ await handle.close();
160
+ }
161
+ }
162
+ catch {
163
+ /* not supported on this platform or filesystem */
164
+ }
165
+ }
166
+ /**
167
+ * reportInvalid prints structural validation diagnostics and exits non-zero.
168
+ *
169
+ * Enrichment refuses to work on a document DP-1 rejects, and refuses to write
170
+ * one. Writing an invalid playlist would replace the operator's file with
171
+ * something sign, publish, and play all reject later, having reported success.
172
+ */
173
+ function reportInvalid(stage, result) {
174
+ console.error(chalk_1.default.red(`\n${stage}`));
175
+ if (result.error) {
176
+ console.error(chalk_1.default.dim(` ${result.error}`));
177
+ }
178
+ for (const detail of result.details ?? []) {
179
+ console.error(chalk_1.default.dim(` ${detail.path}: ${detail.message}`));
180
+ }
181
+ console.error(chalk_1.default.dim('\n The file was left unchanged.\n'));
182
+ process.exit(1);
183
+ }
184
+ /**
185
+ * SKIP_COPY explains each skip in the operator's terms rather than the code's.
186
+ * `no-provenance` is the one a person can act on, so it says what to add.
187
+ */
188
+ const SKIP_COPY = {
189
+ 'already-labelled': 'already has a manifest (use --force to replace)',
190
+ 'external-ref': 'carries an external ref, which outranks an inline manifest',
191
+ 'no-provenance': 'no provenance.contract chain/address/tokenId to look up',
192
+ 'ambiguous-chain': 'chain "evm" names a family; pass --assume-ethereum to assert the network',
193
+ // The indexer drops unresolved tokens from its response rather than
194
+ // reporting why, so there is no per-item reason to relay here.
195
+ 'not-indexed': 'the indexer returned nothing for it',
196
+ 'no-metadata': 'the indexer resolved it but has no artist, description, or still image',
197
+ };
198
+ exports.enrichCommand = new commander_1.Command('enrich')
199
+ .description('Add missing artist, title, and thumbnail metadata to a playlist')
200
+ .argument('<file>', 'Path to the DP-1 playlist file')
201
+ .option('-o, --output <filename>', 'Write here instead of overwriting the input')
202
+ .option('--force', 'Replace manifests that already exist', false)
203
+ .option('--assume-ethereum', 'Treat DP-1 "evm" coordinates as Ethereum. Without this they are skipped, ' +
204
+ 'because "evm" names a family and the wrong member yields another artwork.', false)
205
+ .option('-v, --verbose', 'Show detailed output', false)
206
+ .action(async (file, options) => {
207
+ try {
208
+ console.log(chalk_1.default.blue('\nEnrich playlist\n'));
209
+ // Hash the exact bytes parsed, not a stat taken afterwards: an edit
210
+ // between the read and the stat would leave the snapshot describing
211
+ // newer content while enrichment still worked from the older bytes.
212
+ const original = await fs_1.promises.readFile(file);
213
+ const originalDigest = (0, crypto_1.createHash)('sha256').update(original).digest('hex');
214
+ const playlist = JSON.parse(original.toString('utf-8'));
215
+ const total = Array.isArray(playlist.items) ? playlist.items.length : 0;
216
+ if (total === 0) {
217
+ console.error(chalk_1.default.red('That playlist has no items.'));
218
+ process.exit(1);
219
+ }
220
+ // Validate before spending minutes on indexer lookups for a document
221
+ // that was never going to be writable.
222
+ const before = await (0, playlist_verifier_1.validatePlaylist)(playlist);
223
+ if (!before.valid) {
224
+ reportInvalid('That playlist is not valid DP-1:', before);
225
+ }
226
+ // Warming previously-unseen tokens can take minutes, so a human watching
227
+ // this needs to see it move. Matches the progress line `find` prints.
228
+ let printedProgress = false;
229
+ const onProgress = (done, count) => {
230
+ printedProgress = true;
231
+ process.stdout.write(chalk_1.default.dim(`\r ${done}/${count} looked up...`));
232
+ };
233
+ // getNFTTokenInfoBatch is (tokens, duration, onProgress) — the second
234
+ // positional is DP-1 display seconds, not the callback. Enrichment never
235
+ // sets duration (the curator's timing is not ours to touch), so it is
236
+ // passed undefined and the callback goes third. find.ts carries the same
237
+ // warning; getting this wrong silently returns unusable results.
238
+ const lookup = (tokens, onProgressCallback) => getNFTTokenInfoBatch(tokens, undefined, onProgressCallback);
239
+ const result = await (0, enrich_playlist_1.enrichPlaylistManifests)(playlist, lookup, {
240
+ force: options.force,
241
+ assumeEthereum: options.assumeEthereum,
242
+ onProgress,
243
+ });
244
+ if (printedProgress) {
245
+ process.stdout.write('\n');
246
+ }
247
+ // Said before anything is written, so an operator who did not mean to
248
+ // assert the network still has the file they started with.
249
+ if (result.assumedEthereum > 0) {
250
+ console.log(chalk_1.default.yellow(`\n ${result.assumedEthereum} coordinate(s) gave chain "evm" and were looked up on` +
251
+ `\n Ethereum because --assume-ethereum was passed. An L2 work sharing an` +
252
+ `\n address and token id with an Ethereum one would take the wrong metadata.`));
253
+ }
254
+ const destination = options.output ?? file;
255
+ // --output names a file the caller expects to find afterwards, so it is
256
+ // written even when nothing was enriched. Overwriting the input on a
257
+ // no-op would be pure risk for no gain, so that case still writes
258
+ // nothing.
259
+ const shouldWrite = result.enriched > 0 || options.output !== undefined;
260
+ if (shouldWrite) {
261
+ // Re-validate the enriched candidate. An inline manifest is schema-
262
+ // checked the same way a fetched one is (playlists extension §3.6), so
263
+ // a malformed manifest from the indexer must not reach the file.
264
+ const after = await (0, playlist_verifier_1.validatePlaylist)(result.playlist);
265
+ if (!after.valid) {
266
+ reportInvalid('Enrichment produced an invalid playlist:', after);
267
+ }
268
+ const replaced = await writePlaylistAtomically(destination, JSON.stringify(result.playlist, null, 2), (await isSameFile(file, destination)) ? originalDigest : undefined);
269
+ if (!replaced) {
270
+ console.error(chalk_1.default.red('\nThat playlist changed while the lookup ran.'));
271
+ console.error(chalk_1.default.dim(' Enrichment was computed from the earlier version, so writing it\n' +
272
+ ' would discard whatever changed. Nothing was written. Re-run to\n' +
273
+ ' enrich the current file, or pass -o to write somewhere else.\n'));
274
+ process.exit(1);
275
+ }
276
+ }
277
+ console.log(result.enriched > 0
278
+ ? chalk_1.default.green(`\n${result.enriched} of ${total} item(s) enriched`)
279
+ : chalk_1.default.yellow('\nNothing to enrich'));
280
+ if (shouldWrite) {
281
+ console.log(chalk_1.default.dim(` Output: ${destination}`));
282
+ }
283
+ if (result.skipped.length > 0) {
284
+ const shown = options.verbose ? result.skipped : result.skipped.slice(0, 10);
285
+ console.log(chalk_1.default.dim(`\n Skipped ${result.skipped.length}:`));
286
+ for (const skip of shown) {
287
+ console.log(chalk_1.default.dim(` ${skip.title} — ${SKIP_COPY[skip.reason]}`));
288
+ }
289
+ if (shown.length < result.skipped.length) {
290
+ console.log(chalk_1.default.dim(` ...and ${result.skipped.length - shown.length} more (-v to list)`));
291
+ }
292
+ }
293
+ // Say this loudly. A signed playlist that silently lost its envelope
294
+ // fails at the device, which is the worst place to discover it.
295
+ if (result.signatureInvalidated) {
296
+ console.log(chalk_1.default.yellow('\n Signature removed — the document changed.'));
297
+ console.log(chalk_1.default.dim(` Re-sign before playing: ff-cli sign ${destination}`));
298
+ }
299
+ console.log();
300
+ }
301
+ catch (error) {
302
+ if (error instanceof OwnershipError) {
303
+ console.error(chalk_1.default.red('\nThat playlist belongs to another user or group.'));
304
+ console.error(chalk_1.default.dim(` Replacing it in place would hand it to you and could lock others out,\n` +
305
+ ` so nothing was written. Write elsewhere instead:\n` +
306
+ ` ff-cli enrich ${error.target} -o enriched.json\n`));
307
+ process.exit(1);
308
+ }
309
+ console.error(chalk_1.default.red('\nError:'), error.message);
310
+ if (options.verbose) {
311
+ console.error(chalk_1.default.dim(error.stack));
312
+ }
313
+ process.exit(1);
314
+ }
315
+ });