@better-fs-tools/node 0.1.0 → 0.3.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
@@ -1,6 +1,6 @@
1
1
  # @better-fs-tools/node
2
2
 
3
- The Node filesystem for Better FS Tools, a SHA-256 digest, `createNodeReadTool()`, the zero-config local read tool, and `createNodeFsTools()`, which adds `edit`, `write`, and `apply_patch` over the same filesystem and read store, and `bash` when you ask for it. It works on Node 24 or later, and on Bun.
3
+ The Node backends for Better FS Tools: the local filesystem, a SHA-256 digest on `node:crypto`, and a local command runner. Pass `nodeFileSystem()` as `fs` to any tool or bundle, such as `createReadTool()` or `createFsTools()`, and `nodeCommandRunner()` as the bash `runner`. It works on Node 24 or later, and on Bun.
4
4
 
5
5
  ## Install
6
6
 
@@ -13,15 +13,20 @@ The package has no peers. It needs Node 24 or later (`engines.node` is `>=24`),
13
13
  ## Example
14
14
 
15
15
  ```ts
16
- import { createNodeReadTool, nodeFileSystem } from "@better-fs-tools/node";
17
- import { textOf } from "@better-fs-tools/read";
18
-
19
- // Zero config: rooted at process.cwd(), with SHA-256 observations.
20
- const read = createNodeReadTool();
16
+ import { nodeDigest, nodeFileSystem } from "@better-fs-tools/node";
17
+ import { createReadTool, textOf } from "@better-fs-tools/read";
18
+
19
+ // The local filesystem, rooted at process.cwd(). nodeDigest() is optional: it
20
+ // gives the same values as the default sha256Digest(), faster, on node:crypto.
21
+ const cwd = process.cwd();
22
+ const read = createReadTool({
23
+ fs: nodeFileSystem({ cwd, allowedRoots: [cwd] }),
24
+ digest: nodeDigest(),
25
+ });
21
26
  console.log(textOf(await read({ path: "package.json", limit: 1 }))); // "1|{" and a continue note
22
27
 
23
28
  // Your own roots and policy.
24
- export const docsOnly = createNodeReadTool({
29
+ export const docsOnly = createReadTool({
25
30
  fs: nodeFileSystem({
26
31
  cwd: "/srv/app",
27
32
  allowedRoots: ["/srv/app/docs"],
@@ -31,16 +36,19 @@ export const docsOnly = createNodeReadTool({
31
36
  });
32
37
  ```
33
38
 
34
- All four tools, with one read store, so `edit` and `write` need a read first:
39
+ All four tools over one `nodeFileSystem`, with `createFsTools()`. The read store makes `edit` and `write` need a read first. The store and `apply_patch` are opt-in:
35
40
 
