@archildata/just-bash 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/dist/index.js ADDED
@@ -0,0 +1,514 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __esm = (fn, res) => function __init() {
6
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
7
+ };
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
21
+
22
+ // src/ArchilFs.ts
23
+ var ArchilFs_exports = {};
24
+ __export(ArchilFs_exports, {
25
+ ArchilFs: () => ArchilFs
26
+ });
27
+ import createDebug from "debug";
28
+ var debug, ArchilFs;
29
+ var init_ArchilFs = __esm({
30
+ "src/ArchilFs.ts"() {
31
+ "use strict";
32
+ debug = createDebug("archil:fs");
33
+ ArchilFs = class {
34
+ client;
35
+ user;
36
+ rootInodeId = 1;
37
+ /**
38
+ * Create a new ArchilFs adapter
39
+ *
40
+ * @param client - Connected ArchilClient instance
41
+ * @param options - Optional configuration
42
+ * @param options.user - Unix user context for permission checks
43
+ */
44
+ constructor(client, options) {
45
+ this.client = client;
46
+ this.user = options?.user;
47
+ }
48
+ // ========================================================================
49
+ // Path Resolution
50
+ // ========================================================================
51
+ /**
52
+ * Normalize a path (remove . and .., ensure leading /)
53
+ */
54
+ normalizePath(path) {
55
+ if (!path || path === "") {
56
+ return "/";
57
+ }
58
+ if (!path.startsWith("/")) {
59
+ path = "/" + path;
60
+ }
61
+ const parts = path.split("/").filter((p) => p !== "" && p !== ".");
62
+ const result = [];
63
+ for (const part of parts) {
64
+ if (part === "..") {
65
+ result.pop();
66
+ } else {
67
+ result.push(part);
68
+ }
69
+ }
70
+ return "/" + result.join("/");
71
+ }
72
+ /**
73
+ * Resolve a path to its inode ID, walking the directory tree
74
+ */
75
+ async resolve(path) {
76
+ const normalizedPath = this.normalizePath(path);
77
+ const parts = normalizedPath.split("/").filter((p) => p !== "");
78
+ let currentInodeId = this.rootInodeId;
79
+ for (const part of parts) {
80
+ const response = await this.client.lookupInode(currentInodeId, part, this.user);
81
+ if (response.inodeId === -1) {
82
+ throw new Error(`ENOENT: no such file or directory, '${path}'`);
83
+ }
84
+ currentInodeId = response.inodeId;
85
+ }
86
+ const attributes = await this.client.getAttributes(currentInodeId, this.user);
87
+ return { inodeId: currentInodeId, attributes };
88
+ }
89
+ /**
90
+ * Resolve parent directory and get child name
91
+ */
92
+ async resolveParent(path) {
93
+ debug("resolveParent raw path=%j (bytes: %o)", path, Buffer.from(path));
94
+ const normalizedPath = this.normalizePath(path);
95
+ const lastSlash = normalizedPath.lastIndexOf("/");
96
+ const parentPath = lastSlash === 0 ? "/" : normalizedPath.substring(0, lastSlash);
97
+ const name = normalizedPath.substring(lastSlash + 1);
98
+ debug("resolveParent extracted name=%j (bytes: %o)", name, Buffer.from(name));
99
+ const { inodeId: parentInodeId } = await this.resolve(parentPath);
100
+ return { parentInodeId, name };
101
+ }
102
+ /**
103
+ * Convert InodeAttributes to FsStat
104
+ */
105
+ toStat(attrs) {
106
+ return {
107
+ isFile: attrs.inodeType === "File",
108
+ isDirectory: attrs.inodeType === "Directory",
109
+ isSymlink: attrs.inodeType === "Symlink",
110
+ mode: attrs.mode,
111
+ size: Number(attrs.size),
112
+ mtime: new Date(attrs.mtimeMs)
113
+ };
114
+ }
115
+ // ========================================================================
116
+ // IFileSystem Implementation - Read Operations
117
+ // ========================================================================
118
+ resolvePath(base, ...paths) {
119
+ debug("resolvePath base=%s paths=%o", base, paths);
120
+ let result = base;
121
+ for (const p of paths) {
122
+ if (p.startsWith("/")) {
123
+ result = p;
124
+ } else {
125
+ result = result.endsWith("/") ? result + p : result + "/" + p;
126
+ }
127
+ }
128
+ const normalized = this.normalizePath(result);
129
+ debug("resolvePath result=%s", normalized);
130
+ return normalized;
131
+ }
132
+ async readFile(path, encoding) {
133
+ debug("readFile path=%s encoding=%s", path, encoding);
134
+ try {
135
+ const buffer = await this.readFileBuffer(path);
136
+ debug("readFile got buffer length=%d", buffer.length);
137
+ const decoderEncoding = encoding === "binary" ? "latin1" : encoding || "utf-8";
138
+ debug("readFile using decoder encoding=%s", decoderEncoding);
139
+ const decoder = new TextDecoder(decoderEncoding);
140
+ const result = decoder.decode(buffer);
141
+ debug("readFile decoded to string length=%d", result.length);
142
+ return result;
143
+ } catch (err) {
144
+ debug("readFile FAILED: %O", err);
145
+ throw err;
146
+ }
147
+ }
148
+ async readFileBuffer(path) {
149
+ debug("readFileBuffer path=%s", path);
150
+ const { inodeId, attributes } = await this.resolve(path);
151
+ debug("readFileBuffer resolved inodeId=%d type=%s size=%d", inodeId, attributes.inodeType, attributes.size);
152
+ if (attributes.inodeType !== "File") {
153
+ throw new Error(`EISDIR: illegal operation on a directory, read '${path}'`);
154
+ }
155
+ const size = Number(attributes.size);
156
+ if (size === 0) {
157
+ debug("readFileBuffer file is empty, returning empty buffer");
158
+ return new Uint8Array(0);
159
+ }
160
+ const MAX_CHUNK = 4 * 1024 * 1024;
161
+ if (size <= MAX_CHUNK) {
162
+ const buffer = await this.client.readInode(inodeId, 0, size, this.user);
163
+ return new Uint8Array(buffer);
164
+ }
165
+ const result = new Uint8Array(size);
166
+ let offset = 0;
167
+ while (offset < size) {
168
+ const chunkSize = Math.min(MAX_CHUNK, size - offset);
169
+ const chunk = await this.client.readInode(inodeId, offset, chunkSize, this.user);
170
+ result.set(new Uint8Array(chunk), offset);
171
+ offset += chunkSize;
172
+ }
173
+ return result;
174
+ }
175
+ async readdir(path) {
176
+ debug("readdir path=%s", path);
177
+ const { inodeId, attributes } = await this.resolve(path);
178
+ if (attributes.inodeType !== "Directory") {
179
+ throw new Error(`ENOTDIR: not a directory, scandir '${path}'`);
180
+ }
181
+ const entries = await this.client.readDirectory(inodeId, void 0, void 0, this.user);
182
+ for (const e of entries) {
183
+ debug("readdir entry name=%j (bytes: %o)", e.name, Buffer.from(e.name));
184
+ }
185
+ return entries.map((e) => e.name).filter((name) => name !== "." && name !== "..");
186
+ }
187
+ async readdirWithFileTypes(path) {
188
+ const { inodeId, attributes } = await this.resolve(path);
189
+ if (attributes.inodeType !== "Directory") {
190
+ throw new Error(`ENOTDIR: not a directory, scandir '${path}'`);
191
+ }
192
+ const entries = await this.client.readDirectory(inodeId, void 0, void 0, this.user);
193
+ return entries.filter((e) => e.name !== "." && e.name !== "..").map((e) => ({
194
+ name: e.name,
195
+ isFile: e.inodeType === "File",
196
+ isDirectory: e.inodeType === "Directory",
197
+ isSymlink: e.inodeType === "Symlink"
198
+ }));
199
+ }
200
+ async stat(path) {
201
+ debug("stat path=%s", path);
202
+ const { attributes } = await this.resolve(path);
203
+ if (attributes.inodeType === "Symlink" && attributes.symlinkTarget) {
204
+ const targetPath = attributes.symlinkTarget.startsWith("/") ? attributes.symlinkTarget : this.resolvePath(path, "..", attributes.symlinkTarget);
205
+ return this.stat(targetPath);
206
+ }
207
+ return this.toStat(attributes);
208
+ }
209
+ async lstat(path) {
210
+ debug("lstat path=%s", path);
211
+ const { attributes } = await this.resolve(path);
212
+ return this.toStat(attributes);
213
+ }
214
+ async exists(path) {
215
+ debug("exists path=%s", path);
216
+ try {
217
+ await this.resolve(path);
218
+ debug("exists path=%s -> true", path);
219
+ return true;
220
+ } catch {
221
+ debug("exists path=%s -> false", path);
222
+ return false;
223
+ }
224
+ }
225
+ async readlink(path) {
226
+ const { attributes } = await this.resolve(path);
227
+ if (attributes.inodeType !== "Symlink") {
228
+ throw new Error(`EINVAL: invalid argument, readlink '${path}'`);
229
+ }
230
+ return attributes.symlinkTarget || "";
231
+ }
232
+ async realpath(path) {
233
+ const normalizedPath = this.normalizePath(path);
234
+ const parts = normalizedPath.split("/").filter((p) => p !== "");
235
+ let resolvedPath = "/";
236
+ let currentInodeId = this.rootInodeId;
237
+ for (const part of parts) {
238
+ const response = await this.client.lookupInode(currentInodeId, part, this.user);
239
+ if (response.inodeId === -1) {
240
+ throw new Error(`ENOENT: no such file or directory, realpath '${path}'`);
241
+ }
242
+ const attrs = response.attributes;
243
+ if (attrs.inodeType === "Symlink" && attrs.symlinkTarget) {
244
+ const targetPath = attrs.symlinkTarget.startsWith("/") ? attrs.symlinkTarget : this.resolvePath(resolvedPath, attrs.symlinkTarget);
245
+ const resolved = await this.realpath(targetPath);
246
+ resolvedPath = resolved;
247
+ const { inodeId } = await this.resolve(resolved);
248
+ currentInodeId = inodeId;
249
+ } else {
250
+ resolvedPath = resolvedPath === "/" ? "/" + part : resolvedPath + "/" + part;
251
+ currentInodeId = response.inodeId;
252
+ }
253
+ }
254
+ return resolvedPath;
255
+ }
256
+ // ========================================================================
257
+ // IFileSystem Implementation - Write Operations
258
+ // ========================================================================
259
+ async writeFile(path, content) {
260
+ debug("writeFile path=%s contentLength=%d", path, content.length);
261
+ const data = typeof content === "string" ? new TextEncoder().encode(content) : content;
262
+ let inodeId;
263
+ try {
264
+ const resolved = await this.resolve(path);
265
+ inodeId = resolved.inodeId;
266
+ debug("writeFile resolved existing file path=%s inodeId=%d", path, inodeId);
267
+ if (resolved.attributes.inodeType !== "File") {
268
+ throw new Error(`EISDIR: illegal operation on a directory, write '${path}'`);
269
+ }
270
+ } catch (err) {
271
+ if (err instanceof Error && err.message.includes("EISDIR")) {
272
+ throw err;
273
+ }
274
+ debug("writeFile file doesn't exist, creating: %s", path);
275
+ const { parentInodeId, name } = await this.resolveParent(path);
276
+ debug("writeFile resolved parent parentInodeId=%d name=%s", parentInodeId, name);
277
+ const now = Date.now();
278
+ debug("writeFile calling create parent=%d name=%s", parentInodeId, name);
279
+ try {
280
+ inodeId = await this.client.create(
281
+ parentInodeId,
282
+ name,
283
+ {
284
+ inodeId: 0,
285
+ // Will be assigned by the filesystem
286
+ inodeType: "File",
287
+ size: 0,
288
+ uid: this.user?.uid ?? 0,
289
+ gid: this.user?.gid ?? 0,
290
+ mode: 420,
291
+ nlink: 1,
292
+ ctimeMs: now,
293
+ atimeMs: now,
294
+ mtimeMs: now,
295
+ btimeMs: now,
296
+ rdev: void 0,
297
+ symlinkTarget: void 0
298
+ },
299
+ this.user
300
+ );
301
+ debug("writeFile create succeeded inodeId=%d", inodeId);
302
+ } catch (createErr) {
303
+ debug("writeFile create FAILED: %O", createErr);
304
+ throw createErr;
305
+ }
306
+ }
307
+ debug("writeFile writing %d bytes to inodeId=%d", data.length, inodeId);
308
+ await this.client.writeData(inodeId, 0, Buffer.from(data), this.user);
309
+ debug("writeFile write succeeded");
310
+ }
311
+ async appendFile(path, content) {
312
+ let existing;
313
+ try {
314
+ existing = await this.readFileBuffer(path);
315
+ } catch {
316
+ existing = new Uint8Array(0);
317
+ }
318
+ const data = typeof content === "string" ? new TextEncoder().encode(content) : content;
319
+ const combined = new Uint8Array(existing.length + data.length);
320
+ combined.set(existing, 0);
321
+ combined.set(data, existing.length);
322
+ await this.writeFile(path, combined);
323
+ }
324
+ async mkdir(path, options) {
325
+ const normalizedPath = this.normalizePath(path);
326
+ if (options?.recursive) {
327
+ const parts = normalizedPath.split("/").filter((p) => p !== "");
328
+ let currentPath = "";
329
+ for (const part of parts) {
330
+ currentPath += "/" + part;
331
+ const exists = await this.exists(currentPath);
332
+ if (exists) {
333
+ continue;
334
+ }
335
+ await this.mkdirSingle(currentPath);
336
+ }
337
+ } else {
338
+ await this.mkdirSingle(normalizedPath);
339
+ }
340
+ }
341
+ async mkdirSingle(path) {
342
+ const { parentInodeId, name } = await this.resolveParent(path);
343
+ const now = Date.now();
344
+ await this.client.create(
345
+ parentInodeId,
346
+ name,
347
+ {
348
+ inodeId: 0,
349
+ // Will be assigned by the filesystem
350
+ inodeType: "Directory",
351
+ size: 4096,
352
+ uid: this.user?.uid ?? 0,
353
+ gid: this.user?.gid ?? 0,
354
+ mode: 493,
355
+ nlink: 2,
356
+ ctimeMs: now,
357
+ atimeMs: now,
358
+ mtimeMs: now,
359
+ btimeMs: now,
360
+ rdev: void 0,
361
+ symlinkTarget: void 0
362
+ },
363
+ this.user
364
+ );
365
+ }
366
+ async rm(path, options) {
367
+ let resolved;
368
+ try {
369
+ resolved = await this.resolve(path);
370
+ } catch {
371
+ if (options?.force) {
372
+ return;
373
+ }
374
+ throw new Error(`ENOENT: no such file or directory, rm '${path}'`);
375
+ }
376
+ if (resolved.attributes.inodeType === "Directory") {
377
+ if (!options?.recursive) {
378
+ throw new Error(`EISDIR: illegal operation on a directory, rm '${path}'`);
379
+ }
380
+ const entries = await this.readdir(path);
381
+ for (const entry of entries) {
382
+ await this.rm(this.resolvePath(path, entry), options);
383
+ }
384
+ }
385
+ const { parentInodeId, name } = await this.resolveParent(path);
386
+ await this.client.unlink(parentInodeId, name, this.user);
387
+ }
388
+ async cp(src, dest, options) {
389
+ const srcResolved = await this.resolve(src);
390
+ if (srcResolved.attributes.inodeType === "Directory") {
391
+ if (!options?.recursive) {
392
+ throw new Error(`EISDIR: illegal operation on a directory, cp '${src}'`);
393
+ }
394
+ await this.mkdir(dest, { recursive: true });
395
+ const entries = await this.readdir(src);
396
+ for (const entry of entries) {
397
+ await this.cp(
398
+ this.resolvePath(src, entry),
399
+ this.resolvePath(dest, entry),
400
+ options
401
+ );
402
+ }
403
+ } else {
404
+ const content = await this.readFileBuffer(src);
405
+ await this.writeFile(dest, content);
406
+ }
407
+ }
408
+ async mv(src, dest) {
409
+ const { parentInodeId: srcParentInodeId, name: srcName } = await this.resolveParent(src);
410
+ const { parentInodeId: destParentInodeId, name: destName } = await this.resolveParent(dest);
411
+ await this.client.rename(
412
+ srcParentInodeId,
413
+ srcName,
414
+ destParentInodeId,
415
+ destName,
416
+ this.user
417
+ );
418
+ }
419
+ async symlink(target, path) {
420
+ const { parentInodeId, name } = await this.resolveParent(path);
421
+ const now = Date.now();
422
+ await this.client.create(
423
+ parentInodeId,
424
+ name,
425
+ {
426
+ inodeId: 0,
427
+ // Will be assigned by the filesystem
428
+ inodeType: "Symlink",
429
+ size: target.length,
430
+ uid: this.user?.uid ?? 0,
431
+ gid: this.user?.gid ?? 0,
432
+ mode: 511,
433
+ nlink: 1,
434
+ ctimeMs: now,
435
+ atimeMs: now,
436
+ mtimeMs: now,
437
+ btimeMs: now,
438
+ rdev: void 0,
439
+ symlinkTarget: target
440
+ },
441
+ this.user
442
+ );
443
+ }
444
+ async link(existingPath, newPath) {
445
+ throw new Error(
446
+ "Hard link operations not yet implemented. The archil-node bindings need to expose link for hard links."
447
+ );
448
+ }
449
+ async chmod(path, mode) {
450
+ const { inodeId } = await this.resolve(path);
451
+ await this.client.setattr(
452
+ inodeId,
453
+ { mode },
454
+ this.user ?? { uid: 0, gid: 0 }
455
+ );
456
+ }
457
+ async utimes(path, atime, mtime) {
458
+ debug("utimes path=%s atime=%d mtime=%d", path, atime, mtime);
459
+ const { inodeId } = await this.resolve(path);
460
+ debug("utimes resolved path=%s inodeId=%d", path, inodeId);
461
+ const atimeMs = atime === -1 ? -1 : Math.floor(atime * 1e3);
462
+ const mtimeMs = mtime === -1 ? -1 : Math.floor(mtime * 1e3);
463
+ debug("utimes calling setattr inodeId=%d atimeMs=%d mtimeMs=%d", inodeId, atimeMs, mtimeMs);
464
+ await this.client.setattr(
465
+ inodeId,
466
+ { atimeMs, mtimeMs },
467
+ this.user ?? { uid: 0, gid: 0 }
468
+ );
469
+ debug("utimes setattr succeeded inodeId=%d", inodeId);
470
+ }
471
+ // ========================================================================
472
+ // Utility Methods
473
+ // ========================================================================
474
+ async getAllPaths() {
475
+ const paths = [];
476
+ const walk = async (dirPath) => {
477
+ paths.push(dirPath);
478
+ try {
479
+ const entries = await this.readdirWithFileTypes(dirPath);
480
+ for (const entry of entries) {
481
+ const fullPath = this.resolvePath(dirPath, entry.name);
482
+ if (entry.isDirectory) {
483
+ await walk(fullPath);
484
+ } else {
485
+ paths.push(fullPath);
486
+ }
487
+ }
488
+ } catch {
489
+ }
490
+ };
491
+ await walk("/");
492
+ return paths;
493
+ }
494
+ /**
495
+ * Resolve a path to its inode ID (public wrapper for delegation operations)
496
+ */
497
+ async resolveInodeId(path) {
498
+ const { inodeId } = await this.resolve(path);
499
+ return inodeId;
500
+ }
501
+ };
502
+ }
503
+ });
504
+
505
+ // src/index.ts
506
+ init_ArchilFs();
507
+ function createArchilFs(client, options) {
508
+ const { ArchilFs: ArchilFs2 } = (init_ArchilFs(), __toCommonJS(ArchilFs_exports));
509
+ return new ArchilFs2(client, options);
510
+ }
511
+ export {
512
+ ArchilFs,
513
+ createArchilFs
514
+ };