@archildata/just-bash 0.8.17 → 0.8.19

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,622 @@
1
+ import createDebug from "debug";
2
+ import { MAXIMUM_READ_SIZE } from "@archildata/native";
3
+ import { defineCommand } from "just-bash";
4
+ //#region src/ArchilFs.ts
5
+ /**
6
+ * Archil filesystem adapter for just-bash
7
+ *
8
+ * Implements the IFileSystem interface from just-bash using the ArchilClient
9
+ * from @archildata/native for direct protocol access to Archil distributed filesystems.
10
+ */
11
+ const debug = createDebug("archil:fs");
12
+ /**
13
+ * ArchilFs implements the just-bash IFileSystem interface using Archil protocol.
14
+ *
15
+ * This adapter provides:
16
+ * - Path-to-inode resolution
17
+ * - Full filesystem operations via Archil protocol
18
+ * - Optional user context for permission checks
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * import { ArchilClient } from '@archildata/native';
23
+ * import { ArchilFs } from '@archildata/just-bash';
24
+ *
25
+ * const client = await ArchilClient.connect({
26
+ * region: 'aws-us-east-1',
27
+ * diskName: 'myaccount/mydisk',
28
+ * authToken: 'adt_xxx',
29
+ * });
30
+ *
31
+ * const fs = await ArchilFs.create(client);
32
+ *
33
+ * // Use with just-bash
34
+ * import { Bash } from 'just-bash';
35
+ * const bash = new Bash({ fs });
36
+ * await bash.run('ls -la /');
37
+ * ```
38
+ */
39
+ var ArchilFs = class ArchilFs {
40
+ client;
41
+ user;
42
+ rootInodeId = 1;
43
+ constructor(client, options) {
44
+ this.client = client;
45
+ this.user = options?.user;
46
+ }
47
+ /**
48
+ * Create an ArchilFs adapter, optionally rooted at a subdirectory.
49
+ *
50
+ * The subdirectory path is resolved eagerly: if any component does not
51
+ * exist or is not a directory, this method throws immediately.
52
+ *
53
+ * @param client - Connected ArchilClient instance
54
+ * @param options - Optional configuration
55
+ * @param options.user - Unix user context for permission checks
56
+ * @param options.subdirectory - Subdirectory to treat as the root of the filesystem
57
+ */
58
+ static async create(client, options) {
59
+ const fs = new ArchilFs(client, { user: options?.user });
60
+ if (options?.subdirectory) {
61
+ const resolved = await fs.resolveFollow(options.subdirectory);
62
+ if (resolved.attributes.inodeType !== "Directory") throw new Error(`ENOTDIR: subdirectory '${options.subdirectory}' is not a directory`);
63
+ fs.rootInodeId = resolved.inodeId;
64
+ debug("resolved subdirectory '%s' to inode %d", options.subdirectory, fs.rootInodeId);
65
+ }
66
+ return fs;
67
+ }
68
+ /**
69
+ * Normalize a path (remove . and .., ensure leading /)
70
+ */
71
+ normalizePath(path) {
72
+ if (!path || path === "") return "/";
73
+ if (!path.startsWith("/")) path = "/" + path;
74
+ const parts = path.split("/").filter((p) => p !== "" && p !== ".");
75
+ const result = [];
76
+ for (const part of parts) if (part === "..") result.pop();
77
+ else result.push(part);
78
+ return "/" + result.join("/");
79
+ }
80
+ static MAX_SYMLINKS = 40;
81
+ /**
82
+ * Resolve a path to its inode ID, walking the directory tree.
83
+ * Follows symlinks on intermediate components but NOT on the final
84
+ * component (matching lstat/readlink semantics).
85
+ */
86
+ async resolve(path, symlinkDepth = 0) {
87
+ const parts = this.normalizePath(path).split("/").filter((p) => p !== "");
88
+ let currentInodeId = this.rootInodeId;
89
+ let resolvedPath = "/";
90
+ for (let i = 0; i < parts.length; i++) {
91
+ const part = parts[i];
92
+ const response = await this.client.lookupInode(currentInodeId, part, { user: this.user });
93
+ if (response === null) throw new Error(`ENOENT: no such file or directory, '${path}'`);
94
+ if (!(i === parts.length - 1) && response.attributes.inodeType === "Symlink" && response.attributes.symlinkTarget) {
95
+ if (symlinkDepth >= ArchilFs.MAX_SYMLINKS) throw new Error(`ELOOP: too many levels of symbolic links, '${path}'`);
96
+ const targetPath = response.attributes.symlinkTarget.startsWith("/") ? response.attributes.symlinkTarget : this.resolvePath(resolvedPath, response.attributes.symlinkTarget);
97
+ const remaining = parts.slice(i + 1).join("/");
98
+ const fullPath = remaining ? targetPath + "/" + remaining : targetPath;
99
+ return this.resolve(fullPath, symlinkDepth + 1);
100
+ }
101
+ resolvedPath = resolvedPath === "/" ? "/" + part : resolvedPath + "/" + part;
102
+ currentInodeId = response.inodeId;
103
+ }
104
+ const attributes = await this.client.getAttributes(currentInodeId, { user: this.user });
105
+ return {
106
+ inodeId: currentInodeId,
107
+ attributes
108
+ };
109
+ }
110
+ /**
111
+ * Resolve a path, following symlinks on ALL components including the
112
+ * final one (like stat(2)). Use resolve() when you need lstat semantics.
113
+ */
114
+ async resolveFollow(path, symlinkDepth = 0) {
115
+ if (symlinkDepth >= ArchilFs.MAX_SYMLINKS) throw new Error(`ELOOP: too many levels of symbolic links, '${path}'`);
116
+ const resolved = await this.resolve(path, symlinkDepth);
117
+ if (resolved.attributes.inodeType === "Symlink" && resolved.attributes.symlinkTarget) {
118
+ const targetPath = resolved.attributes.symlinkTarget.startsWith("/") ? resolved.attributes.symlinkTarget : this.resolvePath(path, "..", resolved.attributes.symlinkTarget);
119
+ return this.resolveFollow(targetPath, symlinkDepth + 1);
120
+ }
121
+ return resolved;
122
+ }
123
+ /**
124
+ * Resolve parent directory and get child name
125
+ */
126
+ async resolveParent(path) {
127
+ debug("resolveParent raw path=%j (bytes: %o)", path, Buffer.from(path));
128
+ const normalizedPath = this.normalizePath(path);
129
+ const lastSlash = normalizedPath.lastIndexOf("/");
130
+ const parentPath = lastSlash === 0 ? "/" : normalizedPath.substring(0, lastSlash);
131
+ const name = normalizedPath.substring(lastSlash + 1);
132
+ debug("resolveParent extracted name=%j (bytes: %o)", name, Buffer.from(name));
133
+ const { inodeId: parentInodeId } = await this.resolve(parentPath);
134
+ return {
135
+ parentInodeId,
136
+ name
137
+ };
138
+ }
139
+ /**
140
+ * Convert InodeAttributes to FsStat
141
+ */
142
+ toStat(attrs) {
143
+ return {
144
+ isFile: attrs.inodeType === "File",
145
+ isDirectory: attrs.inodeType === "Directory",
146
+ isSymbolicLink: attrs.inodeType === "Symlink",
147
+ mode: attrs.mode,
148
+ size: Number(attrs.size),
149
+ mtime: new Date(attrs.mtimeMs)
150
+ };
151
+ }
152
+ static DIR_PAGE_SIZE = 1e3;
153
+ /**
154
+ * Read all directory entries using the paginated API.
155
+ */
156
+ async readAllDirectoryEntries(inodeId) {
157
+ const handle = await this.client.openDirectory(inodeId, { user: this.user });
158
+ try {
159
+ const allEntries = [];
160
+ let cursor;
161
+ for (;;) {
162
+ const page = await this.client.readDirectory(inodeId, handle, ArchilFs.DIR_PAGE_SIZE, cursor, { user: this.user });
163
+ allEntries.push(...page.entries);
164
+ if (!page.nextCursor) break;
165
+ cursor = page.nextCursor;
166
+ }
167
+ return allEntries;
168
+ } finally {
169
+ this.client.closeDirectory(inodeId, handle);
170
+ }
171
+ }
172
+ resolvePath(base, ...paths) {
173
+ debug("resolvePath base=%s paths=%o", base, paths);
174
+ let result = base;
175
+ for (const p of paths) if (p.startsWith("/")) result = p;
176
+ else result = result.endsWith("/") ? result + p : result + "/" + p;
177
+ const normalized = this.normalizePath(result);
178
+ debug("resolvePath result=%s", normalized);
179
+ return normalized;
180
+ }
181
+ async readFile(path, encoding) {
182
+ debug("readFile path=%s encoding=%s", path, encoding);
183
+ try {
184
+ const buffer = await this.readFileBuffer(path);
185
+ debug("readFile got buffer length=%d", buffer.length);
186
+ const enc = encoding || "utf-8";
187
+ let result;
188
+ if (enc === "base64" || enc === "hex" || enc === "binary") result = Buffer.from(buffer).toString(enc);
189
+ else result = new TextDecoder(enc).decode(buffer);
190
+ debug("readFile decoded to string length=%d", result.length);
191
+ return result;
192
+ } catch (err) {
193
+ debug("readFile FAILED: %O", err);
194
+ throw err;
195
+ }
196
+ }
197
+ async readFileBuffer(path) {
198
+ debug("readFileBuffer path=%s", path);
199
+ const { inodeId, attributes } = await this.resolveFollow(path);
200
+ debug("readFileBuffer resolved inodeId=%d type=%s size=%d", inodeId, attributes.inodeType, attributes.size);
201
+ if (attributes.inodeType !== "File") throw new Error(`EISDIR: illegal operation on a directory, read '${path}'`);
202
+ const size = Number(attributes.size);
203
+ if (size === 0) {
204
+ debug("readFileBuffer file is empty, returning empty buffer");
205
+ return /* @__PURE__ */ new Uint8Array(0);
206
+ }
207
+ if (size <= MAXIMUM_READ_SIZE) {
208
+ const buffer = await this.client.readInode(inodeId, 0, size, { user: this.user });
209
+ return new Uint8Array(buffer);
210
+ }
211
+ const result = new Uint8Array(size);
212
+ let offset = 0;
213
+ while (offset < size) {
214
+ const chunkSize = Math.min(MAXIMUM_READ_SIZE, size - offset);
215
+ const chunk = await this.client.readInode(inodeId, offset, chunkSize, { user: this.user });
216
+ result.set(new Uint8Array(chunk), offset);
217
+ offset += chunkSize;
218
+ }
219
+ return result;
220
+ }
221
+ async readdir(path) {
222
+ debug("readdir path=%s", path);
223
+ const { inodeId, attributes } = await this.resolveFollow(path);
224
+ if (attributes.inodeType !== "Directory") throw new Error(`ENOTDIR: not a directory, scandir '${path}'`);
225
+ const entries = await this.readAllDirectoryEntries(inodeId);
226
+ for (const e of entries) debug("readdir entry name=%j (bytes: %o)", e.name, Buffer.from(e.name));
227
+ return entries.map((e) => e.name).filter((name) => name !== "." && name !== "..");
228
+ }
229
+ async readdirWithFileTypes(path) {
230
+ const { inodeId, attributes } = await this.resolveFollow(path);
231
+ if (attributes.inodeType !== "Directory") throw new Error(`ENOTDIR: not a directory, scandir '${path}'`);
232
+ return (await this.readAllDirectoryEntries(inodeId)).filter((e) => e.name !== "." && e.name !== "..").map((e) => ({
233
+ name: e.name,
234
+ isFile: e.inodeType === "File",
235
+ isDirectory: e.inodeType === "Directory",
236
+ isSymbolicLink: e.inodeType === "Symlink"
237
+ }));
238
+ }
239
+ async stat(path) {
240
+ debug("stat path=%s", path);
241
+ const { attributes } = await this.resolveFollow(path);
242
+ return this.toStat(attributes);
243
+ }
244
+ async lstat(path) {
245
+ debug("lstat path=%s", path);
246
+ const { attributes } = await this.resolve(path);
247
+ return this.toStat(attributes);
248
+ }
249
+ async exists(path) {
250
+ debug("exists path=%s", path);
251
+ try {
252
+ await this.resolve(path);
253
+ debug("exists path=%s -> true", path);
254
+ return true;
255
+ } catch {
256
+ debug("exists path=%s -> false", path);
257
+ return false;
258
+ }
259
+ }
260
+ async readlink(path) {
261
+ const { attributes } = await this.resolve(path);
262
+ if (attributes.inodeType !== "Symlink") throw new Error(`EINVAL: invalid argument, readlink '${path}'`);
263
+ return attributes.symlinkTarget || "";
264
+ }
265
+ async realpath(path, symlinkDepth = 0) {
266
+ const parts = this.normalizePath(path).split("/").filter((p) => p !== "");
267
+ let resolvedPath = "/";
268
+ let currentInodeId = this.rootInodeId;
269
+ for (const part of parts) {
270
+ const response = await this.client.lookupInode(currentInodeId, part, { user: this.user });
271
+ if (response === null) throw new Error(`ENOENT: no such file or directory, realpath '${path}'`);
272
+ const attrs = response.attributes;
273
+ if (attrs.inodeType === "Symlink" && attrs.symlinkTarget) {
274
+ if (symlinkDepth >= ArchilFs.MAX_SYMLINKS) throw new Error(`ELOOP: too many levels of symbolic links, '${path}'`);
275
+ const targetPath = attrs.symlinkTarget.startsWith("/") ? attrs.symlinkTarget : this.resolvePath(resolvedPath, attrs.symlinkTarget);
276
+ const resolved = await this.realpath(targetPath, symlinkDepth + 1);
277
+ resolvedPath = resolved;
278
+ const { inodeId } = await this.resolve(resolved);
279
+ currentInodeId = inodeId;
280
+ } else {
281
+ resolvedPath = resolvedPath === "/" ? "/" + part : resolvedPath + "/" + part;
282
+ currentInodeId = response.inodeId;
283
+ }
284
+ }
285
+ return resolvedPath;
286
+ }
287
+ async writeFile(path, content) {
288
+ debug("writeFile path=%s contentLength=%d", path, content.length);
289
+ const data = typeof content === "string" ? new TextEncoder().encode(content) : content;
290
+ let resolved;
291
+ try {
292
+ resolved = await this.resolveFollow(path);
293
+ } catch (err) {
294
+ if (err instanceof Error && err.message.includes("ENOENT")) resolved = null;
295
+ else throw err;
296
+ }
297
+ if (resolved !== null) {
298
+ debug("writeFile resolved existing file path=%s inodeId=%d", path, resolved.inodeId);
299
+ if (resolved.attributes.inodeType !== "File") throw new Error(`EISDIR: illegal operation on a directory, write '${path}'`);
300
+ const realPath = await this.realpath(path);
301
+ const { parentInodeId, name } = await this.resolveParent(realPath);
302
+ const tmpName = `.~tmp-${Math.random().toString(36).slice(2)}`;
303
+ debug("writeFile atomic overwrite via temp=%s", tmpName);
304
+ const tmpResult = await this.client.create(parentInodeId, tmpName, {
305
+ inodeType: "File",
306
+ uid: resolved.attributes.uid,
307
+ gid: resolved.attributes.gid,
308
+ mode: resolved.attributes.mode
309
+ }, { user: this.user });
310
+ try {
311
+ await this.client.writeData(tmpResult.inodeId, 0, Buffer.from(data), { user: this.user });
312
+ await this.client.rename(parentInodeId, tmpName, parentInodeId, name, { user: this.user });
313
+ debug("writeFile atomic overwrite succeeded");
314
+ } catch (writeErr) {
315
+ try {
316
+ await this.client.unlink(parentInodeId, tmpName, { user: this.user });
317
+ } catch {}
318
+ throw writeErr;
319
+ }
320
+ return;
321
+ }
322
+ debug("writeFile file doesn't exist, creating: %s", path);
323
+ const { parentInodeId, name } = await this.resolveParent(path);
324
+ debug("writeFile resolved parent parentInodeId=%d name=%s", parentInodeId, name);
325
+ const result = await this.client.create(parentInodeId, name, {
326
+ inodeType: "File",
327
+ uid: this.user?.uid ?? 0,
328
+ gid: this.user?.gid ?? 0,
329
+ mode: 420
330
+ }, { user: this.user });
331
+ debug("writeFile create succeeded inodeId=%d", result.inodeId);
332
+ await this.client.writeData(result.inodeId, 0, Buffer.from(data), { user: this.user });
333
+ debug("writeFile write succeeded");
334
+ }
335
+ async appendFile(path, content) {
336
+ const data = typeof content === "string" ? new TextEncoder().encode(content) : content;
337
+ let inodeId;
338
+ let size;
339
+ try {
340
+ const resolved = await this.resolveFollow(path);
341
+ if (resolved.attributes.inodeType !== "File") throw new Error(`EISDIR: illegal operation on a directory, write '${path}'`);
342
+ inodeId = resolved.inodeId;
343
+ size = Number(resolved.attributes.size);
344
+ } catch (err) {
345
+ if (err instanceof Error && err.message.includes("ENOENT")) {
346
+ await this.writeFile(path, data);
347
+ return;
348
+ }
349
+ throw err;
350
+ }
351
+ await this.client.writeData(inodeId, size, Buffer.from(data), { user: this.user });
352
+ }
353
+ async mkdir(path, options) {
354
+ const normalizedPath = this.normalizePath(path);
355
+ if (options?.recursive) {
356
+ const parts = normalizedPath.split("/").filter((p) => p !== "");
357
+ let currentPath = "";
358
+ for (const part of parts) {
359
+ currentPath += "/" + part;
360
+ if (await this.exists(currentPath)) continue;
361
+ await this.mkdirSingle(currentPath);
362
+ }
363
+ } else await this.mkdirSingle(normalizedPath);
364
+ }
365
+ async mkdirSingle(path) {
366
+ const { parentInodeId, name } = await this.resolveParent(path);
367
+ await this.client.create(parentInodeId, name, {
368
+ inodeType: "Directory",
369
+ uid: this.user?.uid ?? 0,
370
+ gid: this.user?.gid ?? 0,
371
+ mode: 493
372
+ }, { user: this.user });
373
+ }
374
+ async rm(path, options) {
375
+ let resolved;
376
+ try {
377
+ resolved = await this.resolve(path);
378
+ } catch (err) {
379
+ if (err instanceof Error && err.message.includes("ENOENT")) {
380
+ if (options?.force) return;
381
+ throw err;
382
+ }
383
+ throw err;
384
+ }
385
+ if (resolved.attributes.inodeType === "Directory") {
386
+ if (!options?.recursive) throw new Error(`EISDIR: illegal operation on a directory, rm '${path}'`);
387
+ const entries = await this.readdir(path);
388
+ for (const entry of entries) await this.rm(this.resolvePath(path, entry), options);
389
+ }
390
+ const { parentInodeId, name } = await this.resolveParent(path);
391
+ await this.client.unlink(parentInodeId, name, { user: this.user });
392
+ }
393
+ async cp(src, dest, options) {
394
+ if ((await this.resolveFollow(src)).attributes.inodeType === "Directory") {
395
+ if (!options?.recursive) throw new Error(`EISDIR: illegal operation on a directory, cp '${src}'`);
396
+ await this.mkdir(dest, { recursive: true });
397
+ const entries = await this.readdir(src);
398
+ for (const entry of entries) await this.cp(this.resolvePath(src, entry), this.resolvePath(dest, entry), options);
399
+ } else {
400
+ const content = await this.readFileBuffer(src);
401
+ await this.writeFile(dest, content);
402
+ }
403
+ }
404
+ async mv(src, dest) {
405
+ const { parentInodeId: srcParentInodeId, name: srcName } = await this.resolveParent(src);
406
+ const { parentInodeId: destParentInodeId, name: destName } = await this.resolveParent(dest);
407
+ await this.client.rename(srcParentInodeId, srcName, destParentInodeId, destName, { user: this.user });
408
+ }
409
+ async symlink(target, path) {
410
+ const { parentInodeId, name } = await this.resolveParent(path);
411
+ await this.client.create(parentInodeId, name, {
412
+ inodeType: "Symlink",
413
+ uid: this.user?.uid ?? 0,
414
+ gid: this.user?.gid ?? 0,
415
+ mode: 511,
416
+ symlinkTarget: target
417
+ }, { user: this.user });
418
+ }
419
+ async link(existingPath, newPath) {
420
+ throw new Error("Hard link operations not yet implemented. The archil-node bindings need to expose link for hard links.");
421
+ }
422
+ async chmod(path, mode) {
423
+ const { inodeId } = await this.resolveFollow(path);
424
+ await this.client.setattr(inodeId, { mode }, { user: this.user ?? {
425
+ uid: 0,
426
+ gid: 0
427
+ } });
428
+ }
429
+ async utimes(path, atime, mtime) {
430
+ debug("utimes path=%s atime=%s mtime=%s", path, atime.toISOString(), mtime.toISOString());
431
+ const { inodeId } = await this.resolveFollow(path);
432
+ debug("utimes resolved path=%s inodeId=%d", path, inodeId);
433
+ const atimeMs = atime.getTime();
434
+ const mtimeMs = mtime.getTime();
435
+ debug("utimes calling setattr inodeId=%d atimeMs=%d mtimeMs=%d", inodeId, atimeMs, mtimeMs);
436
+ await this.client.setattr(inodeId, {
437
+ atimeMs,
438
+ mtimeMs
439
+ }, { user: this.user ?? {
440
+ uid: 0,
441
+ gid: 0
442
+ } });
443
+ debug("utimes setattr succeeded inodeId=%d", inodeId);
444
+ }
445
+ getAllPaths() {
446
+ return [];
447
+ }
448
+ /**
449
+ * Resolve a path to its inode ID (public wrapper for delegation operations)
450
+ */
451
+ async resolveInodeId(path) {
452
+ const { inodeId } = await this.resolve(path);
453
+ return inodeId;
454
+ }
455
+ };
456
+ //#endregion
457
+ //#region src/commands.ts
458
+ /**
459
+ * Create the `archil` custom command for use with just-bash.
460
+ *
461
+ * Provides checkout/checkin delegation management, delegation listing, and
462
+ * cache control (invalidate-cache, set-cache-expiry) as a shell command that
463
+ * works in scripts, pipes, and interactive use.
464
+ *
465
+ * @example
466
+ * ```typescript
467
+ * import { Bash } from 'just-bash';
468
+ * import { ArchilFs, createArchilCommand } from '@archildata/just-bash';
469
+ *
470
+ * const fs = await ArchilFs.create(client);
471
+ * const bash = new Bash({
472
+ * fs,
473
+ * customCommands: [createArchilCommand(client, fs)],
474
+ * });
475
+ *
476
+ * await bash.exec('archil checkout /mydir');
477
+ * await bash.exec('echo "hello" > /mydir/file.txt');
478
+ * await bash.exec('archil checkin /mydir');
479
+ * ```
480
+ */
481
+ function createArchilCommand(client, fs) {
482
+ return defineCommand("archil", async (args, ctx) => {
483
+ const ok = (stdout) => ({
484
+ stdout,
485
+ stderr: "",
486
+ exitCode: 0
487
+ });
488
+ const fail = (stderr) => ({
489
+ stdout: "",
490
+ stderr,
491
+ exitCode: 1
492
+ });
493
+ const subcommand = args[0];
494
+ if (subcommand === "checkout") {
495
+ const rest = args.slice(1);
496
+ const force = rest.includes("--force") || rest.includes("-f");
497
+ const pathArg = rest.find((a) => !a.startsWith("-"));
498
+ if (!pathArg) return fail("Usage: archil checkout [--force|-f] <path>\n");
499
+ const fullPath = fs.resolvePath(ctx.cwd, pathArg);
500
+ try {
501
+ const inodeId = await fs.resolveInodeId(fullPath);
502
+ await client.checkout(inodeId, { force });
503
+ return ok(`Checked out: ${fullPath} (inode ${inodeId})${force ? " (forced)" : ""}\n`);
504
+ } catch (err) {
505
+ return fail(`Failed to checkout ${fullPath}: ${err instanceof Error ? err.message : err}\n`);
506
+ }
507
+ }
508
+ if (subcommand === "checkin") {
509
+ const pathArg = args[1];
510
+ if (!pathArg) return fail("Usage: archil checkin <path>\n");
511
+ const fullPath = fs.resolvePath(ctx.cwd, pathArg);
512
+ try {
513
+ const inodeId = await fs.resolveInodeId(fullPath);
514
+ await client.checkin(inodeId);
515
+ return ok(`Checked in: ${fullPath} (inode ${inodeId})\n`);
516
+ } catch (err) {
517
+ return fail(`Failed to checkin ${fullPath}: ${err instanceof Error ? err.message : err}\n`);
518
+ }
519
+ }
520
+ if (subcommand === "list-delegations" || subcommand === "delegations") try {
521
+ const delegations = client.listDelegations();
522
+ if (delegations.length === 0) return ok("No delegations held\n");
523
+ return ok("Delegations:\n" + delegations.map((d) => ` inode ${d.inodeId}: ${d.state}`).join("\n") + "\n");
524
+ } catch (err) {
525
+ return fail(`Failed to list delegations: ${err instanceof Error ? err.message : err}\n`);
526
+ }
527
+ if (subcommand === "invalidate-cache") {
528
+ const pathArg = args.slice(1).find((a) => !a.startsWith("-"));
529
+ let scopeLabel = "(mount-wide)";
530
+ if (pathArg) {
531
+ const fullPath = fs.resolvePath(ctx.cwd, pathArg);
532
+ try {
533
+ await fs.resolveInodeId(fullPath);
534
+ scopeLabel = `(via ${fullPath})`;
535
+ } catch (err) {
536
+ return fail(`Failed to resolve ${fullPath}: ${err instanceof Error ? err.message : err}\n`);
537
+ }
538
+ }
539
+ try {
540
+ const stats = client.invalidateCache();
541
+ return ok(`Invalidated cache ${scopeLabel}: ${stats.totalEvictedInodes} inodes evicted (attr=${stats.attribute}, xattr=${stats.extendedAttribute}, dirent=${stats.dirent}, file=${stats.fileData})\n`);
542
+ } catch (err) {
543
+ return fail(`Failed to invalidate cache: ${err instanceof Error ? err.message : err}\n`);
544
+ }
545
+ }
546
+ if (subcommand === "set-cache-expiry") {
547
+ const rest = args.slice(1);
548
+ const flagIdx = rest.indexOf("--readdir-expiry");
549
+ if (flagIdx === -1 || flagIdx === rest.length - 1) return fail("Usage: archil set-cache-expiry <path> --readdir-expiry <seconds>\n");
550
+ const flagValueIdx = flagIdx + 1;
551
+ const expirySeconds = Number(rest[flagValueIdx]);
552
+ if (!Number.isInteger(expirySeconds) || expirySeconds < 0) return fail("--readdir-expiry must be a non-negative integer (seconds)\n");
553
+ const pathArg = rest.find((a, i) => i !== flagIdx && i !== flagValueIdx && !a.startsWith("-"));
554
+ if (!pathArg) return fail("Usage: archil set-cache-expiry <path> --readdir-expiry <seconds>\n");
555
+ const fullPath = fs.resolvePath(ctx.cwd, pathArg);
556
+ try {
557
+ const inodeId = await fs.resolveInodeId(fullPath);
558
+ client.setCacheExpiry(inodeId, expirySeconds);
559
+ return ok(`Set readdir cache expiry for ${fullPath} (inode ${inodeId}) to ${expirySeconds}s\n`);
560
+ } catch (err) {
561
+ return fail(`Failed to set cache expiry for ${fullPath}: ${err instanceof Error ? err.message : err}\n`);
562
+ }
563
+ }
564
+ if (subcommand === "help" || !subcommand) return ok("Archil commands:\n archil checkout [--force|-f] <path> - Acquire write delegation\n archil checkin <path> - Release write delegation\n archil list-delegations - Show held delegations\n archil invalidate-cache [<path>] - Drop every evictable cache entry\n archil set-cache-expiry <path> --readdir-expiry <secs>\n - Set readdir cache TTL on a directory\n archil help - Show this help message\n\nThe --force flag revokes any existing delegation from other clients.\n");
565
+ return fail(`Unknown archil command: ${subcommand}\nRun 'archil help' for available commands\n`);
566
+ });
567
+ }
568
+ //#endregion
569
+ //#region src/index.ts
570
+ /**
571
+ * @archildata/just-bash - Archil filesystem adapter for just-bash
572
+ *
573
+ * This package provides a filesystem adapter that allows just-bash to use
574
+ * Archil distributed filesystems as a backend.
575
+ *
576
+ * @example
577
+ * ```typescript
578
+ * import { ArchilClient } from '@archildata/native';
579
+ * import { ArchilFs } from '@archildata/just-bash';
580
+ * import { Bash } from 'just-bash';
581
+ *
582
+ * // Connect to Archil
583
+ * const client = await ArchilClient.connect({
584
+ * region: 'aws-us-east-1',
585
+ * diskName: 'myaccount/mydisk',
586
+ * authToken: 'adt_xxx',
587
+ * });
588
+ *
589
+ * // Create filesystem adapter
590
+ * const fs = await ArchilFs.create(client);
591
+ *
592
+ * // Use with just-bash
593
+ * const bash = new Bash({ fs });
594
+ * const result = await bash.run('ls -la /');
595
+ * console.log(result.stdout);
596
+ * ```
597
+ *
598
+ * @packageDocumentation
599
+ */
600
+ /**
601
+ * Create an ArchilFs instance, optionally rooted at a subdirectory.
602
+ *
603
+ * @param client - Connected ArchilClient instance
604
+ * @param options - Optional configuration
605
+ * @returns Configured ArchilFs instance
606
+ *
607
+ * @example
608
+ * ```typescript
609
+ * import { ArchilClient } from '@archildata/native';
610
+ * import { createArchilFs } from '@archildata/just-bash';
611
+ *
612
+ * const client = await ArchilClient.connectAuthenticated({...});
613
+ * const fs = await createArchilFs(client, { user: { uid: 1000, gid: 1000 } });
614
+ * ```
615
+ */
616
+ async function createArchilFs(client, options) {
617
+ return ArchilFs.create(client, options);
618
+ }
619
+ //#endregion
620
+ export { createArchilCommand as n, ArchilFs as r, createArchilFs as t };
621
+
622
+ //# sourceMappingURL=src-zhIdm_Vq.mjs.map