36
41
  ```ts
37
- import { createNodeFsTools } from "@better-fs-tools/node";
38
- import { textOf } from "@better-fs-tools/read";
39
- import { protectPaths } from "@better-fs-tools/write";
42
+ import { nodeFileSystem } from "@better-fs-tools/node";
43
+ import { memoryStore, textOf } from "@better-fs-tools/read";
44
+ import { createFsTools, protectPaths } from "@better-fs-tools/write";
40
45
 
41
46
  // read, edit, write, and apply_patch over one nodeFileSystem rooted at
42
47
  // process.cwd(), with one read store, one SHA-256 digest, and one lock manager.
43
- const tools = createNodeFsTools({
48
+ // The read store and apply_patch are opt-in.
49
+ const tools = createFsTools({
50
+ fs: nodeFileSystem({ allowedRoots: [process.cwd()] }),
51
+ state: memoryStore(),
44
52
  edit: { authorize: protectPaths() },
45
53
  write: { authorize: protectPaths() },
46
54
  applyPatch: { authorize: protectPaths() },
@@ -62,29 +70,25 @@ export async function afterShell(path: string): Promise<boolean> {
62
70
 
63
71
  ## Contents
64
72
 
65
- | Export | Use |
66
- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
67
- | `createNodeReadTool(options?)` | `createReadTool()` from `@better-fs-tools/read` with Node defaults. `fs` defaults to `nodeFileSystem` rooted at `process.cwd()`. `digest` defaults to `nodeDigest()`. Pass `digest: null` to turn observations off. Every other option goes to the core. |
68
- | `createNodeFsTools(options?)` | `createFsTools()` from `@better-fs-tools/write` over one `nodeFileSystem`, with `nodeDigest()`: `read`, `edit`, `write`, and `apply_patch` share one `memoryStore({ clock })`, one digest, one `memoryLocks()`, and one clock. Options: `cwd`, `allowedRoots` (default `[cwd]`), `denyRoots`, `symlinks`, `hardLinks`, `newFileMode`, `newDirectoryMode`, `state` (`null` turns read-before-write off), `digest`, `locks`, `clock`, per-tool options under `read`, `edit`, `write`, and `applyPatch`, and `bash`. Bash is off unless `bash` is `true` or an options object. The result also has `bash` (`null` when off), `fs`, `state`, `digest`, `locks`, `clock`, and `invalidate(path, call?)`, which returns an `InvalidateOutcome`. The Node filesystem is fixed, so `call` is not needed. An unknown option key, or `fs`, `state`, `digest`, `locks`, or `clock` inside a per-tool object (`digest` or `clock` inside `bash`), throws `TypeError` |
69
- | `createNodeEditTool(deps?)`, `createNodeWriteTool(deps?)`, `createNodeApplyPatchTool(deps?)` | One write tool each. `fs` defaults to `nodeFileSystem` rooted at `process.cwd()`, `digest` to `nodeDigest()`. `state` stays `null`, so every update carries a `read-before-write-off` note |
70
- | `createNodeBashTool(deps?)` | The local `bash` tool. See [Bash tool](#bash-tool) |
71
- | `nodeCommandRunner(options?)` | The command runner that `createNodeBashTool()` uses: `bash -c` in its own process group. POSIX only |
72
- | `nodeFileSystem(options)` | A `WritableFileSystem` over Node file descriptors |
73
- | `nodeDigest()` | SHA-256 over `node:crypto`. Values look like `sha256:<hex>`, the same as `sha256Digest()` from `@better-fs-tools/read`. |
73
+ | Export | Use |
74
+ | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
75
+ | `nodeFileSystem(options)` | A `WritableFileSystem` over Node file descriptors |
76
+ | `nodeCommandRunner(options?)` | A bash `CommandRunner`: `bash -c` in its own process group. POSIX only. See [Bash tool](#bash-tool) |
77
+ | `nodeDigest()` | SHA-256 over `node:crypto`. Values look like `sha256:<hex>`, the same as the default `sha256Digest()` from `@better-fs-tools/read`, so records made with one are valid for the other. Faster |
74
78
 
75
79
  `nodeFileSystem` options. The first six are the shared `FileSystemRootOptions` from `@better-fs-tools/fs`. The filesystem also exposes the resolved `cwd`, `allowedRoots`, `denyRoots`, `symlinks`, and `identity`:
76
80
 
77
- | Option | Default | Meaning |
78
- | ------------------ | ----------------------- | ------------------------------------------------------------------------------------------------------ |
79
- | `allowedRoots` | required | At least one root. A path outside every root gives `OUTSIDE_ALLOWED_ROOTS`. |
80
- | `cwd` | `process.cwd()` | Base for relative paths. A relative `cwd` resolves against `process.cwd()` |
81
- | `denyRoots` | none | Refused as `DANGEROUS_PATH`, in addition to `/dev`, `/proc`, and `/sys` |
82
- | `symlinks` | `"follow-within-roots"` | `"reject"` refuses every symlink |
83
- | `identity` | `"required"` | The only value: Node always reports device and inode |
84
- | `id` | `"node"` | Appears in `result.file.backend` |
85
- | `hardLinks` | `"refuse"` | A replace of a file with more than one hard link. `"in-place"` writes through the link, not atomically |
86
- | `newFileMode` | `0o666` less the umask | Mode of a new file. A mode you set is exact: the umask does not apply to it |
87
- | `newDirectoryMode` | `0o777` less the umask | Mode of a directory that `createParents` makes. A mode you set is exact |
81
+ | Option | Default | Meaning |
82
+ | ------------------ | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
83
+ | `allowedRoots` | required | At least one root. A path outside every root gives `OUTSIDE_ALLOWED_ROOTS`. |
84
+ | `cwd` | `process.cwd()` | Base for relative paths. A relative `cwd` resolves against `process.cwd()` |
85
+ | `denyRoots` | none | Refused as `DANGEROUS_PATH`, in addition to `/dev`, `/proc`, and `/sys` |
86
+ | `symlinks` | `"follow-within-roots"` | `"reject"` refuses every symlink |
87
+ | `identity` | `"required"` | The only value: Node always reports device and inode |
88
+ | `id` | `"node"` | Appears in `result.file.backend` |
89
+ | `hardLinks` | `"in-place"` | A replace of a file with more than one hard link. `"in-place"` writes through the link, not atomically. `"refuse"` fails with reason `denied`. A file with one link is always replaced by temp file and rename |
90
+ | `newFileMode` | `0o666` less the umask | Mode of a new file. A mode you set is exact: the umask does not apply to it |
91
+ | `newDirectoryMode` | `0o777` less the umask | Mode of a directory that `createParents` makes. A mode you set is exact |
88
92
 
89
93
  ## How it opens a file
90
94
 
@@ -96,7 +100,7 @@ export async function afterShell(path: string): Promise<boolean> {
96
100
 
97
101
  A write goes to a `0o600` temp file next to the target. The bytes are written and synced, and the file gets the old mode or the new-file mode. Publishing takes an in-process lock for the real path and checks the precondition against a fresh `lstat`. A create is published with `link()`, so a concurrent creator makes it fail with `exists`. A replace is published with `rename()`. Any failure removes the temp file and the directories the write created. The version token is the read identity: device, inode, size, and both change times. `EROFS` gives `read-only`, and `ENOSPC` and `EDQUOT` give `no-space`.
98
102
 
99
- `writeCapabilities` is `{ atomic: true, compareAndSwap: true, preserveMode: true }`, and `stage()` and `remove()` exist. Some of this holds with limits:
103
+ `writeCapabilities` is `{ compareAndSwap: true }`. A replace is atomic and keeps the mode, and `stage()` and `remove()` exist. Some of this holds with limits:
100
104
 
101
105
  - `compareAndSwap` holds inside one process only. The lock orders writes inside one process. Another process can still change the file between the final check and the rename, and that change is then lost.
102
106
  - A replace keeps the permission bits only. The owner, the group, extended attributes, and ACLs are not kept, because `rename()` publishes a new file owned by the writing user.
@@ -105,19 +109,25 @@ A write goes to a `0o600` temp file next to the target. The bytes are written an
105
109
 
106
110
  ## Bash tool
107
111
 
108
- `createNodeBashTool()` is the zero-config local `bash` tool from [`@better-fs-tools/shell`](https://www.npmjs.com/package/@better-fs-tools/shell). It uses `nodeCommandRunner()`: `bash -c` in its own process group, stdin on `/dev/null`, SIGTERM to the group on a stop, and SIGKILL after the grace time. The environment is `process.env`, read on each call, with the pager and colour defaults over it. `createNodeFsTools()` starts no process unless you ask: `bash: true`, or a `bash` options object, adds the same tool as `bash`, in the same cwd, with the bundle's digest and clock. Its `env` also defaults to `process.env`, since a host that turns on a local bash in a Node bundle asks for a local shell. Pass `env` to narrow it, for example `shellEnv({ PATH: process.env.PATH })`. With your own `bash.runner`, an explicit `cwd` still applies: it becomes the bash `cwd` dependency. `bash.cwd` wins over both. `nodeCommandRunner({ cwd })` resolves a relative `cwd` against `process.cwd()`, as `nodeFileSystem` does. So does the `cwd` dependency of `createNodeBashTool({ cwd })` and `bash.cwd`; the portable core keeps its absolute rule.
112
+ `nodeCommandRunner()` runs `bash -c` in its own process group, with stdin on `/dev/null`. A stop sends SIGTERM to the group, and SIGKILL after the grace time. `nodeCommandRunner({ cwd })` resolves a relative `cwd` against `process.cwd()`, as `nodeFileSystem` does. Give it to `createBashTool()` from [`@better-fs-tools/shell`](https://www.npmjs.com/package/@better-fs-tools/shell), or to the `bash` options of a bundle, with an `env`. `shellEnv(() => process.env)` passes `process.env`, read on each call, with the pager and colour defaults over it. Pass a smaller `env` to narrow it, for example `shellEnv({ PATH: process.env.PATH })`. In a bundle, the bash tool gets the digest and clock of the set.
109
113
 
110
114
  ```ts
