@statewalker/webrun-files-composite 0.7.1 → 0.8.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/esm/index.js CHANGED
@@ -23,9 +23,42 @@ function joinPath(...segments) {
23
23
  }
24
24
  //#endregion
25
25
  //#region src/composite-files-api.ts
26
+ /**
27
+ * Composite `FilesApi` that routes calls to one of several backends based
28
+ * on a path prefix. Mounts are matched by **longest prefix wins**, so a
29
+ * mount at `/a/b` takes precedence over a mount at `/a` for paths under
30
+ * `/a/b/...`. The mount point itself appears in listings as a synthetic
31
+ * directory and cannot be removed.
32
+ *
33
+ * Each backend can use a sub-directory of its own filesystem as the mount
34
+ * root via `fsPath` (constructor `rootPath` for the implicit root mount,
35
+ * `fsPath` argument for additional mounts). Cross-mount `move` is
36
+ * implemented as copy-then-delete; there is no atomicity guarantee.
37
+ *
38
+ * Access control and visibility filtering are intentionally **not** part of
39
+ * this class — wrap with {@link GuardedFilesApi} or {@link FilteredFilesApi}
40
+ * (or both) instead.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * const fs = new CompositeFilesApi(localFs, "/projects")
45
+ * .mount("/docs", s3Fs, "/documentation")
46
+ * .mount("/cache", memFs);
47
+ * await fs.write("/readme.md", data); // → localFs:/projects/readme.md
48
+ * await fs.write("/docs/api.md", data); // → s3Fs:/documentation/api.md
49
+ * ```
50
+ */
26
51
  var CompositeFilesApi = class {
27
52
  mounts;
28
- guards = [];
53
+ /**
54
+ * @param root Default backend used for any path that does not match a
55
+ * more specific mount. All paths are routed here unless `mount()`
56
+ * intercepts them.
57
+ * @param rootPath Optional sub-directory of the root backend to use as
58
+ * the composite filesystem's `/`. For example, `rootPath = "/projects"`
59
+ * makes the composite path `/readme.md` resolve to `/projects/readme.md`
60
+ * in the root backend. Defaults to `"/"` (no remapping).
61
+ */
29
62
  constructor(root, rootPath) {
30
63
  this.mounts = [{
31
64
  prefix: "/",
@@ -33,6 +66,22 @@ var CompositeFilesApi = class {
33
66
  basePath: normalizePath(rootPath ?? "/")
34
67
  }];
35
68
  }
69
+ /**
70
+ * Attaches a backend to handle every composite path under `path`. The
71
+ * mount prefix is normalized; paths under it are resolved against the
72
+ * mount's `fsPath` sub-directory (defaulting to `"/"`).
73
+ *
74
+ * @param path Composite-namespace prefix (e.g. `"/docs"`). Mounting at
75
+ * `"/"` is forbidden — use the constructor `root` argument instead.
76
+ * @param api The backend `FilesApi` to delegate to for paths under
77
+ * `path`. Wrap it in {@link FilteredFilesApi} / {@link GuardedFilesApi}
78
+ * first if you want mount-local filtering or guards.
79
+ * @param fsPath Sub-directory of the mounted backend used as its mount
80
+ * root, e.g. `mount("/docs", s3, "/documentation")` makes
81
+ * `/docs/api.md` resolve to `/documentation/api.md` on `s3`.
82
+ * @returns `this`, for chaining.
83
+ * @throws If `path` normalizes to `"/"`.
84
+ */
36
85
  mount(path, api, fsPath) {
37
86
  const prefix = normalizePath(path);
38
87
  if (prefix === "/") throw new Error("Cannot mount at root — root is set via constructor");
@@ -44,14 +93,6 @@ var CompositeFilesApi = class {
44
93
  this.mounts.sort((a, b) => b.prefix.length - a.prefix.length);
45
94
  return this;
46
95
  }
47
- guard(operations, check, message) {
48
- this.guards.push({
49
- operations,
50
- check,
51
- message
52
- });
53
- return this;
54
- }
55
96
  resolve(path) {
56
97
  const normalized = normalizePath(path);
57
98
  for (const mount of this.mounts) {
@@ -89,33 +130,19 @@ var CompositeFilesApi = class {
89
130
  }
90
131
  return result;
91
132
  }
92
- checkGuard(operation, path) {
93
- const normalized = normalizePath(path);
94
- for (const guard of this.guards) {
95
- if (!guard.operations.includes(operation)) continue;
96
- if (!guard.check(normalized)) {
97
- const msg = guard.message ?? "Access denied";
98
- throw new Error(`${msg}: ${normalized}`);
99
- }
100
- }
101
- }
102
133
  read(path, options) {
103
- this.checkGuard("read", path);
104
134
  const { api, resolvedPath } = this.resolve(path);
105
135
  return api.read(resolvedPath, options);
106
136
  }
107
137
  async write(path, content) {
108
- this.checkGuard("write", path);
109
138
  const { api, resolvedPath } = this.resolve(path);
110
139
  return api.write(resolvedPath, content);
111
140
  }
112
141
  async mkdir(path) {
113
- this.checkGuard("mkdir", path);
114
142
  const { api, resolvedPath } = this.resolve(path);
115
143
  return api.mkdir(resolvedPath);
116
144
  }
117
145
  async *list(path, options) {
118
- this.checkGuard("list", path);
119
146
  const normalized = normalizePath(path);
120
147
  const { api, resolvedPath } = this.resolve(path);
121
148
  const childMounts = this.childMountPrefixes(normalized);
@@ -180,13 +207,10 @@ var CompositeFilesApi = class {
180
207
  async remove(path) {
181
208
  const normalized = normalizePath(path);
182
209
  if (this.isMountPoint(normalized)) throw new Error(`Cannot remove mount point: ${normalized}`);
183
- this.checkGuard("remove", path);
184
210
  const { api, resolvedPath } = this.resolve(path);
185
211
  return api.remove(resolvedPath);
186
212
  }
187
213
  async move(source, target) {
188
- this.checkGuard("move", source);
189
- this.checkGuard("move", target);
190
214
  const src = this.resolve(source);
191
215
  const tgt = this.resolve(target);
192
216
  if (src.api === tgt.api) return src.api.move(src.resolvedPath, tgt.resolvedPath);
@@ -195,8 +219,6 @@ var CompositeFilesApi = class {
195
219
  return copied;
196
220
  }
197
221
  async copy(source, target) {
198
- this.checkGuard("copy", source);
199
- this.checkGuard("copy", target);
200
222
  const src = this.resolve(source);
201
223
  const tgt = this.resolve(target);
202
224
  if (src.api === tgt.api) return src.api.copy(src.resolvedPath, tgt.resolvedPath);
@@ -235,4 +257,402 @@ var CompositeFilesApi = class {
235
257
  }
236
258
  };
237
259
  //#endregion
238
- export { CompositeFilesApi };
260
+ //#region src/glob-to-regexp.ts
261
+ /**
262
+ * Compiles a glob pattern into a `RegExp`.
263
+ *
264
+ * @example
265
+ * ```ts
266
+ * globToRegExp("*.js"); // /^.*\.js$/
267
+ * globToRegExp("*.js", { globstar: true }); // /^([^/]*)\.js$/
268
+ * globToRegExp("/foo/**", { globstar: true }) // /^\/foo\/((?:[^/]*(?:\/|$))*)$/
269
+ * globToRegExp("foo{bar,baz}", { extended: true }); // /^foo(bar|baz)$/
270
+ * ```
271
+ */
272
+ function globToRegExp(glob, opts = {}) {
273
+ if (typeof glob !== "string") throw new TypeError("Expected a string");
274
+ const str = String(glob);
275
+ let reStr = "";
276
+ const extended = !!opts.extended;
277
+ const globstar = !!opts.globstar;
278
+ let inGroup = false;
279
+ const flags = typeof opts.flags === "string" ? opts.flags : "";
280
+ for (let i = 0; i < str.length; i++) {
281
+ const c = str[i];
282
+ switch (c) {
283
+ case "/":
284
+ case "$":
285
+ case "^":
286
+ case "+":
287
+ case ".":
288
+ case "(":
289
+ case ")":
290
+ case "=":
291
+ case "!":
292
+ case "|":
293
+ reStr += `\\${c}`;
294
+ break;
295
+ case "?":
296
+ reStr += extended ? "." : `\\${c}`;
297
+ break;
298
+ case "[":
299
+ case "]":
300
+ reStr += extended ? c : `\\${c}`;
301
+ break;
302
+ case "{":
303
+ if (extended) {
304
+ inGroup = true;
305
+ reStr += "(";
306
+ } else reStr += `\\${c}`;
307
+ break;
308
+ case "}":
309
+ if (extended) {
310
+ inGroup = false;
311
+ reStr += ")";
312
+ } else reStr += `\\${c}`;
313
+ break;
314
+ case ",":
315
+ if (inGroup) reStr += "|";
316
+ else reStr += `\\${c}`;
317
+ break;
318
+ case "*": {
319
+ const prevChar = str[i - 1];
320
+ let starCount = 1;
321
+ while (str[i + 1] === "*") {
322
+ starCount++;
323
+ i++;
324
+ }
325
+ const nextChar = str[i + 1];
326
+ if (!globstar) reStr += ".*";
327
+ else if (starCount > 1 && (prevChar === "/" || prevChar === void 0) && (nextChar === "/" || nextChar === void 0)) {
328
+ reStr += "((?:[^/]*(?:\\/|$))*)";
329
+ i++;
330
+ } else reStr += "([^/]*)";
331
+ break;
332
+ }
333
+ default: reStr += c;
334
+ }
335
+ }
336
+ if (!flags?.includes("g")) reStr = `^${reStr}$`;
337
+ return new RegExp(reStr, flags);
338
+ }
339
+ //#endregion
340
+ //#region src/filtered-files-api.ts
341
+ /**
342
+ * Builds a {@link PathFilter} that hides any path whose normalized form
343
+ * equals one of the provided prefixes or lives under `${prefix}/`.
344
+ *
345
+ * Prefixes are normalized through `normalizePath` (so `"foo"`, `"/foo"`, and
346
+ * `"/foo/"` are equivalent). Empty / root entries are dropped — they would
347
+ * otherwise hide every path.
348
+ *
349
+ * Matching is **boundary-aware**: the prefix `"/priv"` does not match the
350
+ * path `"/private"` because there is no `/` boundary between them.
351
+ *
352
+ * @param pathPrefixes Path prefixes whose contents (and the prefix itself)
353
+ * should be hidden. Pass none to hide nothing.
354
+ *
355
+ * @example
356
+ * ```ts
357
+ * const filter = newPathFilter("/.git", "/node_modules");
358
+ * filter("/src/index.ts"); // true
359
+ * filter("/.git"); // false
360
+ * filter("/.git/HEAD"); // false
361
+ * filter("/notgit"); // true (boundary-aware, no false match)
362
+ * ```
363
+ */
364
+ function newPathFilter(...pathPrefixes) {
365
+ const normalized = pathPrefixes.map((p) => normalizePath(p)).filter((p) => p !== "/");
366
+ return (path) => {
367
+ const target = normalizePath(path);
368
+ for (const prefix of normalized) {
369
+ if (target === prefix) return false;
370
+ if (target.startsWith(`${prefix}/`)) return false;
371
+ }
372
+ return true;
373
+ };
374
+ }
375
+ /**
376
+ * Builds a {@link PathFilter} that hides any path whose normalized form
377
+ * matches at least one of the provided regular expressions.
378
+ *
379
+ * The path is normalized through `normalizePath` before matching, so a
380
+ * regexp anchored on `^/` always sees a leading slash and never a trailing
381
+ * one. The regexp's `lastIndex` is irrelevant — the filter calls `test`
382
+ * via a fresh evaluation each time, but stateful (`/g`, `/y`) regexps
383
+ * still mutate `lastIndex` across calls; pass non-stateful regexps unless
384
+ * you know what you are doing.
385
+ *
386
+ * @param pathRegexps Regular expressions whose match means "hide this
387
+ * path". Pass none to hide nothing.
388
+ *
389
+ * @example
390
+ * ```ts
391
+ * // Hide every dotfile and every *.log file
392
+ * const filter = newRegexpPathFilter(/\/\.[^/]+$/, /\.log$/);
393
+ * filter("/src/index.ts"); // true
394
+ * filter("/.env"); // false (matches /\/\.[^/]+$/)
395
+ * filter("/build.log"); // false (matches /\.log$/)
396
+ * ```
397
+ */
398
+ function newRegexpPathFilter(...pathRegexps) {
399
+ return (path) => {
400
+ const target = normalizePath(path);
401
+ for (const regexp of pathRegexps) if (regexp.test(target)) return false;
402
+ return true;
403
+ };
404
+ }
405
+ /**
406
+ * Builds a {@link PathFilter} that hides any path whose normalized form
407
+ * matches at least one of the provided glob patterns.
408
+ *
409
+ * Each glob is compiled with `extended: true` and `globstar: true`, the
410
+ * standard "filesystem-style" mode:
411
+ *
412
+ * - `*` matches any number of characters within a single path segment
413
+ * (does **not** cross `/`).
414
+ * - `**` between slashes matches zero or more whole path segments.
415
+ * - `?` matches exactly one character.
416
+ * - `[abc]` / `[a-z]` matches a single character in the set / range.
417
+ * - `{a,b,c}` matches one of the alternatives.
418
+ *
419
+ * Because matching is done on the **normalized** path (which always starts
420
+ * with `/`), patterns that should match anywhere in the tree need a
421
+ * leading `**​/`, e.g. `**​/*.log` to hide every `.log` file at any depth.
422
+ *
423
+ * Gotcha: `/foo/**` matches descendants of `/foo` but **not** `/foo`
424
+ * itself, because the glob requires a `/` after `foo` before `**` can
425
+ * match. To hide both the directory and its contents, list both prefixes:
426
+ * `newGlobPathFilter("/foo", "/foo/**")`. {@link newPathFilter} doesn't
427
+ * have this problem and may be a better fit for prefix-only hiding.
428
+ *
429
+ * @param pathGlobs Glob patterns whose match means "hide this path". Pass
430
+ * none to hide nothing.
431
+ *
432
+ * @example
433
+ * ```ts
434
+ * const filter = newGlobPathFilter("**​/*.log", "/.git", "/.git/**");
435
+ * filter("/src/index.ts"); // true
436
+ * filter("/build.log"); // false (matches **​/*.log)
437
+ * filter("/.git"); // false (matches /.git)
438
+ * filter("/.git/HEAD"); // false (matches /.git/**)
439
+ * ```
440
+ */
441
+ function newGlobPathFilter(...pathGlobs) {
442
+ return newRegexpPathFilter(...pathGlobs.map((glob) => globToRegExp(glob, {
443
+ extended: true,
444
+ globstar: true
445
+ })));
446
+ }
447
+ /**
448
+ * `FilesApi` decorator that hides every path the supplied {@link PathFilter}
449
+ * rejects. Hidden paths are treated as if they do not exist:
450
+ *
451
+ * - `read` / `list` yield empty iterables.
452
+ * - `stats` returns `undefined`; `exists` returns `false`.
453
+ * - `remove` returns `false` (no error, nothing changed).
454
+ * - `move` / `copy` return `false` if either endpoint is hidden.
455
+ * - `write` / `mkdir` reject with an `Error` (since silently dropping a
456
+ * write would lose data).
457
+ * - `list` recursively skips entries whose paths are hidden, so iterating a
458
+ * visible parent never reveals a hidden child.
459
+ *
460
+ * Wrap any `FilesApi` to scope its visibility without changing the
461
+ * underlying storage; the wrapped instance still holds the data, it is just
462
+ * not reachable through this decorator.
463
+ *
464
+ * Pair with one of the built-in {@link PathFilter} factories
465
+ * ({@link newPathFilter}, {@link newRegexpPathFilter},
466
+ * {@link newGlobPathFilter}) or pass any predicate of shape
467
+ * `(path) => boolean | Promise<boolean>`.
468
+ *
469
+ * @example
470
+ * ```ts
471
+ * import {
472
+ * FilteredFilesApi,
473
+ * newGlobPathFilter,
474
+ * newPathFilter,
475
+ * newRegexpPathFilter,
476
+ * } from "@statewalker/webrun-files-composite";
477
+ *
478
+ * // Hide by path prefix
479
+ * const noVcs = new FilteredFilesApi(sourceFiles, newPathFilter("/.git", "/.cache"));
480
+ * await noVcs.exists("/.git"); // false
481
+ * await noVcs.write("/.git/x", data); // throws "Path is hidden"
482
+ *
483
+ * // Hide by regexp
484
+ * const noLogs = new FilteredFilesApi(sourceFiles, newRegexpPathFilter(/\.log$/));
485
+ *
486
+ * // Hide by glob (extended + globstar mode)
487
+ * const noJunk = new FilteredFilesApi(
488
+ * sourceFiles,
489
+ * newGlobPathFilter("**​/*.log", "/.git", "/.git/**"),
490
+ * );
491
+ * ```
492
+ */
493
+ var FilteredFilesApi = class {
494
+ source;
495
+ pathFilter;
496
+ /**
497
+ * @param source The underlying `FilesApi` whose paths will be selectively
498
+ * hidden. Operations always delegate to this instance; the decorator
499
+ * only adds the visibility check.
500
+ * @param pathFilter Predicate that decides per-call whether a normalized
501
+ * path is visible. See {@link PathFilter}.
502
+ */
503
+ constructor(source, pathFilter) {
504
+ this.source = source;
505
+ this.pathFilter = pathFilter;
506
+ }
507
+ async isHidden(path) {
508
+ return await this.pathFilter(normalizePath(path)) === false;
509
+ }
510
+ async *read(path, options) {
511
+ if (await this.isHidden(path)) return;
512
+ yield* this.source.read(path, options);
513
+ }
514
+ async write(path, content) {
515
+ if (await this.isHidden(path)) throw new Error(`Path is hidden: ${path}`);
516
+ await this.source.write(path, content);
517
+ }
518
+ async mkdir(path) {
519
+ if (await this.isHidden(path)) throw new Error(`Path is hidden: ${path}`);
520
+ await this.source.mkdir(path);
521
+ }
522
+ async *list(path, options) {
523
+ if (await this.isHidden(path)) return;
524
+ for await (const entry of this.source.list(path, options)) {
525
+ if (await this.isHidden(entry.path)) continue;
526
+ yield entry;
527
+ }
528
+ }
529
+ async stats(path) {
530
+ if (await this.isHidden(path)) return void 0;
531
+ return this.source.stats(path);
532
+ }
533
+ async exists(path) {
534
+ if (await this.isHidden(path)) return false;
535
+ return this.source.exists(path);
536
+ }
537
+ async remove(path) {
538
+ if (await this.isHidden(path)) return false;
539
+ return this.source.remove(path);
540
+ }
541
+ async move(source, target) {
542
+ if (await this.isHidden(source) || await this.isHidden(target)) return false;
543
+ return this.source.move(source, target);
544
+ }
545
+ async copy(source, target) {
546
+ if (await this.isHidden(source) || await this.isHidden(target)) return false;
547
+ return this.source.copy(source, target);
548
+ }
549
+ };
550
+ //#endregion
551
+ //#region src/guarded-files-api.ts
552
+ /**
553
+ * `FilesApi` decorator that runs every call through an ordered list of
554
+ * {@link FileGuard}s. A guard fires when its `operations` set intersects the
555
+ * effective operation(s) for the current call. The first guard whose
556
+ * `check` returns `false` aborts the call by throwing an `Error` with that
557
+ * guard's `message` (defaulting to `"Access denied"`) followed by the
558
+ * normalized path.
559
+ *
560
+ * Effective operations per call:
561
+ *
562
+ * | Method | Operations checked |
563
+ * | ------------- | --------------------------------------------------- |
564
+ * | `read` | `read` |
565
+ * | `write` | `write` |
566
+ * | `mkdir` | `mkdir` |
567
+ * | `remove` | `remove` |
568
+ * | `list` | `list` on the path AND on each directory entry |
569
+ * | `stats` | `list` (a stat reveals existence like a tiny list) |
570
+ * | `exists` | `read` (existence is a read of metadata) |
571
+ * | `move(s, t)` | `move`+`read` on source; `move`+`write` on target |
572
+ * | `copy(s, t)` | `copy`+`read` on source; `copy`+`write` on target |
573
+ *
574
+ * The expanded checks for `move`/`copy` mean a guard that blocks `read` on
575
+ * a path also prevents move/copy *from* that path, and a `write`-blocking
576
+ * guard prevents move/copy *to* it. Likewise, an `exists` call respects any
577
+ * read guard, and `stats` respects any list guard.
578
+ *
579
+ * @example
580
+ * ```ts
581
+ * const api = new GuardedFilesApi(source, [
582
+ * {
583
+ * operations: ["write", "remove", "move", "mkdir"],
584
+ * check: (p) => !p.startsWith("/.system/"),
585
+ * message: "system folder is read-only",
586
+ * },
587
+ * ]);
588
+ * await api.write("/.system/cfg", data); // throws "system folder is read-only: /.system/cfg"
589
+ * ```
590
+ */
591
+ var GuardedFilesApi = class {
592
+ source;
593
+ guards;
594
+ /**
595
+ * @param source The underlying `FilesApi` whose calls will be policed.
596
+ * Allowed operations delegate straight through.
597
+ * @param guards Ordered list of access policies. The wrapper takes a
598
+ * defensive copy, so mutating the array afterwards has no effect.
599
+ * An empty list disables every check (the wrapper becomes a passthrough).
600
+ */
601
+ constructor(source, guards) {
602
+ this.source = source;
603
+ this.guards = [...guards];
604
+ }
605
+ checkGuard(path, ...operations) {
606
+ const normalized = normalizePath(path);
607
+ for (const guard of this.guards) {
608
+ if (!operations.some((op) => guard.operations.includes(op))) continue;
609
+ if (!guard.check(normalized)) {
610
+ const msg = guard.message ?? "Access denied";
611
+ throw new Error(`${msg}: ${normalized}`);
612
+ }
613
+ }
614
+ }
615
+ read(path, options) {
616
+ this.checkGuard(path, "read");
617
+ return this.source.read(path, options);
618
+ }
619
+ async write(path, content) {
620
+ this.checkGuard(path, "write");
621
+ return this.source.write(path, content);
622
+ }
623
+ async mkdir(path) {
624
+ this.checkGuard(path, "mkdir");
625
+ return this.source.mkdir(path);
626
+ }
627
+ async *list(path, options) {
628
+ this.checkGuard(path, "list");
629
+ for await (const info of this.source.list(path, options)) {
630
+ if (info.kind === "directory") this.checkGuard(info.path, "list");
631
+ yield info;
632
+ }
633
+ }
634
+ stats(path) {
635
+ this.checkGuard(path, "list");
636
+ return this.source.stats(path);
637
+ }
638
+ exists(path) {
639
+ this.checkGuard(path, "read");
640
+ return this.source.exists(path);
641
+ }
642
+ async remove(path) {
643
+ this.checkGuard(path, "remove");
644
+ return this.source.remove(path);
645
+ }
646
+ async move(source, target) {
647
+ this.checkGuard(source, "move", "read");
648
+ this.checkGuard(target, "move", "write");
649
+ return this.source.move(source, target);
650
+ }
651
+ async copy(source, target) {
652
+ this.checkGuard(source, "copy", "read");
653
+ this.checkGuard(target, "copy", "write");
654
+ return this.source.copy(source, target);
655
+ }
656
+ };
657
+ //#endregion
658
+ export { CompositeFilesApi, FilteredFilesApi, GuardedFilesApi, globToRegExp, newGlobPathFilter, newPathFilter, newRegexpPathFilter };