@better-fs-tools/cloudflare-shell 0.0.0-tegami-trusted-publish-setup → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Gareth Andrew
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,6 +1,72 @@
1
- # Placeholder package
2
-
3
- This empty package was published by [Tegami](https://tegami.fuma-nama.dev) to configure npm trusted publishing.
4
-
5
- The real package contents will be published via CI with OIDC.
6
-
1
+ # @better-fs-tools/cloudflare-shell
2
+
3
+ A `WritableFileSystem` over a [Cloudflare Shell](https://www.npmjs.com/package/@cloudflare/shell) `Workspace`, for the Better Read tool and the `edit`, `write`, and `apply_patch` tools in a Worker or a Cloudflare Agent.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install @better-fs-tools/cloudflare-shell @better-fs-tools/read @better-fs-tools/write
9
+ ```
10
+
11
+ The package has no peers. It declares the Workspace methods that it uses as a structural type, so `@cloudflare/shell`'s `Workspace` fits without an import. It imports no `node:` module.
12
+
13
+ ## Example
14
+
15
+ With the AI SDK adapter (`npm install @better-fs-tools/ai-sdk ai`):
16
+
17
+ ```ts
18
+ import type { Workspace } from "@cloudflare/shell";
19
+ import { createAiSdkReadTool } from "@better-fs-tools/ai-sdk";
20
+ import { cloudflareShellFileSystem } from "@better-fs-tools/cloudflare-shell";
21
+
22
+ export function workspaceReadTool(workspace: Workspace) {
23
+ return createAiSdkReadTool({
24
+ fs: cloudflareShellFileSystem(workspace, { allowedRoots: ["/workspace"] }),
25
+ });
26
+ }
27
+ ```
28
+
29
+ With the write tools. `createAiSdkFsTools()` gives the read tool and the write tools one digest and one lock manager, and one read store when you pass `state`. Its default digest, `sha256Digest()` from `@better-fs-tools/read`, is SHA-256 in plain JavaScript, so it runs in a Worker:
30
+
31
+ ```ts
32
+ import type { Workspace } from "@cloudflare/shell";
33
+ import { createAiSdkFsTools } from "@better-fs-tools/ai-sdk";
34
+ import { cloudflareShellFileSystem } from "@better-fs-tools/cloudflare-shell";
35
+
36
+ // read, edit, and write with one sha256Digest() and one lock manager. Nothing
37
+ // here needs Node, so it runs in a Worker.
38
+ export function workspaceTools(workspace: Workspace) {
39
+ const fs = cloudflareShellFileSystem(workspace, { allowedRoots: ["/workspace"] });
40
+ return createAiSdkFsTools({ fs }).tools;
41
+ }
42
+ ```
43
+
44
+ ## What the filesystem does
45
+
46
+ - `cloudflareShellFileSystem(workspace, options)` takes the shared `FileSystemRootOptions` and `maxBufferedBytes` from `@better-fs-tools/fs`: `allowedRoots` (required), `denyRoots`, `cwd`, `id`, `symlinks`, and `identity`. It refuses every path outside the allowed roots, or inside a deny root, before it calls the Workspace. A deny root gives `dangerous-path`, as in every adapter.
47
+ - `cwd` must be absolute and defaults to the first allowed root. Relative paths and relative roots resolve against it. Display paths are relative to `cwd`, and absolute outside it. `id` defaults to `"cloudflare-shell"`.
48
+ - `symlinks` can only be `"reject"` and `identity` only `"none"`. It walks each path with `lstat` from `/`, so a symlink above the root, a symlinked root, parent, or file is refused before any byte is read.
49
+ - The filesystem exposes the resolved `cwd`, `allowedRoots`, `denyRoots`, `symlinks`, `identity`, and `maxBufferedBytes`.
50
+ - Reads are buffered: the Workspace returns whole files. `maxBufferedBytes` defaults to 16 MiB, as in every buffering adapter. When you use converters, set it at or above `maxConvertBytes` and `maxMediaBytes`.
51
+ - Because reads are buffered inside `open()`, the whole file has left the Workspace before the read tool's `authorize` runs. The core still passes no byte to a classifier, a converter, or the model until `authorize` allows it. If a denied read must not reach the Workspace, deny it in the adapter with `denyRoots` or `allowedRoots`.
52
+ - `verify()` compares size and modification time. A same-size edit within the same millisecond is not detected.
53
+ - `list()` lists directories, so suggestions and `directoryListing()` work. Opening a directory gives a `not-a-file` error with `kind: "directory"`.
54
+
55
+ ## How it writes
56
+
57
+ - `stat()`, `write()`, and `remove()` use `lstat`, `writeFileBytes`, `mkdir`, and `rm`. They check the roots and refuse every symlink on the path before any Workspace write, as `open()` does. `writeFileBytes` would create missing parents and follow a link by itself, so the adapter checks both first.
58
+ - `writeFileBytes`, `mkdir`, and `rm` are optional in `CloudflareShellWorkspaceLike`. They are checked when a write runs, not when the filesystem is built. A read-only Workspace wrapper backs the read tool, and a write to it gives `unsupported`, which the tools report as `UNSUPPORTED_BACKEND`.
59
+ - `writeCapabilities` is `{ compareAndSwap: false }`. A large file spills to R2 in several steps, so a reader can see a partial file. Shell has no version check, so the adapter checks the precondition with a fresh `lstat` just before the write. Shell has no modes.
60
+ - There is no `stage()`: Shell's `mv` removes the destination first. `apply_patch` writes each file in turn, and undoes them on a failure.
61
+ - The version is the size and `updatedAt`. Shell stores whole seconds, so two same-size writes in one second keep the version. The write tools also compare the content hash of what the model read, so a change after the read is still `STALE`. Between the adapter's last check and the write, it is not seen.
62
+ - A replace passes the file's mime type back, since Shell would reset it. A new file gets Shell's default, `application/octet-stream`.
63
+ - A read or a write over `maxBufferedBytes` gives `too-large` with the `limit` and the `size`, since the adapter could not read the file back. The tools report `TOO_LARGE`. The effective limit is the smaller of `maxBufferedBytes` and the tool's own limits.
64
+ - Shell's errors carry their POSIX code in the message. The adapter reads the code and drops the message: `EEXIST` gives `exists`, `EROFS` gives `read-only`, and `ENOSPC` and `EDQUOT` give `no-space`.
65
+
66
+ ## Links
67
+
68
+ - `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
69
+ - [`@better-fs-tools/read`](https://www.npmjs.com/package/@better-fs-tools/read): every read option
70
+ - [`@better-fs-tools/write`](https://www.npmjs.com/package/@better-fs-tools/write): the write tools
71
+ - [`@better-fs-tools/ai-sdk`](https://www.npmjs.com/package/@better-fs-tools/ai-sdk): the AI SDK tools
72
+ - [`@better-fs-tools/fs`](https://www.npmjs.com/package/@better-fs-tools/fs): the filesystem contract
@@ -0,0 +1,58 @@
1
+ import type { BufferedFileSystemOptions, FileSystemRootOptions, FileSystemRootSettings, ListOptions, ListOutcome, MutateOptions, MutationOutcome, WritableFileSystem } from "@better-fs-tools/fs";
2
+ /**
3
+ * An entry as a Shell Workspace describes it. A structural subset of Shell's
4
+ * `FileInfo` and `FileStat`.
5
+ */
6
+ export interface CloudflareShellFileInfo {
7
+ path: string;
8
+ type: "file" | "directory" | "symlink";
9
+ size: number;
10
+ /** Epoch milliseconds. Shell's `updatedAt`. */
11
+ updatedAt: number;
12
+ name?: string;
13
+ mimeType?: string;
14
+ target?: string;
15
+ }
16
+ /**
17
+ * The Workspace methods this adapter uses. `@cloudflare/shell`'s `Workspace`
18
+ * and its `WorkspaceFsLike` structural type both satisfy it.
19
+ *
20
+ * The write methods are optional: a Workspace without them still serves
21
+ * reads, and a write reports `unsupported`.
22
+ */
23
+ export interface CloudflareShellWorkspaceLike {
24
+ stat(path: string): Promise<CloudflareShellFileInfo | null>;
25
+ lstat(path: string): Promise<CloudflareShellFileInfo | null>;
26
+ readFileBytes(path: string): Promise<Uint8Array | null>;
27
+ readDir(dir: string, opts?: {
28
+ limit?: number;
29
+ offset?: number;
30
+ }): Promise<CloudflareShellFileInfo[]>;
31
+ writeFileBytes?(path: string, data: Uint8Array, mimeType?: string): Promise<void>;
32
+ mkdir?(path: string, opts?: {
33
+ recursive?: boolean;
34
+ }): Promise<void>;
35
+ rm?(path: string, opts?: {
36
+ recursive?: boolean;
37
+ force?: boolean;
38
+ }): Promise<void>;
39
+ }
40
+ /**
41
+ * The shared root options, with Workspace paths. `allowedRoots` holds
42
+ * absolute paths, or paths relative to `cwd`. `cwd` must be absolute and
43
+ * defaults to the first allowed root. `symlinks` can only be `"reject"` and
44
+ * `identity` only `"none"`. `id` defaults to `"cloudflare-shell"`.
45
+ * `maxBufferedBytes` defaults to 16 MiB.
46
+ */
47
+ export interface CloudflareShellFileSystemOptions extends FileSystemRootOptions<"reject", "none">, BufferedFileSystemOptions {
48
+ }
49
+ /**
50
+ * A writable filesystem over a Cloudflare Shell Workspace. Writes are not
51
+ * atomic and do not keep a file mode. There is no compare-and-swap and no
52
+ * `stage()`.
53
+ */
54
+ export interface CloudflareShellFileSystem extends WritableFileSystem, FileSystemRootSettings<"reject", "none"> {
55
+ readonly maxBufferedBytes: number;
56
+ list(path: string, options: ListOptions): Promise<ListOutcome>;
57
+ remove(path: string, options: MutateOptions): Promise<MutationOutcome>;
58
+ }
File without changes
@@ -0,0 +1,9 @@
1
+ import type { CloudflareShellFileSystem, CloudflareShellFileSystemOptions, CloudflareShellWorkspaceLike } from "./contract.ts";
2
+ export type { CloudflareShellFileInfo, CloudflareShellFileSystem, CloudflareShellFileSystemOptions, CloudflareShellWorkspaceLike, } from "./contract.ts";
3
+ /**
4
+ * Adapt a Cloudflare Shell Workspace to the filesystem contract.
5
+ *
6
+ * Paths outside the allowed roots, inside a deny root, or through a symbolic
7
+ * link are refused.
8
+ */
9
+ export declare function cloudflareShellFileSystem(workspace: CloudflareShellWorkspaceLike, options: CloudflareShellFileSystemOptions): CloudflareShellFileSystem;
package/dist/index.js ADDED
@@ -0,0 +1,207 @@
1
+ import { DEFAULT_MAX_BUFFERED_BYTES, posixPaths, resolvePosix } from "@better-fs-tools/fs";
2
+ import { authorize, call, displayPath, inspect, invalid, notAFile, pathsFromSlashToTarget, refuse, resolveRoots, toFileSystemError, validateStat, validateWorkspace, } from "./policy.js";
3
+ import { SHELL_WRITE_CAPABILITIES, shellVersion, shellWrites } from "./write.js";
4
+ /**
5
+ * Adapt a Cloudflare Shell Workspace to the filesystem contract.
6
+ *
7
+ * Paths outside the allowed roots, inside a deny root, or through a symbolic
8
+ * link are refused.
9
+ */
10
+ export function cloudflareShellFileSystem(workspace, options) {
11
+ validateWorkspace(workspace);
12
+ if (options === null || typeof options !== "object" || Array.isArray(options)) {
13
+ throw new TypeError("cloudflareShellFileSystem options must be an object");
14
+ }
15
+ const roots = resolveRoots(options);
16
+ const { cwd } = roots;
17
+ const maxBufferedBytes = options.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED_BYTES;
18
+ if (!Number.isSafeInteger(maxBufferedBytes) || maxBufferedBytes <= 0) {
19
+ throw new TypeError("maxBufferedBytes must be a positive safe integer");
20
+ }
21
+ const id = options.id ?? "cloudflare-shell";
22
+ if (typeof id !== "string" || id === "")
23
+ throw new TypeError("id must be a non-empty string");
24
+ const refuseSymlinksAlongPath = async (target) => {
25
+ for (const component of pathsFromSlashToTarget(target)) {
26
+ const stat = await inspect(workspace, "lstat", component);
27
+ if (stat === null) {
28
+ throw refuse({
29
+ reason: "not-found",
30
+ ...(component === target ? {} : { detail: "a path component does not exist" }),
31
+ });
32
+ }
33
+ if (stat.type === "symlink") {
34
+ throw refuse({
35
+ reason: "denied",
36
+ detail: component === target
37
+ ? "the path is a symbolic link and this adapter refuses symlinks"
38
+ : "a path component is a symbolic link and this adapter refuses symlinks",
39
+ });
40
+ }
41
+ if (component !== target && stat.type !== "directory") {
42
+ throw refuse({ reason: "not-found", detail: "a path component is not a directory" });
43
+ }
44
+ if (component === target)
45
+ return stat;
46
+ }
47
+ throw refuse(notAFile("directory", cwd, target));
48
+ };
49
+ return Object.freeze({
50
+ id,
51
+ capabilities: Object.freeze({ identity: false }),
52
+ paths: posixPaths,
53
+ cwd,
54
+ allowedRoots: roots.allowedRoots,
55
+ denyRoots: roots.denyRoots,
56
+ symlinks: "reject",
57
+ identity: "none",
58
+ maxBufferedBytes,
59
+ writeCapabilities: SHELL_WRITE_CAPABILITIES,
60
+ ...shellWrites(workspace, roots, maxBufferedBytes),
61
+ async open(requested, callOptions = {}) {
62
+ const signal = callOptions.signal;
63
+ if (signal?.aborted)
64
+ return { ok: false, error: { reason: "aborted" } };
65
+ try {
66
+ const { target } = authorize(roots, requested);
67
+ await refuseSymlinksAlongPath(target);
68
+ const stat = await inspect(workspace, "stat", target);
69
+ if (stat === null)
70
+ throw refuse({ reason: "not-found" });
71
+ if (stat.type !== "file") {
72
+ throw refuse(notAFile(stat.type === "directory" ? "directory" : "other", cwd, target));
73
+ }
74
+ if (stat.size > maxBufferedBytes) {
75
+ throw refuse({
76
+ reason: "too-large",
77
+ limit: maxBufferedBytes,
78
+ size: stat.size,
79
+ detail: `the object exceeds the ${maxBufferedBytes}-byte buffered ceiling`,
80
+ });
81
+ }
82
+ /* Shell's readFileBytes takes no signal, so abort is checked on both sides. */
83
+ if (signal?.aborted)
84
+ throw refuse({ reason: "aborted" });
85
+ const bytes = await call(workspace.readFileBytes(target), "readFileBytes");
86
+ if (signal?.aborted)
87
+ throw refuse({ reason: "aborted" });
88
+ if (bytes === null) {
89
+ throw refuse({
90
+ reason: "not-found",
91
+ detail: "the entry disappeared before its buffered read",
92
+ });
93
+ }
94
+ if (!(bytes instanceof Uint8Array)) {
95
+ throw invalid("readFileBytes returned neither bytes nor null", "readFileBytes");
96
+ }
97
+ if (bytes.byteLength > maxBufferedBytes) {
98
+ throw refuse({
99
+ reason: "too-large",
100
+ limit: maxBufferedBytes,
101
+ size: bytes.byteLength,
102
+ detail: `the backend returned more than the ${maxBufferedBytes}-byte buffered ceiling`,
103
+ });
104
+ }
105
+ return { ok: true, file: shellOpenFile(workspace, cwd, target, stat, bytes) };
106
+ }
107
+ catch (error) {
108
+ return { ok: false, error: toFileSystemError(error) };
109
+ }
110
+ },
111
+ async list(requested, listOptions) {
112
+ if (listOptions.signal?.aborted)
113
+ return { ok: false, error: { reason: "aborted" } };
114
+ const limit = listOptions.limit;
115
+ if (!Number.isSafeInteger(limit) || limit <= 0) {
116
+ return {
117
+ ok: false,
118
+ error: { reason: "io", detail: "list limit must be a positive safe integer" },
119
+ };
120
+ }
121
+ try {
122
+ const { target } = authorize(roots, requested);
123
+ const stat = target === "/" ? null : await refuseSymlinksAlongPath(target);
124
+ if (stat !== null && stat.type !== "directory") {
125
+ throw refuse({ reason: "not-found", detail: "not a directory" });
126
+ }
127
+ const oneMoreThanLimit = limit + 1;
128
+ const listed = await call(workspace.readDir(target, { limit: oneMoreThanLimit, offset: 0 }), "readDir");
129
+ if (!Array.isArray(listed))
130
+ throw invalid("readDir returned a non-array", "readDir");
131
+ const entries = [];
132
+ for (const value of listed.slice(0, limit)) {
133
+ const entry = validateStat(value, "readDir");
134
+ if (entry === null)
135
+ throw invalid("readDir returned a null entry", "readDir");
136
+ const path = resolvePosix("/", entry.path);
137
+ if (posixPaths.dirname(path) !== target) {
138
+ throw invalid("readDir returned an entry outside the listed directory", "readDir");
139
+ }
140
+ entries.push({
141
+ name: posixPaths.basename(path),
142
+ type: entry.type === "symlink" ? "other" : entry.type,
143
+ });
144
+ }
145
+ return { ok: true, entries, truncated: listed.length > limit };
146
+ }
147
+ catch (error) {
148
+ return { ok: false, error: toFileSystemError(error) };
149
+ }
150
+ },
151
+ });
152
+ }
153
+ function shellOpenFile(workspace, cwd, target, stat, bytes) {
154
+ let consumed = false;
155
+ let closed = false;
156
+ return {
157
+ info: {
158
+ resolvedPath: target,
159
+ displayPath: displayPath(cwd, target),
160
+ size: stat.size,
161
+ mtimeMs: stat.updatedAt,
162
+ identity: null,
163
+ mimeType: stat.mimeType ?? null,
164
+ version: shellVersion(stat),
165
+ },
166
+ bytes() {
167
+ if (consumed)
168
+ throw new TypeError("shell workspace byte source is single-use");
169
+ consumed = true;
170
+ let sent = closed || bytes.byteLength === 0;
171
+ return {
172
+ [Symbol.asyncIterator]() {
173
+ return {
174
+ async next() {
175
+ if (sent || closed)
176
+ return { done: true, value: undefined };
177
+ sent = true;
178
+ return { done: false, value: bytes };
179
+ },
180
+ async return() {
181
+ sent = true;
182
+ return { done: true, value: undefined };
183
+ },
184
+ };
185
+ },
186
+ };
187
+ },
188
+ async verify() {
189
+ try {
190
+ const current = await inspect(workspace, "lstat", target);
191
+ if (current === null)
192
+ return { ok: true, changed: true };
193
+ const changed = current.type !== stat.type ||
194
+ current.size !== stat.size ||
195
+ current.updatedAt !== stat.updatedAt;
196
+ return { ok: true, changed };
197
+ }
198
+ catch (error) {
199
+ return { ok: false, error: toFileSystemError(error) };
200
+ }
201
+ },
202
+ async close() {
203
+ closed = true;
204
+ consumed = true;
205
+ },
206
+ };
207
+ }
@@ -0,0 +1,28 @@
1
+ import type { FileSystemError, FileSystemRootOptions, NotAFileError } from "@better-fs-tools/fs";
2
+ import type { CloudflareShellFileInfo, CloudflareShellWorkspaceLike } from "./contract.ts";
3
+ export interface Roots {
4
+ readonly cwd: string;
5
+ readonly allowedRoots: readonly string[];
6
+ readonly denyRoots: readonly string[];
7
+ }
8
+ export declare function resolveRoots(options: FileSystemRootOptions<"reject", "none">): Roots;
9
+ export declare function pathsFromSlashToTarget(target: string): string[];
10
+ export declare function authorize(roots: Roots, requested: unknown): {
11
+ readonly root: string;
12
+ readonly target: string;
13
+ };
14
+ export declare function displayPath(cwd: string, target: string): string;
15
+ export declare function notAFile(kind: NotAFileError["kind"], cwd: string, target: string): NotAFileError;
16
+ export declare function inspect(workspace: CloudflareShellWorkspaceLike, method: "stat" | "lstat", path: string): Promise<CloudflareShellFileInfo | null>;
17
+ export declare function validateStat(value: unknown, phase: string): CloudflareShellFileInfo | null;
18
+ export declare function call<T>(pending: Promise<T> | T, phase: string): Promise<T>;
19
+ export declare function mapBackendError(error: unknown, phase: string): FileSystemError;
20
+ export declare function boundedCode(error: unknown): string;
21
+ export declare class AdapterRefusal extends Error {
22
+ readonly error: FileSystemError;
23
+ constructor(error: FileSystemError);
24
+ }
25
+ export declare function refuse(error: FileSystemError): AdapterRefusal;
26
+ export declare function invalid(detail: string, phase: string): AdapterRefusal;
27
+ export declare function toFileSystemError(error: unknown): FileSystemError;
28
+ export declare function validateWorkspace(workspace: CloudflareShellWorkspaceLike): void;
package/dist/policy.js ADDED
@@ -0,0 +1,195 @@
1
+ import { containsPosix, posixPaths, resolvePosix } from "@better-fs-tools/fs";
2
+ export function resolveRoots(options) {
3
+ const base = options.cwd === undefined ? "/" : absolutePath(options.cwd, "cwd");
4
+ const allowed = options.allowedRoots;
5
+ if (!Array.isArray(allowed) || allowed.length === 0) {
6
+ throw new TypeError("allowedRoots must be a non-empty array");
7
+ }
8
+ const allowedRoots = Object.freeze(allowed.map((root) => configuredRoot(base, root)));
9
+ if (options.denyRoots !== undefined && !Array.isArray(options.denyRoots)) {
10
+ throw new TypeError("denyRoots must be an array");
11
+ }
12
+ const denyRoots = Object.freeze((options.denyRoots ?? []).map((root) => configuredRoot(base, root)));
13
+ if (options.symlinks !== undefined && options.symlinks !== "reject") {
14
+ throw new TypeError('symlinks must be "reject": this adapter refuses every symbolic link');
15
+ }
16
+ if (options.identity !== undefined && options.identity !== "none") {
17
+ throw new TypeError('identity must be "none": a Workspace row has no stable identity');
18
+ }
19
+ return { cwd: options.cwd === undefined ? allowedRoots[0] : base, allowedRoots, denyRoots };
20
+ }
21
+ function absolutePath(value, label) {
22
+ if (typeof value !== "string" || !value.startsWith("/") || value.includes("\0")) {
23
+ throw new TypeError(`${label} must be an absolute POSIX path without NUL`);
24
+ }
25
+ return resolvePosix("/", value);
26
+ }
27
+ function configuredRoot(base, value) {
28
+ if (typeof value !== "string" || value === "" || value.includes("\0")) {
29
+ throw new TypeError("filesystem roots must be non-empty POSIX paths without NUL");
30
+ }
31
+ return resolvePosix(base, value);
32
+ }
33
+ export function pathsFromSlashToTarget(target) {
34
+ const found = [];
35
+ let current = "";
36
+ for (const segment of target.split("/")) {
37
+ if (segment === "")
38
+ continue;
39
+ current = `${current}/${segment}`;
40
+ found.push(current);
41
+ }
42
+ return found;
43
+ }
44
+ export function authorize(roots, requested) {
45
+ if (typeof requested !== "string" || requested === "") {
46
+ throw refuse({ reason: "io", detail: "the requested path must be a non-empty string" });
47
+ }
48
+ if (requested.includes("\0")) {
49
+ throw refuse({ reason: "dangerous-path", detail: "the path contains NUL" });
50
+ }
51
+ const target = resolvePosix(roots.cwd, requested);
52
+ const denied = roots.denyRoots.find((root) => containsPosix(root, target));
53
+ if (denied !== undefined)
54
+ throw refuse({ reason: "dangerous-path", detail: denied });
55
+ const innermostRoot = innermostAllowedRoot(roots, target);
56
+ if (innermostRoot === null)
57
+ throw refuse({ reason: "outside-allowed-roots" });
58
+ return { root: innermostRoot, target };
59
+ }
60
+ function innermostAllowedRoot(roots, target) {
61
+ let root = null;
62
+ for (const candidate of roots.allowedRoots) {
63
+ if (containsPosix(candidate, target) && (root === null || candidate.length > root.length)) {
64
+ root = candidate;
65
+ }
66
+ }
67
+ return root;
68
+ }
69
+ export function displayPath(cwd, target) {
70
+ if (!containsPosix(cwd, target))
71
+ return target;
72
+ if (target === cwd)
73
+ return posixPaths.basename(target) || "/";
74
+ return target.slice(cwd === "/" ? 1 : cwd.length + 1);
75
+ }
76
+ export function notAFile(kind, cwd, target) {
77
+ return {
78
+ reason: "not-a-file",
79
+ kind,
80
+ target: { resolvedPath: target, displayPath: displayPath(cwd, target) },
81
+ };
82
+ }
83
+ export async function inspect(workspace, method, path) {
84
+ const value = await call(workspace[method](path), method);
85
+ const stat = validateStat(value, method);
86
+ if (stat !== null && resolvePosix("/", stat.path) !== path) {
87
+ throw invalid(`${method} returned an entry for a different path`, method);
88
+ }
89
+ return stat;
90
+ }
91
+ export function validateStat(value, phase) {
92
+ if (value === null)
93
+ return null;
94
+ if (value === undefined || typeof value !== "object" || Array.isArray(value)) {
95
+ throw invalid(`${phase} returned neither an entry nor null`, phase);
96
+ }
97
+ const entry = value;
98
+ if (typeof entry.path !== "string" || !entry.path.startsWith("/") || entry.path.includes("\0")) {
99
+ throw invalid(`${phase} returned an entry without an absolute path`, phase);
100
+ }
101
+ if (entry.type !== "file" && entry.type !== "directory" && entry.type !== "symlink") {
102
+ throw invalid(`${phase} returned an unknown entry type`, phase);
103
+ }
104
+ if (!Number.isSafeInteger(entry.size) || entry.size < 0) {
105
+ throw invalid(`${phase} returned an unusable size`, phase);
106
+ }
107
+ if (typeof entry.updatedAt !== "number" || !Number.isFinite(entry.updatedAt)) {
108
+ throw invalid(`${phase} returned an unusable modification time`, phase);
109
+ }
110
+ if (entry.mimeType !== undefined && typeof entry.mimeType !== "string") {
111
+ throw invalid(`${phase} returned an unusable mime type`, phase);
112
+ }
113
+ const mimeType = typeof entry.mimeType === "string" && entry.mimeType !== "" ? entry.mimeType : undefined;
114
+ return {
115
+ path: entry.path,
116
+ type: entry.type,
117
+ size: entry.size,
118
+ updatedAt: entry.updatedAt,
119
+ ...(mimeType === undefined ? {} : { mimeType }),
120
+ };
121
+ }
122
+ export async function call(pending, phase) {
123
+ try {
124
+ return await pending;
125
+ }
126
+ catch (error) {
127
+ if (error instanceof AdapterRefusal)
128
+ throw error;
129
+ throw refuse(mapBackendError(error, phase));
130
+ }
131
+ }
132
+ export function mapBackendError(error, phase) {
133
+ const code = boundedCode(error);
134
+ const cause = { code, phase };
135
+ if (code === "ABORT_ERR")
136
+ return { reason: "aborted", cause };
137
+ if (code === "ENOENT" || code === "ENOTDIR")
138
+ return { reason: "not-found", cause };
139
+ if (code === "EISDIR")
140
+ return { reason: "not-a-file", kind: "directory", target: null, cause };
141
+ if (code === "EACCES" || code === "EPERM")
142
+ return { reason: "permission-denied", cause };
143
+ if (code === "ELOOP")
144
+ return { reason: "denied", detail: "too many symbolic links", cause };
145
+ return { reason: "io", detail: phase, cause };
146
+ }
147
+ export function boundedCode(error) {
148
+ if (error !== null && typeof error === "object" && "code" in error) {
149
+ const code = error.code;
150
+ if (typeof code === "string" && /^[A-Za-z0-9_.-]{1,40}$/u.test(code))
151
+ return code;
152
+ }
153
+ if (error instanceof Error && error.name === "AbortError")
154
+ return "ABORT_ERR";
155
+ return "UNKNOWN";
156
+ }
157
+ export class AdapterRefusal extends Error {
158
+ error;
159
+ constructor(error) {
160
+ super(error.reason);
161
+ this.error = error;
162
+ this.name = "AdapterRefusal";
163
+ }
164
+ }
165
+ export function refuse(error) {
166
+ return new AdapterRefusal(error);
167
+ }
168
+ export function invalid(detail, phase) {
169
+ return new AdapterRefusal({
170
+ reason: "io",
171
+ detail,
172
+ cause: { code: "INVALID_BACKEND_RESULT", phase },
173
+ });
174
+ }
175
+ export function toFileSystemError(error) {
176
+ if (error instanceof AdapterRefusal)
177
+ return error.error;
178
+ return {
179
+ reason: "io",
180
+ detail: "the Shell Workspace adapter failed",
181
+ cause: { code: boundedCode(error) },
182
+ };
183
+ }
184
+ export function validateWorkspace(workspace) {
185
+ if (workspace === null || typeof workspace !== "object" || Array.isArray(workspace)) {
186
+ throw new TypeError("cloudflareShellFileSystem needs a Shell Workspace object");
187
+ }
188
+ const methods = ["stat", "lstat", "readFileBytes", "readDir"];
189
+ for (const method of methods) {
190
+ if (typeof workspace[method] !== "function") {
191
+ /* Security: without `lstat` a symlink could not be refused before `stat` follows it. */
192
+ throw new TypeError(`the Shell Workspace must implement ${method}()`);
193
+ }
194
+ }
195
+ }
@@ -0,0 +1,11 @@
1
+ import type { MutateOptions, MutationOutcome, OpenOptions, StatOutcome, WriteCapabilities, WriteOptions } from "@better-fs-tools/fs";
2
+ import type { CloudflareShellFileInfo, CloudflareShellWorkspaceLike } from "./contract.ts";
3
+ import type { Roots } from "./policy.ts";
4
+ export declare const SHELL_WRITE_CAPABILITIES: WriteCapabilities;
5
+ export interface ShellWrites {
6
+ stat(path: string, options?: OpenOptions): Promise<StatOutcome>;
7
+ write(path: string, bytes: Uint8Array, options: WriteOptions): Promise<MutationOutcome>;
8
+ remove(path: string, options: MutateOptions): Promise<MutationOutcome>;
9
+ }
10
+ export declare function shellVersion(entry: CloudflareShellFileInfo): string;
11
+ export declare function shellWrites(workspace: CloudflareShellWorkspaceLike, roots: Roots, maxBufferedBytes: number): ShellWrites;
package/dist/write.js ADDED
@@ -0,0 +1,224 @@
1
+ import { containsPosix } from "@better-fs-tools/fs";
2
+ import { AdapterRefusal, authorize, boundedCode, displayPath, inspect, mapBackendError, notAFile, pathsFromSlashToTarget, refuse, toFileSystemError, } from "./policy.js";
3
+ export const SHELL_WRITE_CAPABILITIES = Object.freeze({
4
+ compareAndSwap: false,
5
+ });
6
+ export function shellVersion(entry) {
7
+ return `shell:${entry.size}:${entry.updatedAt}`;
8
+ }
9
+ export function shellWrites(workspace, roots, maxBufferedBytes) {
10
+ const { cwd } = roots;
11
+ const locate = async (root, target) => {
12
+ const missing = [];
13
+ for (const component of pathsFromSlashToTarget(target)) {
14
+ if (missing.length > 0) {
15
+ missing.push(component);
16
+ continue;
17
+ }
18
+ const entry = await inspect(workspace, "lstat", component);
19
+ if (entry === null) {
20
+ if (containsPosix(component, root)) {
21
+ throw refuse({ reason: "not-found", detail: "the root does not exist" });
22
+ }
23
+ missing.push(component);
24
+ continue;
25
+ }
26
+ if (entry.type === "symlink") {
27
+ throw refuse({
28
+ reason: "denied",
29
+ detail: component === target
30
+ ? "the path is a symbolic link and this adapter refuses symlinks"
31
+ : "a path component is a symbolic link and this adapter refuses symlinks",
32
+ });
33
+ }
34
+ if (component === target) {
35
+ if (entry.type !== "file")
36
+ throw refuse(notAFile("directory", cwd, target));
37
+ return { exists: true, entry };
38
+ }
39
+ if (entry.type !== "directory") {
40
+ throw refuse({ reason: "not-found", detail: "a path component is not a directory" });
41
+ }
42
+ }
43
+ if (missing.length === 0)
44
+ throw refuse(notAFile("directory", cwd, target));
45
+ return { exists: false, missingDirectories: missing.slice(0, -1) };
46
+ };
47
+ const fileStat = (target, located) => located.exists
48
+ ? {
49
+ exists: true,
50
+ resolvedPath: target,
51
+ displayPath: displayPath(cwd, target),
52
+ size: located.entry.size,
53
+ mtimeMs: located.entry.updatedAt,
54
+ identity: null,
55
+ version: shellVersion(located.entry),
56
+ mode: null,
57
+ hardLinks: null,
58
+ }
59
+ : {
60
+ exists: false,
61
+ resolvedPath: target,
62
+ displayPath: displayPath(cwd, target),
63
+ missingDirectories: located.missingDirectories,
64
+ };
65
+ const makeDirectories = async (mkdir, directories) => {
66
+ const created = [];
67
+ for (const directory of directories) {
68
+ await mutate(mkdir(directory, { recursive: true }), "mkdir");
69
+ const entry = await inspect(workspace, "lstat", directory);
70
+ if (entry?.type !== "directory") {
71
+ throw refuse({ reason: "denied", detail: "a created parent is not a directory" });
72
+ }
73
+ created.push(directory);
74
+ }
75
+ return created;
76
+ };
77
+ const mutated = (target, entry, created) => ({
78
+ resolvedPath: target,
79
+ displayPath: displayPath(cwd, target),
80
+ version: entry === null ? null : shellVersion(entry),
81
+ identity: null,
82
+ size: entry?.size ?? null,
83
+ createdDirectories: created,
84
+ });
85
+ return {
86
+ async stat(requested, options = {}) {
87
+ if (options.signal?.aborted)
88
+ return { ok: false, error: { reason: "aborted" } };
89
+ try {
90
+ const { root, target } = authorize(roots, requested);
91
+ return { ok: true, stat: fileStat(target, await locate(root, target)) };
92
+ }
93
+ catch (error) {
94
+ return { ok: false, error: toFileSystemError(error) };
95
+ }
96
+ },
97
+ async write(requested, bytes, options) {
98
+ if (options.signal?.aborted)
99
+ return { ok: false, error: { reason: "aborted" } };
100
+ try {
101
+ const writeFileBytes = requireMethod(workspace, "writeFileBytes");
102
+ const mkdir = requireMethod(workspace, "mkdir");
103
+ const { root, target } = authorize(roots, requested);
104
+ if (bytes.byteLength > maxBufferedBytes) {
105
+ throw new WriteRefusal({
106
+ reason: "too-large",
107
+ limit: maxBufferedBytes,
108
+ size: bytes.byteLength,
109
+ detail: `the object exceeds the ${maxBufferedBytes}-byte buffered ceiling`,
110
+ });
111
+ }
112
+ const located = await locate(root, target);
113
+ refuseConflict(located, options.precondition);
114
+ if (!located.exists && located.missingDirectories.length > 0 && !options.createParents) {
115
+ throw refuse({ reason: "not-found", detail: "the parent directory does not exist" });
116
+ }
117
+ if (options.signal?.aborted)
118
+ throw refuse({ reason: "aborted" });
119
+ const created = located.exists
120
+ ? []
121
+ : await makeDirectories(mkdir, located.missingDirectories);
122
+ /* Shell resets the mime type to its default unless it is passed again. */
123
+ const mimeType = located.exists ? located.entry.mimeType : undefined;
124
+ await mutate(mimeType === undefined
125
+ ? writeFileBytes(target, bytes)
126
+ : writeFileBytes(target, bytes, mimeType), "writeFileBytes");
127
+ const after = await inspect(workspace, "lstat", target);
128
+ if (after?.type !== "file") {
129
+ throw refuse({ reason: "io", detail: "the file was not there after the write" });
130
+ }
131
+ return { ok: true, file: mutated(target, after, created) };
132
+ }
133
+ catch (error) {
134
+ return { ok: false, error: toMutationError(error) };
135
+ }
136
+ },
137
+ async remove(requested, options) {
138
+ if (options.signal?.aborted)
139
+ return { ok: false, error: { reason: "aborted" } };
140
+ try {
141
+ const rm = requireMethod(workspace, "rm");
142
+ const { root, target } = authorize(roots, requested);
143
+ const located = await locate(root, target);
144
+ refuseConflict(located, options.precondition);
145
+ if (!located.exists)
146
+ throw refuse({ reason: "not-found" });
147
+ if (options.signal?.aborted)
148
+ throw refuse({ reason: "aborted" });
149
+ await mutate(rm(target), "rm");
150
+ return { ok: true, file: mutated(target, null, []) };
151
+ }
152
+ catch (error) {
153
+ return { ok: false, error: toMutationError(error) };
154
+ }
155
+ },
156
+ };
157
+ }
158
+ function requireMethod(workspace, method) {
159
+ const found = workspace[method];
160
+ if (typeof found !== "function") {
161
+ throw new WriteRefusal({
162
+ reason: "unsupported",
163
+ detail: `the Shell Workspace has no ${method}(), so this backend cannot write`,
164
+ });
165
+ }
166
+ return found.bind(workspace);
167
+ }
168
+ function refuseConflict(located, precondition) {
169
+ switch (precondition.kind) {
170
+ case "absent":
171
+ if (located.exists)
172
+ throw new WriteRefusal({ reason: "exists" });
173
+ return;
174
+ case "version":
175
+ if (!located.exists || shellVersion(located.entry) !== precondition.version) {
176
+ throw new WriteRefusal({ reason: "changed" });
177
+ }
178
+ return;
179
+ case "any":
180
+ return;
181
+ default:
182
+ throw refuse({ reason: "io", detail: "unknown precondition" });
183
+ }
184
+ }
185
+ class WriteRefusal extends Error {
186
+ error;
187
+ constructor(error) {
188
+ super(error.reason);
189
+ this.error = error;
190
+ this.name = "WriteRefusal";
191
+ }
192
+ }
193
+ async function mutate(pending, phase) {
194
+ try {
195
+ return await pending;
196
+ }
197
+ catch (error) {
198
+ const code = codeFromErrorOrMessage(error);
199
+ const cause = { code, phase };
200
+ if (code === "EEXIST")
201
+ throw new WriteRefusal({ reason: "exists", cause });
202
+ if (code === "EROFS")
203
+ throw new WriteRefusal({ reason: "read-only", cause });
204
+ if (code === "ENOSPC" || code === "EDQUOT") {
205
+ throw new WriteRefusal({ reason: "no-space", cause });
206
+ }
207
+ throw refuse(mapBackendError({ code }, phase));
208
+ }
209
+ }
210
+ /* Shell errors carry the POSIX code only as a message prefix, e.g. `EEXIST: ...`. */
211
+ function codeFromErrorOrMessage(error) {
212
+ const code = boundedCode(error);
213
+ if (code !== "UNKNOWN" || !(error instanceof Error))
214
+ return code;
215
+ const match = /^(E[A-Z]{2,12}):/u.exec(String(error.message).slice(0, 64));
216
+ return match?.[1] ?? code;
217
+ }
218
+ function toMutationError(error) {
219
+ if (error instanceof WriteRefusal)
220
+ return error.error;
221
+ if (error instanceof AdapterRefusal)
222
+ return error.error;
223
+ return toFileSystemError(error);
224
+ }
package/package.json CHANGED
@@ -1,5 +1,39 @@
1
1
  {
2
2
  "name": "@better-fs-tools/cloudflare-shell",
3
- "version": "0.0.0-tegami-trusted-publish-setup",
4
- "description": "Placeholder published by Tegami for npm trusted publishing setup."
3
+ "version": "0.2.0",
4
+ "description": "A readable and writable filesystem over a Cloudflare Shell Workspace.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/gingerhendrix/better-fs-tools.git",
9
+ "directory": "packages/cloudflare-shell"
10
+ },
11
+ "files": [
12
+ "dist"
13
+ ],
14
+ "type": "module",
15
+ "sideEffects": false,
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js"
20
+ }
21
+ },
22
+ "publishConfig": {
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "import": "./dist/index.js"
27
+ }
28
+ },
29
+ "access": "public"
30
+ },
31
+ "dependencies": {
32
+ "@better-fs-tools/fs": "^0.2.0"
33
+ },
34
+ "devDependencies": {
35
+ "@better-fs-tools/read": "^0.2.0",
36
+ "@better-fs-tools/write": "^0.2.0",
37
+ "@cloudflare/shell": "0.4.3"
38
+ }
5
39
  }