111
- import { createNodeFsTools, nodeCommandRunner } from "@better-fs-tools/node";
112
- import type { NodeFsToolsWithBash } from "@better-fs-tools/node";
113
-
114
- // bash is created only because `bash` is set. The hook makes the next edit of
115
- // package.json need a read first, since a command may have changed it.
116
- let tools: NodeFsToolsWithBash | undefined;
117
- tools = createNodeFsTools({
118
- cwd: "/srv/project",
115
+ import { nodeCommandRunner, nodeFileSystem } from "@better-fs-tools/node";
116
+ import { memoryStore } from "@better-fs-tools/read";
117
+ import { shellEnv } from "@better-fs-tools/shell";
118
+ import { createFsTools } from "@better-fs-tools/write";
119
+ import type { FsToolsWithBash } from "@better-fs-tools/write";
120
+
121
+ // bash is created only because `bash` is set. With a read store, the hook makes
122
+ // the next edit of package.json need a read first, since a command may have
123
+ // changed it.
124
+ let tools: FsToolsWithBash | undefined;
125
+ tools = createFsTools({
126
+ fs: nodeFileSystem({ cwd: "/srv/project", allowedRoots: ["/srv/project"] }),
127
+ state: memoryStore(),
119
128
  bash: {
120
129
  runner: nodeCommandRunner({ cwd: "/srv/project", shell: "/bin/bash" }),
130
+ env: shellEnv(() => process.env),
121
131
  afterRun: [
122
132
  {
123
133
  id: "invalidate-package-json",
@@ -146,4 +156,4 @@ The allowed roots do not limit what a command touches. The runner is POSIX only.
146
156
 
147
157
  - `docs/hosts.md` in [`@better-fs-tools/write`](https://www.npmjs.com/package/@better-fs-tools/write): the defaults of every host and bundle, and what each backend can do
148
158
  - [`@better-fs-tools/read`](https://www.npmjs.com/package/@better-fs-tools/read): every read option
149
- - [`@better-fs-tools/pi`](https://www.npmjs.com/package/@better-fs-tools/pi): the Pi tool, which builds on `nodeFileSystem`
159
+ - [`@better-fs-tools/pi`](https://www.npmjs.com/package/@better-fs-tools/pi): `piCwdFileSystem()` and `piCwdCommandRunner()` on its `./node` subpath build on these backends
@@ -26,8 +26,8 @@ export function nodeFileSystem(options) {
26
26
  denyRoots: Object.freeze([...config.denyRoots]),
27
27
  symlinks: config.symlinks,
28
28
  identity: "required",
29
- capabilities: Object.freeze({ streaming: true, identity: true }),
30
- writeCapabilities: Object.freeze({ atomic: true, compareAndSwap: true, preserveMode: true }),
29
+ capabilities: Object.freeze({ identity: true }),
30
+ writeCapabilities: Object.freeze({ compareAndSwap: true }),
31
31
  paths: posixPaths,
32
32
  stat: (path, callOptions = {}) => nodeStat(context, path, callOptions),
33
33
  write: writes.write,
package/dist/index.d.ts CHANGED
@@ -1,12 +1,5 @@
1
1
  export { nodeCommandRunner } from "./command-runner.ts";
2
2
  export type { NodeCommandRunnerOptions } from "./command-runner.ts";
3
- export { createNodeBashTool } from "./create-node-bash-tool.ts";
4
- export { createNodeFsTools } from "./create-node-fs-tools.ts";
5
- export type { CreateNodeFsToolsOptions, NodeFsTools, NodeFsToolsBashOptions, NodeFsToolsWithBash, } from "./create-node-fs-tools.ts";
6
- export { createNodeReadTool } from "./create-node-read-tool.ts";
7
- export type { CreateNodeReadToolOptions } from "./create-node-read-tool.ts";
8
- export { createNodeApplyPatchTool, createNodeEditTool, createNodeWriteTool, } from "./create-node-write-tools.ts";
9
- export type { CreateNodeApplyPatchToolOptions, CreateNodeEditToolOptions, CreateNodeWriteToolOptions, } from "./create-node-write-tools.ts";
10
3
  export { nodeDigest } from "./digest.ts";
11
4
  export { nodeFileSystem } from "./filesystem.ts";
12
5
  export type { NodeFileSystem } from "./filesystem.ts";
package/dist/index.js CHANGED
@@ -1,7 +1,3 @@
1
1
  export { nodeCommandRunner } from "./command-runner.js";
2
- export { createNodeBashTool } from "./create-node-bash-tool.js";
3
- export { createNodeFsTools } from "./create-node-fs-tools.js";
4
- export { createNodeReadTool } from "./create-node-read-tool.js";
5
- export { createNodeApplyPatchTool, createNodeEditTool, createNodeWriteTool, } from "./create-node-write-tools.js";
6
2
  export { nodeDigest } from "./digest.js";
7
3
  export { nodeFileSystem } from "./filesystem.js";
package/dist/policy.d.ts CHANGED
@@ -8,7 +8,11 @@ import type { FileSystemError, FileSystemRootOptions, SymlinkPolicy } from "@bet
8
8
  * defaults to "node".
9
9
  */
10
10
  export interface NodeFileSystemOptions extends FileSystemRootOptions<SymlinkPolicy, "required"> {
11
- /** How to replace a file with more than one hard link. Default "refuse". "in-place" truncates and writes, which is not atomic. */
11
+ /**
12
+ * How to replace a file with more than one hard link. Default "in-place":
13
+ * truncate and write through the link, which is not atomic. "refuse" fails
14
+ * with denied. A file with one link is always replaced by temp file and rename.
15
+ */
12
16
  readonly hardLinks?: "refuse" | "in-place";
13
17
  /**
14
18
  * Mode of a new file, exactly: the umask does not apply to a mode you set.
package/dist/policy.js CHANGED
@@ -70,7 +70,7 @@ function resolveOptions(options) {
70
70
  if (symlinks !== "follow-within-roots" && symlinks !== "reject") {
71
71
  throw new TypeError('symlinks must be "follow-within-roots" or "reject"');
72
72
  }
73
- const hardLinks = options.hardLinks ?? "refuse";
73
+ const hardLinks = options.hardLinks ?? "in-place";
74
74
  if (hardLinks !== "refuse" && hardLinks !== "in-place") {
75
75
  throw new TypeError('hardLinks must be "refuse" or "in-place"');
76
76
  }
package/dist/write.js CHANGED
@@ -132,7 +132,7 @@ export function nodeWrites(context, io = NODE_WRITE_IO) {
132
132
  await syncDirectory(path.dirname(target.resolvedPath));
133
133
  const stats = await temp.handle.stat({ bigint: true }).catch(() => null);
134
134
  await temp.handle.close().catch(() => { });
135
- return { ok: true, file: mutated(target, stats, createdDirectories, true) };
135
+ return { ok: true, file: mutated(target, stats, createdDirectories) };
136
136
  });
137
137
  settled = true;
138
138
  if (!outcome.ok)
@@ -182,7 +182,7 @@ export function nodeWrites(context, io = NODE_WRITE_IO) {
182
182
  await handle.writeFile(bytes);
183
183
  await handle.sync();
184
184
  const after = await handle.stat({ bigint: true });
185
- return { ok: true, file: mutated(target, after, [], false) };
185
+ return { ok: true, file: mutated(target, after, []) };
186
186
  }
187
187
  catch (error) {
188
188
  return fail(mapMutationError(error, "publish", target));
@@ -265,7 +265,7 @@ export function nodeWrites(context, io = NODE_WRITE_IO) {
265
265
  return fail(mapMutationError(error, "remove", target));
266
266
  }
267
267
  await syncDirectory(path.dirname(target.resolvedPath));
268
- return { ok: true, file: mutated(target, null, [], true) };
268
+ return { ok: true, file: mutated(target, null, []) };
269
269
  });
270
270
  };
271
271
  return { write, stage, remove };
@@ -281,7 +281,7 @@ function preconditionConflict(current, options) {
281
281
  }
282
282
  return null;
283
283
  }
284
- function mutated(target, stats, createdDirectories, atomic) {
284
+ function mutated(target, stats, createdDirectories) {
285
285
  const version = stats === null ? null : nodeIdentity(stats);
286
286
  return {
287
287
  ...target,
@@ -289,7 +289,6 @@ function mutated(target, stats, createdDirectories, atomic) {
289
289
  identity: version,
290
290
  size: stats === null ? null : Number(stats.size),
291
291
  createdDirectories,
292
- atomic,
293
292
  };
294
293
  }
295
294
  const TEMP_NAME_MAX_CHARS = 48;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@better-fs-tools/node",
3
- "version": "0.1.0",
4
- "description": "The Node filesystem, a SHA-256 digest, a bash runner, and the zero-config read, edit, write, apply_patch, and bash tools for Node and Bun.",
3
+ "version": "0.3.0",
4
+ "description": "The Node filesystem, a SHA-256 digest on node:crypto, and a bash runner for Node and Bun.",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -29,10 +29,10 @@
29
29
  "access": "public"
30
30
  },
31
31
  "dependencies": {
32
- "@better-fs-tools/fs": "^0.1.0",
33
- "@better-fs-tools/read": "^0.1.0",
34
- "@better-fs-tools/shell": "^0.1.0",
35
- "@better-fs-tools/write": "^0.1.0"
32
+ "@better-fs-tools/fs": "^0.3.0",
33
+ "@better-fs-tools/read": "^0.3.0",
34
+ "@better-fs-tools/shell": "^0.3.0",
35
+ "@better-fs-tools/write": "^0.3.0"
36
36
  },
37
37
  "engines": {
38
38
  "node": ">=24"
@@ -1,10 +0,0 @@
1
- import type { BashTool, ShellToolDeps } from "@better-fs-tools/shell";
2
- /**
3
- * Creates a bash tool that runs commands on the local machine. `runner`
4
- * defaults to nodeCommandRunner() at process.cwd(). `env` defaults to
5
- * process.env, read on each call, with defaultShellEnv over it. A relative
6
- * `cwd` resolves against process.cwd(). There is no authorizer, hook, or
7
- * spill unless you pass one.
8
- */
9
- export declare function createNodeBashTool<THost = undefined>(deps?: Partial<ShellToolDeps<THost>>): BashTool<THost>;
10
- export declare function withNodeShellDefaults<THost>(deps: Partial<ShellToolDeps<THost>>, cwd?: string): ShellToolDeps<THost>;
@@ -1,31 +0,0 @@
1
- import path from "node:path";
2
- import { createBashTool, shellEnv } from "@better-fs-tools/shell";
3
- import { nodeCommandRunner } from "./command-runner.js";
4
- /**
5
- * Creates a bash tool that runs commands on the local machine. `runner`
6
- * defaults to nodeCommandRunner() at process.cwd(). `env` defaults to
7
- * process.env, read on each call, with defaultShellEnv over it. A relative
8
- * `cwd` resolves against process.cwd(). There is no authorizer, hook, or
9
- * spill unless you pass one.
10
- */
11
- export function createNodeBashTool(deps = {}) {
12
- if (deps === null || typeof deps !== "object" || Array.isArray(deps)) {
13
- throw new TypeError("bash tool dependencies must be an object");
14
- }
15
- return createBashTool(withNodeShellDefaults(deps));
16
- }
17
- export function withNodeShellDefaults(deps, cwd) {
18
- const given = deps.cwd;
19
- return {
20
- ...deps,
21
- ...(isValidRelativePath(given) ? { cwd: path.resolve(given) } : {}),
22
- runner: deps.runner ?? nodeCommandRunner(cwd === undefined ? {} : { cwd }),
23
- env: deps.env ?? shellEnv(() => process.env),
24
- };
25
- }
26
- function isValidRelativePath(given) {
27
- return (typeof given === "string" &&
28
- given.trim() !== "" &&
29
- !given.includes("\0") &&
30
- !path.isAbsolute(given));
31
- }
@@ -1,75 +0,0 @@
1
- import type { SymlinkPolicy } from "@better-fs-tools/fs";
2
- import type { Clock, Digest, ReadStateStore, ReadTool, ReadToolDeps, ToolCallContext } from "@better-fs-tools/read";
3
- import type { ApplyPatchTool, ApplyPatchToolDeps, EditTool, EditToolDeps, FsToolsSharedKey, InvalidateOutcome, LockManager, WriteTool, WriteToolDeps } from "@better-fs-tools/write";
4
- import type { BashTool, ShellToolDeps } from "@better-fs-tools/shell";
5
- import type { NodeFileSystem } from "./filesystem.ts";
6
- /**
7
- * Options for the bundle's bash tool, all optional. `runner` defaults to
8
- * nodeCommandRunner({ cwd }), and `env` to shellEnv(() => process.env).
9
- */
10
- export type NodeFsToolsBashOptions<THost = undefined> = Omit<Partial<ShellToolDeps<THost>>, "digest" | "clock">;
11
- export interface CreateNodeFsToolsOptions<THost = undefined> {
12
- /** Default process.cwd(). */
13
- readonly cwd?: string;
14
- /** Default [cwd]. They do not limit a bash command. */
15
- readonly allowedRoots?: readonly string[];
16
- readonly denyRoots?: readonly string[];
17
- readonly symlinks?: SymlinkPolicy;
18
- readonly hardLinks?: "refuse" | "in-place";
19
- /** Mode of a new file, exactly. Default 0o666 less the process umask. */
20
- readonly newFileMode?: number;
21
- /** Mode of a directory that createParents makes, exactly. Default 0o777 less the umask. */
22
- readonly newDirectoryMode?: number;
23
- /** Default a memory store on the bundle clock. null turns read-before-write off. */
24
- readonly state?: ReadStateStore | null;
25
- /** Default nodeDigest(). */
26
- readonly digest?: Digest;
27
- /** Default memoryLocks(). */
28
- readonly locks?: LockManager;
29
- /** Default () => new Date(). */
30
- readonly clock?: Clock;
31
- readonly read?: Omit<Partial<ReadToolDeps<THost>>, FsToolsSharedKey>;
32
- readonly edit?: Omit<Partial<EditToolDeps<THost>>, FsToolsSharedKey>;
33
- readonly write?: Omit<Partial<WriteToolDeps<THost>>, FsToolsSharedKey>;
34
- readonly applyPatch?: Omit<Partial<ApplyPatchToolDeps<THost>>, FsToolsSharedKey>;
35
- /**
36
- * `true` or an options object adds a bash tool. Off by default. The runner
37
- * defaults to nodeCommandRunner({ cwd }), and env to
38
- * shellEnv(() => process.env). With your own runner, commands still run in
39
- * an explicit top-level cwd. bash.cwd wins over both.
40
- */
41
- readonly bash?: boolean | NodeFsToolsBashOptions<THost>;
42
- }
43
- export interface NodeFsTools<THost = undefined> {
44
- readonly read: ReadTool<THost>;
45
- readonly edit: EditTool<THost>;
46
- readonly write: WriteTool<THost>;
47
- readonly applyPatch: ApplyPatchTool<THost>;
48
- /** null unless options.bash is set. Runs in cwd. It does not share the read state: see invalidate. */
49
- readonly bash: BashTool<THost> | null;
50
- readonly fs: NodeFileSystem;
51
- readonly state: ReadStateStore | null;
52
- readonly digest: Digest;
53
- readonly locks: LockManager;
54
- readonly clock: Clock;
55
- /**
56
- * Forgets the read record for a path, so the next edit needs a fresh read.
57
- * With state null it reports recorded: false. `call` is ignored.
58
- */
59
- invalidate(path: string, call?: ToolCallContext<THost>): Promise<InvalidateOutcome>;
60
- }
61
- /** The result when options.bash is true or an object: bash is there. */
62
- export interface NodeFsToolsWithBash<THost = undefined> extends NodeFsTools<THost> {
63
- readonly bash: BashTool<THost>;
64
- }
65
- /**
66
- * Creates read, edit, write, and apply_patch tools over one local filesystem.
67
- * They share one read state store, digest, lock manager, and clock. With
68
- * `bash`, adds a bash tool in the same cwd. The allowed roots do not limit
69
- * what a bash command touches. To make the next edit after a command need a
70
- * read, call invalidate(path) from a bash afterRun hook.
71
- */
72
- export declare function createNodeFsTools<THost = undefined>(options: CreateNodeFsToolsOptions<THost> & {
73
- readonly bash: true | NodeFsToolsBashOptions<THost>;
74
- }): NodeFsToolsWithBash<THost>;
75
- export declare function createNodeFsTools<THost = undefined>(options?: CreateNodeFsToolsOptions<THost>): NodeFsTools<THost>;
@@ -1,112 +0,0 @@
1
- import path from "node:path";
2
- import { createFsTools } from "@better-fs-tools/write";
3
- import { withNodeShellDefaults } from "./create-node-bash-tool.js";
4
- import { nodeDigest } from "./digest.js";
5
- import { nodeFileSystem } from "./filesystem.js";
6
- const KNOWN_OPTIONS = new Set([
7
- "cwd",
8
- "allowedRoots",
9
- "denyRoots",
10
- "symlinks",
11
- "hardLinks",
12
- "newFileMode",
13
- "newDirectoryMode",
14
- "state",
15
- "digest",
16
- "locks",
17
- "clock",
18
- "read",
19
- "edit",
20
- "write",
21
- "applyPatch",
22
- "bash",
23
- ]);
24
- const BUNDLE_SHARED_KEYS_BY_TOOL = {
25
- read: ["fs", "state", "digest", "clock"],
26
- edit: ["fs", "state", "digest", "locks", "clock"],
27
- write: ["fs", "state", "digest", "locks", "clock"],
28
- applyPatch: ["fs", "state", "digest", "locks", "clock"],
29
- bash: ["digest", "clock"],
30
- };
31
- export function createNodeFsTools(options = {}) {
32
- checkOptions(options);
33
- const cwd = path.resolve(options.cwd ?? process.cwd());
34
- const fs = nodeFileSystem({
35
- cwd,
36
- allowedRoots: options.allowedRoots ?? [cwd],
37
- ...pickDefined(options, [
38
- "denyRoots",
39
- "symlinks",
40
- "hardLinks",
41
- "newFileMode",
42
- "newDirectoryMode",
43
- ]),
44
- });
45
- const bash = options.bash === true ? {} : options.bash;
46
- const tools = createFsTools({
47
- fs,
48
- digest: options.digest ?? nodeDigest(),
49
- ...pickDefined(options, ["state", "locks", "clock", "read", "edit", "write", "applyPatch"]),
50
- ...(bash === undefined || bash === false ? {} : { bash: bashDeps(bash, options.cwd, cwd) }),
51
- });
52
- return Object.freeze({
53
- read: tools.read,
54
- edit: tools.edit,
55
- write: tools.write,
56
- applyPatch: tools.applyPatch,
57
- bash: tools.bash,
58
- fs,
59
- state: tools.state,
60
- digest: tools.digest,
61
- locks: tools.locks,
62
- clock: tools.clock,
63
- invalidate: (target) => tools.invalidate(target),
64
- });
65
- }
66
- function checkOptions(options) {
67
- if (options === null || typeof options !== "object" || Array.isArray(options)) {
68
- throw new TypeError("createNodeFsTools options must be an object");
69
- }
70
- for (const key of Object.keys(options)) {
71
- if (!KNOWN_OPTIONS.has(key))
72
- throw new TypeError(`Unknown createNodeFsTools option: ${key}`);
73
- }
74
- const state = options.state;
75
- if (state !== undefined && state !== null && !isReadStateStore(state)) {
76
- throw new TypeError(`createNodeFsTools state must be a read state store or null: a bundle takes one store, not a per-call factory`);
77
- }
78
- for (const [tool, keys] of Object.entries(BUNDLE_SHARED_KEYS_BY_TOOL)) {
79
- const part = options[tool];
80
- if (part === undefined || (tool === "bash" && typeof part === "boolean"))
81
- continue;
82
- if (part === null || typeof part !== "object" || Array.isArray(part)) {
83
- throw new TypeError(`createNodeFsTools ${tool} options must be an object`);
84
- }
85
- for (const key of keys) {
86
- if (Object.hasOwn(part, key)) {
87
- throw new TypeError(`createNodeFsTools ${tool} options cannot set ${key}: set it once at the top level`);
88
- }
89
- }
90
- }
91
- }
92
- function pickDefined(options, keys) {
93
- const picked = {};
94
- for (const key of keys) {
95
- if (options[key] !== undefined)
96
- picked[key] = options[key];
97
- }
98
- return picked;
99
- }
100
- function bashDeps(bash, explicitCwd, cwd) {
101
- const deps = withNodeShellDefaults(bash, cwd);
102
- const customRunnerNeedsExplicitCwd = bash.runner !== undefined && explicitCwd !== undefined && bash.cwd === undefined;
103
- if (!customRunnerNeedsExplicitCwd)
104
- return deps;
105
- return { ...deps, cwd };
106
- }
107
- function isReadStateStore(value) {
108
- if (value === null || typeof value !== "object")
109
- return false;
110
- const store = value;
111
- return ["get", "put", "delete"].every((key) => typeof store[key] === "function");
112
- }
@@ -1,9 +0,0 @@
1
- import type { ReadTool, ReadToolDeps, StateNeedsDigestOrDefault } from "@better-fs-tools/read";
2
- /** Options for createNodeReadTool, all optional. A `state` needs a digest that is not null. */
3
- export type CreateNodeReadToolOptions<THost = undefined> = Partial<ReadToolDeps<THost>> & StateNeedsDigestOrDefault;
4
- /**
5
- * Creates a read tool for local files. `fs` defaults to nodeFileSystem rooted
6
- * at process.cwd(). `digest` defaults to nodeDigest(); pass `digest: null` to
7
- * turn observations off.
8
- */
9
- export declare function createNodeReadTool<THost = undefined>(deps?: CreateNodeReadToolOptions<THost>): ReadTool<THost>;
@@ -1,22 +0,0 @@
1
- import { createReadTool } from "@better-fs-tools/read";
2
- import { nodeDigest } from "./digest.js";
3
- import { nodeFileSystem } from "./filesystem.js";
4
- /**
5
- * Creates a read tool for local files. `fs` defaults to nodeFileSystem rooted
6
- * at process.cwd(). `digest` defaults to nodeDigest(); pass `digest: null` to
7
- * turn observations off.
8
- */
9
- export function createNodeReadTool(deps = {}) {
10
- if (deps === null || typeof deps !== "object" || Array.isArray(deps)) {
11
- throw new TypeError("read tool dependencies must be an object");
12
- }
13
- const fs = deps.fs ?? defaultFileSystem();
14
- // digest: null narrows the options to the branch without a state.
15
- if (deps.digest === null)
16
- return createReadTool({ ...deps, fs, digest: null });
17
- return createReadTool({ ...deps, fs, digest: deps.digest ?? nodeDigest() });
18
- }
19
- function defaultFileSystem() {
20
- const cwd = process.cwd();
21
- return nodeFileSystem({ cwd, allowedRoots: [cwd] });
22
- }
@@ -1,19 +0,0 @@
1
- import type { ApplyPatchTool, ApplyPatchToolDeps, EditTool, EditToolDeps, WriteTool, WriteToolDeps } from "@better-fs-tools/write";
2
- import type { StateNeedsDigestOrDefault } from "@better-fs-tools/read";
3
- /** Options for createNodeEditTool, all optional. A `state` needs a digest that is not null. */
4
- export type CreateNodeEditToolOptions<THost = undefined> = Partial<EditToolDeps<THost>> & StateNeedsDigestOrDefault;
5
- /** As CreateNodeEditToolOptions, for write. */
6
- export type CreateNodeWriteToolOptions<THost = undefined> = Partial<WriteToolDeps<THost>> & StateNeedsDigestOrDefault;
7
- /** As CreateNodeEditToolOptions, for apply_patch. */
8
- export type CreateNodeApplyPatchToolOptions<THost = undefined> = Partial<ApplyPatchToolDeps<THost>> & StateNeedsDigestOrDefault;
9
- /**
10
- * Creates an edit tool for local files. `fs` defaults to nodeFileSystem rooted
11
- * at process.cwd(). `digest` defaults to nodeDigest(); pass `digest: null` to
12
- * turn it off. Read-before-write is off unless you pass a `state`; use
13
- * createNodeFsTools() for a store shared with read.
14
- */
15
- export declare function createNodeEditTool<THost = undefined>(deps?: CreateNodeEditToolOptions<THost>): EditTool<THost>;
16
- /** Creates a write tool for local files, with the same defaults as createNodeEditTool. */
17
- export declare function createNodeWriteTool<THost = undefined>(deps?: CreateNodeWriteToolOptions<THost>): WriteTool<THost>;
18
- /** Creates an apply_patch tool for local files, with the same defaults as createNodeEditTool. */
19
- export declare function createNodeApplyPatchTool<THost = undefined>(deps?: CreateNodeApplyPatchToolOptions<THost>): ApplyPatchTool<THost>;
@@ -1,42 +0,0 @@
1
- import { createApplyPatchTool, createEditTool, createWriteTool } from "@better-fs-tools/write";
2
- import { nodeDigest } from "./digest.js";
3
- import { nodeFileSystem } from "./filesystem.js";
4
- /**
5
- * Creates an edit tool for local files. `fs` defaults to nodeFileSystem rooted
6
- * at process.cwd(). `digest` defaults to nodeDigest(); pass `digest: null` to
7
- * turn it off. Read-before-write is off unless you pass a `state`; use
8
- * createNodeFsTools() for a store shared with read.
9
- */
10
- export function createNodeEditTool(deps = {}) {
11
- checkDeps(deps, "edit");
12
- const fs = deps.fs ?? defaultFileSystem();
13
- // digest: null narrows the options to the branch without a state.
14
- if (deps.digest === null)
15
- return createEditTool({ ...deps, fs, digest: null });
16
- return createEditTool({ ...deps, fs, digest: deps.digest ?? nodeDigest() });
17
- }
18
- /** Creates a write tool for local files, with the same defaults as createNodeEditTool. */
19
- export function createNodeWriteTool(deps = {}) {
20
- checkDeps(deps, "write");
21
- const fs = deps.fs ?? defaultFileSystem();
22
- if (deps.digest === null)
23
- return createWriteTool({ ...deps, fs, digest: null });
24
- return createWriteTool({ ...deps, fs, digest: deps.digest ?? nodeDigest() });
25
- }
26
- /** Creates an apply_patch tool for local files, with the same defaults as createNodeEditTool. */
27
- export function createNodeApplyPatchTool(deps = {}) {
28
- checkDeps(deps, "apply_patch");
29
- const fs = deps.fs ?? defaultFileSystem();
30
- if (deps.digest === null)
31
- return createApplyPatchTool({ ...deps, fs, digest: null });
32
- return createApplyPatchTool({ ...deps, fs, digest: deps.digest ?? nodeDigest() });
33
- }
34
- function checkDeps(deps, tool) {
35
- if (deps === null || typeof deps !== "object" || Array.isArray(deps)) {
36
- throw new TypeError(`${tool} tool dependencies must be an object`);
37
- }
38
- }
39
- function defaultFileSystem() {
40
- const cwd = process.cwd();
41
- return nodeFileSystem({ cwd, allowedRoots: [cwd] });
42
- }