@deepseek-ai/dsh-util-file-operations 0.0.0-stage → 0.2.3-alpha.4
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 +21 -0
- package/README.i18n.yaml +52 -0
- package/README.md +132 -2
- package/README.zh.md +133 -0
- package/lib/index.js +794 -0
- package/lib/types/index.d.ts +286 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js.map +1 -0
- package/package.json +40 -3
- package/src/index.ts +913 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,913 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `FileSystem` file-operation rules as one function over a machine's `node:fs/promises` and `node:path`, which
|
|
3
|
+
* references only its parameters and JavaScript globals. An execution environment runs it from its source text on the
|
|
4
|
+
* machine where the file lives, because `ctx.environments.define()` sends only that text; `FileOperationEnv.limits` and
|
|
5
|
+
* `FileOperationEnv.sandbox` carry such a run's message bound and write sandbox. `fileOperations` builds the
|
|
6
|
+
* `FileSystem` methods on a runner of that function.
|
|
7
|
+
* @module @deepseek-ai/dsh-util-file-operations
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type * as nodeFs from 'node:fs/promises'
|
|
11
|
+
import type * as nodePath from 'node:path'
|
|
12
|
+
import type { BigIntStats } from 'node:fs'
|
|
13
|
+
import {
|
|
14
|
+
FS_ERROR_CODES, FsError, FsTargetKey, FsVersion,
|
|
15
|
+
type FileSystem, type FsDirEntry, type FsEditRequest, type FsErrorCode, type FsTarget, type FsWriteIntent,
|
|
16
|
+
} from '@deepseek-ai/dsh-fs'
|
|
17
|
+
import { applyHunks, type PatchHunk } from '@deepseek-ai/dsh-fs-patch'
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Native publication steps and test hooks a caller may pass; each omitted hook uses the portable `node:fs/promises`
|
|
21
|
+
* behavior.
|
|
22
|
+
*/
|
|
23
|
+
export interface FileOperationHooks {
|
|
24
|
+
/** Platform whose publication rules apply; defaults to `env.platform`. */
|
|
25
|
+
platform?: string
|
|
26
|
+
/** Name of the private staging directory, relative to the target's directory. */
|
|
27
|
+
tempDirName?: (path: string) => string
|
|
28
|
+
/** Name of the staged file, relative to the staging directory. */
|
|
29
|
+
tempName?: (path: string) => string
|
|
30
|
+
/** Copy the Windows DACL of an existing destination onto the staged file; without it the staged file keeps inherited security. */
|
|
31
|
+
copyFileDacl?: (source: string, destination: string) => Promise<void>
|
|
32
|
+
/** Replace an existing Windows destination keeping its security descriptor; without it publication renames. */
|
|
33
|
+
replaceFile?: (replaced: string, replacement: string) => Promise<void>
|
|
34
|
+
/** No-replace publication of a guarded creation. */
|
|
35
|
+
linkFile?: (existingPath: string, newPath: string) => Promise<void>
|
|
36
|
+
/** Metadata of the destination after a guarded publication failed. */
|
|
37
|
+
inspectPublicationTarget?: (path: string) => Promise<BigIntStats>
|
|
38
|
+
/** Runs at the last cancellable checkpoint of a delete or move, with the source path. */
|
|
39
|
+
inspectBeforeMutation?: (path: string) => void | Promise<void>
|
|
40
|
+
/** Non-recursive removal of a delete or move source. */
|
|
41
|
+
removeFile?: (path: string) => Promise<void>
|
|
42
|
+
/** Removal of the staging directory. */
|
|
43
|
+
removeStagingDir?: (stagingDir: string) => Promise<void>
|
|
44
|
+
/** Runs after the staged file is written and synced, before its mode is set and it is published. */
|
|
45
|
+
inspectTemp?: (paths: { stagingDir: string; tempPath: string }) => void | Promise<void>
|
|
46
|
+
/** Runs between the size check and the content read of a byte read, with the file path. */
|
|
47
|
+
inspectReadBytesAfterStat?: (path: string) => void | Promise<void>
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** What {@link fileOperation} uses of the machine the file lives on. */
|
|
51
|
+
export interface FileOperationEnv {
|
|
52
|
+
/** The machine's `node:fs/promises`. */
|
|
53
|
+
readonly fs: typeof nodeFs
|
|
54
|
+
/** The machine's `node:path`. */
|
|
55
|
+
readonly path: typeof nodePath
|
|
56
|
+
/** The machine's `process.platform`. */
|
|
57
|
+
readonly platform: string
|
|
58
|
+
/** Directory a relative request `cwd` resolves against, and the default `cwd`. */
|
|
59
|
+
readonly cwd: string
|
|
60
|
+
/** Cancels the operation at its checkpoints with `FS_ABORTED`. */
|
|
61
|
+
readonly signal?: AbortSignal
|
|
62
|
+
/**
|
|
63
|
+
* Bound on the result of a list, read, edit or load, as an execution environment's connection sets it: text whose
|
|
64
|
+
* UTF-16 units at two bytes each, plus a 4096-byte margin, exceed `maxMessageBytes` fails with `FS_TOO_LARGE`.
|
|
65
|
+
* Omitted: unbounded.
|
|
66
|
+
*/
|
|
67
|
+
readonly limits?: { readonly maxMessageBytes: number }
|
|
68
|
+
/** Native publication steps and test hooks. */
|
|
69
|
+
readonly hooks?: FileOperationHooks
|
|
70
|
+
/**
|
|
71
|
+
* The run's sandbox where the machine fences writes, as an execution environment's run does. A move checks with it
|
|
72
|
+
* that its source may be removed before it publishes anything, so a denied source leaves no copy behind. Omitted where
|
|
73
|
+
* the caller checks every path before the operation runs.
|
|
74
|
+
*/
|
|
75
|
+
readonly sandbox?: {
|
|
76
|
+
readonly mode: string
|
|
77
|
+
/**
|
|
78
|
+
* Tell whether the run may write one path.
|
|
79
|
+
* @param absolutePath - the path to test.
|
|
80
|
+
* @returns whether a write there is permitted.
|
|
81
|
+
*/
|
|
82
|
+
canWrite(absolutePath: string): Promise<boolean>
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* One operation. `path` is a target's realpath identity and `display` the path shown in diagnostics; `version` and
|
|
88
|
+
* `expected` are version tokens from `stat`. `basisMaxBytes` is the exclusive byte bound on a returned diff basis.
|
|
89
|
+
*/
|
|
90
|
+
export type FileOperationRequest =
|
|
91
|
+
| { readonly op: 'resolve'; readonly path: string; readonly cwd: string | undefined }
|
|
92
|
+
| { readonly op: 'stat'; readonly path: string }
|
|
93
|
+
| { readonly op: 'list'; readonly path: string; readonly display: string }
|
|
94
|
+
| { readonly op: 'lstat'; readonly path: string; readonly cwd: string | undefined }
|
|
95
|
+
| { readonly op: 'read'; readonly path: string; readonly display: string }
|
|
96
|
+
| {
|
|
97
|
+
readonly op: 'text'
|
|
98
|
+
readonly bytes: Uint8Array
|
|
99
|
+
/** Bytes of a character split across steps, carried from the previous step. */
|
|
100
|
+
readonly tail: Uint8Array
|
|
101
|
+
/** Bytes of the stream before this step, so the NUL sample stays the one a whole-file read inspects. */
|
|
102
|
+
readonly offset: number
|
|
103
|
+
/** Whether the stream ends after this step, so a character still split at its end is incomplete text. */
|
|
104
|
+
readonly final: boolean
|
|
105
|
+
readonly display: string
|
|
106
|
+
}
|
|
107
|
+
| { readonly op: 'bytes'; readonly path: string; readonly display: string; readonly maxBytes: number }
|
|
108
|
+
| {
|
|
109
|
+
readonly op: 'write'
|
|
110
|
+
readonly path: string
|
|
111
|
+
readonly display: string
|
|
112
|
+
readonly content: string | Uint8Array
|
|
113
|
+
readonly expected: FsWriteIntent | undefined
|
|
114
|
+
readonly basisMaxBytes: number
|
|
115
|
+
}
|
|
116
|
+
| { readonly op: 'edit'; readonly path: string; readonly display: string; readonly edit: FsEditRequest; readonly expected: string | undefined }
|
|
117
|
+
| {
|
|
118
|
+
readonly op: 'load'
|
|
119
|
+
readonly path: string
|
|
120
|
+
readonly display: string
|
|
121
|
+
readonly verb: string
|
|
122
|
+
readonly expected: string | undefined
|
|
123
|
+
/** A move destination, checked like a write target before the source is read. */
|
|
124
|
+
readonly destination?: { readonly path: string; readonly display: string; readonly expected: FsWriteIntent | undefined }
|
|
125
|
+
}
|
|
126
|
+
| {
|
|
127
|
+
readonly op: 'store'
|
|
128
|
+
readonly path: string
|
|
129
|
+
readonly display: string
|
|
130
|
+
readonly verb: string
|
|
131
|
+
readonly content: string
|
|
132
|
+
readonly crlf: boolean
|
|
133
|
+
readonly version: string
|
|
134
|
+
}
|
|
135
|
+
| { readonly op: 'delete'; readonly path: string; readonly display: string; readonly expected: string | undefined; readonly basisMaxBytes: number }
|
|
136
|
+
| {
|
|
137
|
+
readonly op: 'move'
|
|
138
|
+
readonly source: string
|
|
139
|
+
readonly sourceDisplay: string
|
|
140
|
+
readonly sourceVersion: string
|
|
141
|
+
readonly destination: string
|
|
142
|
+
readonly destinationDisplay: string
|
|
143
|
+
readonly content: string
|
|
144
|
+
readonly crlf: boolean
|
|
145
|
+
readonly expected: FsWriteIntent | undefined
|
|
146
|
+
readonly basisMaxBytes: number
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
/** File metadata; `type` follows symbolic links except for `lstat`, which reports `symlink`. */
|
|
151
|
+
export interface FileOperationInfo {
|
|
152
|
+
readonly version: string
|
|
153
|
+
readonly type: 'file' | 'directory' | 'symlink' | 'other'
|
|
154
|
+
readonly size: number
|
|
155
|
+
readonly mode: number
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Result of each operation, by `op`. */
|
|
159
|
+
export interface FileOperationResults {
|
|
160
|
+
/** `display` is the absolute path before symbolic links resolve; `real` is the realpath identity. */
|
|
161
|
+
resolve: { display: string; real: string }
|
|
162
|
+
stat: FileOperationInfo | null
|
|
163
|
+
/** Direct children in name order; `info` follows links and is null for a child that vanished. */
|
|
164
|
+
list: Array<{ name: string; display: string; real: string; info: FileOperationInfo | null }>
|
|
165
|
+
lstat: FileOperationInfo | null
|
|
166
|
+
read: string
|
|
167
|
+
/** One decoded step of a streamed read: its text and the split character it carries. */
|
|
168
|
+
text: { text: string; tail: Uint8Array }
|
|
169
|
+
bytes: Uint8Array
|
|
170
|
+
/** `before` is the LF-normalized previous text, or null without a text basis below `basisMaxBytes`. */
|
|
171
|
+
write: { operation: 'create' | 'update'; version: string; before: string | null }
|
|
172
|
+
/** LF-normalized text before and after the edit. */
|
|
173
|
+
edit: { version: string; before: string; after: string }
|
|
174
|
+
/** LF-normalized text, whether the file stores CRLF line endings, and the version it was read at. */
|
|
175
|
+
load: { content: string; crlf: boolean; version: string }
|
|
176
|
+
store: { version: string }
|
|
177
|
+
delete: { before: string | null }
|
|
178
|
+
/** `sourceFailure` describes a source that stayed after its destination was published. */
|
|
179
|
+
move: {
|
|
180
|
+
operation: 'create' | 'update'
|
|
181
|
+
version: string
|
|
182
|
+
before: string | null
|
|
183
|
+
sourceFailure: { code: FsErrorCode; message: string } | null
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Perform one file operation. It references only its parameters and JavaScript globals (`Buffer`, `TextDecoder`), and
|
|
189
|
+
* keeps no module state; a change must keep it so, because an execution environment evaluates its source text in another
|
|
190
|
+
* process. That run's `fs` throws errors of another realm, so errors are read by their fields, never by `instanceof`.
|
|
191
|
+
* Failures carry an `FS_*` `code` and their diagnostic, or are defects without a code; {@link fileOperationError} turns
|
|
192
|
+
* them into `FsError`s. A publication or removal that the environment's file guard refuses with code `SANDBOX_DENIED`
|
|
193
|
+
* fails `FS_SANDBOX_DENIED` with the guard's message.
|
|
194
|
+
*
|
|
195
|
+
* Text is UTF-8: a read rejects a NUL byte in its first 8192 bytes, and a mutation that reads text rejects any NUL.
|
|
196
|
+
* Edits match literal text on LF-normalized content and store it back in the file's line-ending style, CRLF when CRLF
|
|
197
|
+
* pairs outnumber lone LFs in the first 4096 characters. Mutations check the version guard immediately before
|
|
198
|
+
* publishing; publication writes an owner-only file in a private sibling staging directory, syncs it, carries the
|
|
199
|
+
* existing file mode, and renames it over the target, or links it for a guarded creation so a concurrent creator is
|
|
200
|
+
* never replaced. Cancellation is observed until publication; a move that published its destination still removes
|
|
201
|
+
* its source.
|
|
202
|
+
* @param request - the operation.
|
|
203
|
+
* @param env - the machine the file lives on.
|
|
204
|
+
* @returns the operation's {@link FileOperationResults} entry.
|
|
205
|
+
*/
|
|
206
|
+
export async function fileOperation<R extends FileOperationRequest>(request: R, env: FileOperationEnv): Promise<FileOperationResults[R['op']]>
|
|
207
|
+
export async function fileOperation(
|
|
208
|
+
request: FileOperationRequest, env: FileOperationEnv,
|
|
209
|
+
): Promise<FileOperationResults[keyof FileOperationResults]> {
|
|
210
|
+
const { fs, path: P } = env
|
|
211
|
+
const hooks = env.hooks ?? {}
|
|
212
|
+
// Each case returns through this, so its value is checked against the result its operation declares.
|
|
213
|
+
const result = <K extends keyof FileOperationResults>(_op: K, value: FileOperationResults[K]): FileOperationResults[K] => value
|
|
214
|
+
const fail = (code: string, message: string, cause?: unknown): Error =>
|
|
215
|
+
Object.assign(new Error(message), cause === undefined ? { code } : { code, cause })
|
|
216
|
+
const codeOf = (error: unknown): unknown => (error as { code?: unknown } | null)?.code
|
|
217
|
+
// An execution environment runs this function in its own realm, where `instanceof Error` fails for the errors its
|
|
218
|
+
// `fs` throws, so errors are read by their fields.
|
|
219
|
+
const messageOf = (error: unknown): string => {
|
|
220
|
+
const message = (error as { message?: unknown } | null)?.message
|
|
221
|
+
return typeof message === 'string' ? message : String(error)
|
|
222
|
+
}
|
|
223
|
+
const coded = (error: unknown): boolean => typeof codeOf(error) === 'string' && String(codeOf(error)).startsWith('FS_')
|
|
224
|
+
const absent = (error: unknown): boolean => codeOf(error) === 'ENOENT' || codeOf(error) === 'ENOTDIR'
|
|
225
|
+
const permission = (error: unknown): boolean => codeOf(error) === 'EACCES' || codeOf(error) === 'EPERM'
|
|
226
|
+
const abortError = (error: unknown): boolean => (error as { name?: unknown } | null)?.name === 'AbortError'
|
|
227
|
+
// An execution environment's file guard refuses a write outside the run's policy with this code; it is a policy
|
|
228
|
+
// denial, not an errno failure, and keeps the guard's message, which names the path, the mode and the roots.
|
|
229
|
+
const sandboxDenied = (error: unknown): Error | undefined =>
|
|
230
|
+
codeOf(error) === 'SANDBOX_DENIED' ? fail('FS_SANDBOX_DENIED', messageOf(error), error) : undefined
|
|
231
|
+
// The classification of `fsErrorFromErrno` in `@deepseek-ai/dsh-fs` for an errno failure; a defect passes through.
|
|
232
|
+
const classify = (verb: string, display: string, error: unknown): unknown => {
|
|
233
|
+
if (coded(error) || typeof codeOf(error) !== 'string') return error
|
|
234
|
+
const failure = `cannot ${verb} "${display}"`
|
|
235
|
+
if (absent(error)) return fail('FS_NOT_FOUND', `${failure}: not found`, error)
|
|
236
|
+
if (permission(error)) return fail('FS_PERMISSION_DENIED', `${failure}: permission denied`, error)
|
|
237
|
+
if (codeOf(error) === 'EISDIR') return fail('FS_NOT_REGULAR_FILE', `${failure}: not a regular file`, error)
|
|
238
|
+
return fail('FS_IO_ERROR', `${failure}: ${messageOf(error)}`, error)
|
|
239
|
+
}
|
|
240
|
+
const checkAborted = (verb: string): void => {
|
|
241
|
+
if (env.signal?.aborted === true) throw fail('FS_ABORTED', `${verb} aborted`)
|
|
242
|
+
}
|
|
243
|
+
// A string counts at most two bytes per UTF-16 code unit; the margin covers the rest of the result message.
|
|
244
|
+
const fits = (units: number): boolean => env.limits === undefined || units * 2 + 4096 <= env.limits.maxMessageBytes
|
|
245
|
+
const tooLarge = (verb: string, display: string): Error =>
|
|
246
|
+
fail('FS_TOO_LARGE', `cannot ${verb} "${display}": larger than the environment connection carries`)
|
|
247
|
+
const changed = (verb: string, display: string): Error => fail('FS_STALE_VERSION', `cannot ${verb} "${display}": file changed since it was read`)
|
|
248
|
+
|
|
249
|
+
const versionOf = (info: BigIntStats): string => `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`
|
|
250
|
+
/** The entry type one metadata read reports, most specific classification first. */
|
|
251
|
+
const typeOfEntry = (info: BigIntStats): FileOperationInfo['type'] => {
|
|
252
|
+
if (info.isSymbolicLink()) return 'symlink'
|
|
253
|
+
if (info.isFile()) return 'file'
|
|
254
|
+
if (info.isDirectory()) return 'directory'
|
|
255
|
+
return 'other'
|
|
256
|
+
}
|
|
257
|
+
const describe = (info: BigIntStats): FileOperationInfo => ({
|
|
258
|
+
version: versionOf(info),
|
|
259
|
+
type: typeOfEntry(info),
|
|
260
|
+
size: Number(info.size),
|
|
261
|
+
mode: Number(info.mode & 0o777n),
|
|
262
|
+
})
|
|
263
|
+
// Absent (ENOENT, or ENOTDIR for a file-valued parent segment) is null; another failure is a metadata fault.
|
|
264
|
+
const probe = async (path: string, follow = true): Promise<BigIntStats | null> => {
|
|
265
|
+
try {
|
|
266
|
+
return await (follow ? fs.stat(path, { bigint: true }) : fs.lstat(path, { bigint: true }))
|
|
267
|
+
} catch (error) {
|
|
268
|
+
if (absent(error)) return null
|
|
269
|
+
throw classify('stat', path, error)
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
const requireFile = async (path: string, display: string, verb: string, expected: string | undefined): Promise<BigIntStats> => {
|
|
273
|
+
const existing = await probe(path)
|
|
274
|
+
if (existing === null) throw changed(verb, display)
|
|
275
|
+
if (!existing.isFile()) throw fail('FS_NOT_REGULAR_FILE', `cannot ${verb} "${display}": not a regular file`)
|
|
276
|
+
if (expected !== undefined && versionOf(existing) !== expected) throw changed(verb, display)
|
|
277
|
+
return existing
|
|
278
|
+
}
|
|
279
|
+
const writeTarget = async (path: string, display: string, expected: FsWriteIntent | undefined): Promise<BigIntStats | null> => {
|
|
280
|
+
const existing = await probe(path)
|
|
281
|
+
if (existing !== null && !existing.isFile()) throw fail('FS_NOT_REGULAR_FILE', `cannot write "${display}": not a regular file`)
|
|
282
|
+
if (expected?.kind === 'replaceIfVersion') {
|
|
283
|
+
if (existing === null) throw fail('FS_STALE_VERSION', `cannot write "${display}": file no longer exists`)
|
|
284
|
+
if (versionOf(existing) !== expected.version) throw changed('write', display)
|
|
285
|
+
} else if (expected?.kind === 'createIfAbsent' && existing !== null) {
|
|
286
|
+
throw fail('FS_NOT_OBSERVED', `cannot overwrite existing "${display}" without reading it first`)
|
|
287
|
+
}
|
|
288
|
+
return existing
|
|
289
|
+
}
|
|
290
|
+
const versionAfter = async (path: string): Promise<string> => {
|
|
291
|
+
const after = await probe(path)
|
|
292
|
+
/* v8 ignore next -- needs a concurrent unlink between publication and this stat. */
|
|
293
|
+
return after === null ? `missing:${path}` : versionOf(after)
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// --- Text ---
|
|
297
|
+
const normalize = (text: string): string => text.replaceAll('\r\n', '\n')
|
|
298
|
+
const crlfOf = (raw: string): boolean => {
|
|
299
|
+
const sample = raw.slice(0, 4096)
|
|
300
|
+
const crlf = sample.split('\r\n').length - 1
|
|
301
|
+
return crlf > sample.split('\n').length - 1 - crlf
|
|
302
|
+
}
|
|
303
|
+
const restore = (content: string, crlf: boolean): string => crlf ? normalize(content).split('\n').join('\r\n') : content
|
|
304
|
+
/** A NUL byte makes content binary rather than text. */
|
|
305
|
+
const assertBytes = (bytes: Uint8Array, verb: string, display: string): void => {
|
|
306
|
+
if (bytes.includes(0)) throw fail('FS_NOT_TEXT', `cannot ${verb} "${display}": binary file`)
|
|
307
|
+
}
|
|
308
|
+
const decodeUtf8 = (bytes: Uint8Array, verb: string, display: string): string => {
|
|
309
|
+
try {
|
|
310
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(bytes)
|
|
311
|
+
} catch (invalid) {
|
|
312
|
+
throw fail('FS_NOT_TEXT', `cannot ${verb} "${display}": invalid UTF-8 text`, invalid)
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
/** Leading bytes a text read inspects for NUL, applied by a whole-file read and by each streamed step. */
|
|
316
|
+
const SAMPLE_BYTES = 8192
|
|
317
|
+
/**
|
|
318
|
+
* Length of the UTF-8 sequence a lead byte starts: 0xC2–0xDF starts two bytes, 0xE0–0xEF three, 0xF0–0xF4 four,
|
|
319
|
+
* and every other byte starts none.
|
|
320
|
+
* @param lead - the first byte of a sequence.
|
|
321
|
+
* @returns its length in bytes, or 0 when it starts no multi-byte sequence.
|
|
322
|
+
*/
|
|
323
|
+
const sequenceLength = (lead: number): number => {
|
|
324
|
+
if (lead >= 0xC2 && lead <= 0xDF) return 2
|
|
325
|
+
if (lead >= 0xE0 && lead <= 0xEF) return 3
|
|
326
|
+
if (lead >= 0xF0 && lead <= 0xF4) return 4
|
|
327
|
+
return 0
|
|
328
|
+
}
|
|
329
|
+
/** Whether `bytes` are the start of a well-formed UTF-8 sequence a later step completes, so they can be carried. */
|
|
330
|
+
const unfinishedSequence = (bytes: Uint8Array): boolean => {
|
|
331
|
+
const lead = bytes[0] as number
|
|
332
|
+
const expected = sequenceLength(lead)
|
|
333
|
+
if (expected === 0 || bytes.length >= expected) return false
|
|
334
|
+
for (let index = 1; index < bytes.length; index += 1) if (((bytes[index] as number) & 0xC0) !== 0x80) return false
|
|
335
|
+
return true
|
|
336
|
+
}
|
|
337
|
+
// A read samples its leading bytes, as a stream does; a mutation that rewrites the file rejects any NUL.
|
|
338
|
+
const decode = (bytes: Uint8Array, verb: string, display: string): string => {
|
|
339
|
+
assertBytes(verb === 'read' ? bytes.subarray(0, SAMPLE_BYTES) : bytes, verb, display)
|
|
340
|
+
return decodeUtf8(bytes, verb, display)
|
|
341
|
+
}
|
|
342
|
+
const readFile = async (path: string, display: string, verb: string): Promise<Uint8Array> => {
|
|
343
|
+
checkAborted(verb)
|
|
344
|
+
try {
|
|
345
|
+
return await fs.readFile(path, env.signal === undefined ? {} : { signal: env.signal })
|
|
346
|
+
} catch (error) {
|
|
347
|
+
/* v8 ignore next -- a mid-read abort needs cancellation racing an active read; earlier checkpoints catch a prior abort. */
|
|
348
|
+
if (abortError(error)) throw fail('FS_ABORTED', `${verb} aborted`)
|
|
349
|
+
throw classify(verb, display, error)
|
|
350
|
+
} finally {
|
|
351
|
+
checkAborted(verb)
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
// Text for a literal edit or patch: any NUL rejects, and the result is LF-normalized with the stored style.
|
|
355
|
+
const readForEdit = async (path: string, display: string): Promise<{ content: string; crlf: boolean }> => {
|
|
356
|
+
const raw = decode(await readFile(path, display, 'edit'), 'edit', display)
|
|
357
|
+
return { content: normalize(raw), crlf: crlfOf(raw) }
|
|
358
|
+
}
|
|
359
|
+
const statRegular = async (path: string, display: string): Promise<BigIntStats> => {
|
|
360
|
+
checkAborted('read')
|
|
361
|
+
let info: BigIntStats
|
|
362
|
+
try {
|
|
363
|
+
info = await fs.stat(path, { bigint: true })
|
|
364
|
+
} catch (error) {
|
|
365
|
+
throw classify('read', display, error)
|
|
366
|
+
}
|
|
367
|
+
if (!info.isFile()) throw fail('FS_NOT_REGULAR_FILE', `cannot read "${display}": not a regular file`)
|
|
368
|
+
return info
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* Best-effort LF-normalized diff basis of `path`: null for a non-regular, at/above-bound, binary, non-UTF-8, resized
|
|
372
|
+
* or unreadable file. The bound applies to the opened descriptor, and reads go in 64 KiB chunks so cancellation is
|
|
373
|
+
* observed between them; cancellation propagates.
|
|
374
|
+
*/
|
|
375
|
+
const basis = async (path: string, maxBytes: number): Promise<string | null> => {
|
|
376
|
+
checkAborted('read')
|
|
377
|
+
try {
|
|
378
|
+
const handle = await fs.open(path, 'r')
|
|
379
|
+
let buffer: Buffer
|
|
380
|
+
let total = 0
|
|
381
|
+
let openedSize = 0
|
|
382
|
+
try {
|
|
383
|
+
checkAborted('read')
|
|
384
|
+
const info = await handle.stat()
|
|
385
|
+
checkAborted('read')
|
|
386
|
+
if (!info.isFile() || info.size >= maxBytes) return null
|
|
387
|
+
openedSize = info.size
|
|
388
|
+
// One extra byte detects growth after the descriptor stat.
|
|
389
|
+
buffer = Buffer.allocUnsafe(openedSize + 1)
|
|
390
|
+
while (total < buffer.length) {
|
|
391
|
+
checkAborted('read')
|
|
392
|
+
const { bytesRead } = await handle.read(buffer, total, Math.min(buffer.length - total, 64 * 1024), null)
|
|
393
|
+
if (bytesRead === 0) break
|
|
394
|
+
total += bytesRead
|
|
395
|
+
}
|
|
396
|
+
} finally {
|
|
397
|
+
await handle.close()
|
|
398
|
+
}
|
|
399
|
+
checkAborted('read')
|
|
400
|
+
if (total !== openedSize) return null
|
|
401
|
+
try {
|
|
402
|
+
return normalize(decode(buffer.subarray(0, total), 'edit', path))
|
|
403
|
+
} catch (_notText) {
|
|
404
|
+
// A binary or non-UTF-8 previous file costs only the optional basis.
|
|
405
|
+
return null
|
|
406
|
+
}
|
|
407
|
+
} catch (error) {
|
|
408
|
+
if (coded(error)) throw error
|
|
409
|
+
// A descriptor-phase errno costs only the optional basis: a committed mutation must not fail for it.
|
|
410
|
+
if (typeof codeOf(error) === 'string') return null
|
|
411
|
+
throw error
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
const literalEdit = (content: string, edit: FsEditRequest, display: string): string => {
|
|
415
|
+
const oldString = normalize(edit.oldString)
|
|
416
|
+
if (oldString.length === 0) throw fail('FS_EDIT_NOT_FOUND', 'old_string must be a non-empty string')
|
|
417
|
+
let matches = 0
|
|
418
|
+
for (let index = content.indexOf(oldString); index !== -1; index = content.indexOf(oldString, index + oldString.length)) matches++
|
|
419
|
+
if (matches === 0) throw fail('FS_EDIT_NOT_FOUND', `old_string was not found in "${display}"`)
|
|
420
|
+
if (!edit.replaceAll && matches > 1) {
|
|
421
|
+
throw fail('FS_AMBIGUOUS_EDIT', `old_string matched ${matches} times in "${display}"; provide a more specific old_string or set replace_all to true`)
|
|
422
|
+
}
|
|
423
|
+
return content.split(oldString).join(normalize(edit.newString))
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
// --- Publication ---
|
|
427
|
+
const writeFailure = (display: string, error: unknown): unknown => {
|
|
428
|
+
if (coded(error)) return error
|
|
429
|
+
const denied = sandboxDenied(error)
|
|
430
|
+
if (denied !== undefined) return denied
|
|
431
|
+
/* v8 ignore next -- an abort during the staged write needs a writeFile/signal race; the checkpoints around it are tested. */
|
|
432
|
+
if (abortError(error)) return fail('FS_ABORTED', 'write aborted')
|
|
433
|
+
if (permission(error)) return fail('FS_PERMISSION_DENIED', `cannot write "${display}": permission denied`, error)
|
|
434
|
+
if (typeof codeOf(error) === 'string') return fail('FS_IO_ERROR', `cannot write "${display}": ${messageOf(error)}`, error)
|
|
435
|
+
return error
|
|
436
|
+
}
|
|
437
|
+
const guardedCreateFailure = async (error: unknown, path: string, display: string): Promise<never> => {
|
|
438
|
+
let existing: BigIntStats | undefined
|
|
439
|
+
try {
|
|
440
|
+
existing = await (hooks.inspectPublicationTarget ?? (target => fs.lstat(target, { bigint: true })))(path)
|
|
441
|
+
} catch (metadataError) {
|
|
442
|
+
if (!absent(metadataError)) throw fail('FS_IO_ERROR', `cannot write "${display}": ${messageOf(metadataError)}`, metadataError)
|
|
443
|
+
}
|
|
444
|
+
// Link errno values vary by platform and filesystem; the destination entry tells a collision from missing link support.
|
|
445
|
+
if (existing !== undefined && !existing.isFile()) throw fail('FS_NOT_REGULAR_FILE', `cannot write "${display}": not a regular file`, error)
|
|
446
|
+
if (existing !== undefined || codeOf(error) === 'EEXIST') {
|
|
447
|
+
throw fail('FS_NOT_OBSERVED', `cannot overwrite existing "${display}" without reading it first`, error)
|
|
448
|
+
}
|
|
449
|
+
throw fail('FS_IO_ERROR', `cannot write "${display}": ${messageOf(error)}`, error)
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* Atomically publish `content` at `path`. On Windows an existing destination keeps its security descriptor through
|
|
453
|
+
* the DACL and replacement hooks; a replaced destination that vanished during staging is recreated by rename.
|
|
454
|
+
*/
|
|
455
|
+
const publish = async (
|
|
456
|
+
path: string, display: string, content: string | Uint8Array, mode: number | undefined,
|
|
457
|
+
options: { createIfAbsent?: boolean; existingDestination?: boolean; cancellable?: boolean } = {},
|
|
458
|
+
): Promise<void> => {
|
|
459
|
+
const cancellable = options.cancellable ?? true
|
|
460
|
+
const check = (): void => { if (cancellable) checkAborted('write') }
|
|
461
|
+
const existingDestination = options.existingDestination ?? mode !== undefined
|
|
462
|
+
const platform = hooks.platform ?? env.platform
|
|
463
|
+
check()
|
|
464
|
+
const directory = P.dirname(path)
|
|
465
|
+
try { await fs.mkdir(directory, { recursive: true }) } catch (error) { throw writeFailure(display, error) }
|
|
466
|
+
check()
|
|
467
|
+
const stagingDir = P.join(directory, hooks.tempDirName?.(path) ?? `.${P.basename(path)}.${Date.now().toString(36)}${Math.random().toString(36).slice(2)}.tmpdir`)
|
|
468
|
+
const tempPath = P.join(stagingDir, hooks.tempName?.(path) ?? `${P.basename(path)}.tmp`)
|
|
469
|
+
const removeStagingDir = hooks.removeStagingDir ?? (dir => fs.rm(dir, { recursive: true, force: true }))
|
|
470
|
+
let handle: nodeFs.FileHandle | undefined
|
|
471
|
+
let stagingCreated = false
|
|
472
|
+
try {
|
|
473
|
+
await fs.mkdir(stagingDir, { mode: 0o700 })
|
|
474
|
+
stagingCreated = true
|
|
475
|
+
await fs.chmod(stagingDir, 0o700)
|
|
476
|
+
handle = await fs.open(tempPath, 'wx', 0o600)
|
|
477
|
+
await handle.chmod(0o600)
|
|
478
|
+
if (platform === 'win32' && existingDestination) await hooks.copyFileDacl?.(path, tempPath)
|
|
479
|
+
// Text is written as UTF-8; bytes are stored verbatim.
|
|
480
|
+
await handle.writeFile(content, {
|
|
481
|
+
...typeof content === 'string' ? { encoding: 'utf8' as const } : {},
|
|
482
|
+
...cancellable && env.signal !== undefined ? { signal: env.signal } : {},
|
|
483
|
+
})
|
|
484
|
+
await handle.sync()
|
|
485
|
+
await hooks.inspectTemp?.({ stagingDir, tempPath })
|
|
486
|
+
if (mode !== undefined) await handle.chmod(mode)
|
|
487
|
+
await handle.close()
|
|
488
|
+
handle = undefined
|
|
489
|
+
check()
|
|
490
|
+
if (options.createIfAbsent === true) {
|
|
491
|
+
try {
|
|
492
|
+
await (hooks.linkFile ?? fs.link)(tempPath, path)
|
|
493
|
+
} catch (error) {
|
|
494
|
+
await guardedCreateFailure(error, path, display)
|
|
495
|
+
}
|
|
496
|
+
} else if (platform === 'win32' && existingDestination && hooks.replaceFile !== undefined) {
|
|
497
|
+
try {
|
|
498
|
+
await hooks.replaceFile(path, tempPath)
|
|
499
|
+
} catch (error) {
|
|
500
|
+
// A destination that disappeared during staging is recreated with the already-protected staged file.
|
|
501
|
+
if (codeOf(error) !== 'ENOENT') throw error
|
|
502
|
+
await fs.rename(tempPath, path)
|
|
503
|
+
}
|
|
504
|
+
} else {
|
|
505
|
+
await fs.rename(tempPath, path)
|
|
506
|
+
}
|
|
507
|
+
try {
|
|
508
|
+
await removeStagingDir(stagingDir)
|
|
509
|
+
} catch (_committedStagingCleanupFailure) {
|
|
510
|
+
// The target is committed; owner-only staging residue cannot turn that write into a failure.
|
|
511
|
+
}
|
|
512
|
+
} catch (error) {
|
|
513
|
+
let failure = writeFailure(display, error)
|
|
514
|
+
/* v8 ignore next 8 -- reached only if writeFile/sync throws with the handle open; a close failure is a double fault. */
|
|
515
|
+
if (handle !== undefined) {
|
|
516
|
+
try {
|
|
517
|
+
await handle.close()
|
|
518
|
+
} catch (closeError) {
|
|
519
|
+
failure = fail('FS_NOT_FOUND', `write failed (${messageOf(failure)}) and temp close failed (${messageOf(closeError)})`, failure)
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
if (!stagingCreated) throw failure
|
|
523
|
+
try {
|
|
524
|
+
await removeStagingDir(stagingDir)
|
|
525
|
+
} catch (cleanupError) {
|
|
526
|
+
/* v8 ignore next -- needs a second filesystem fault after the primary write failure. */
|
|
527
|
+
throw fail('FS_NOT_FOUND', `write failed (${messageOf(failure)}) and temp cleanup failed (${messageOf(cleanupError)})`, failure)
|
|
528
|
+
}
|
|
529
|
+
throw failure
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
/** Remove one file, returning the failure a delete throws and a move reports, or null once the file is gone. */
|
|
533
|
+
const remove = async (path: string, display: string): Promise<{
|
|
534
|
+
readonly code: 'FS_SANDBOX_DENIED' | 'FS_PERMISSION_DENIED' | 'FS_IO_ERROR'
|
|
535
|
+
readonly message: string
|
|
536
|
+
readonly cause: unknown
|
|
537
|
+
} | null> => {
|
|
538
|
+
try {
|
|
539
|
+
await (hooks.removeFile ?? fs.rm)(path)
|
|
540
|
+
return null
|
|
541
|
+
} catch (error) {
|
|
542
|
+
// An execution environment's file guard refuses the removal with its own message.
|
|
543
|
+
if (codeOf(error) === 'SANDBOX_DENIED') return { code: 'FS_SANDBOX_DENIED', message: messageOf(error), cause: error }
|
|
544
|
+
const code = permission(error) ? 'FS_PERMISSION_DENIED' : 'FS_IO_ERROR'
|
|
545
|
+
return { code, message: `cannot delete "${display}": ${messageOf(error)}`, cause: error }
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
// --- Paths ---
|
|
550
|
+
// Native drive semantics on Windows; elsewhere a spelling with `..` keeps physical parent traversal.
|
|
551
|
+
const displayPath = (cwd: string, path: string): string => {
|
|
552
|
+
// A drive-relative base such as `C:Users\x` already names its directory; prefixing the process directory would
|
|
553
|
+
// resolve it against the wrong one, so it passes through unchanged.
|
|
554
|
+
const driveRelative = env.platform === 'win32' && /^[A-Za-z]:(?![\\/])/u.test(cwd)
|
|
555
|
+
const absoluteCwd = P.isAbsolute(cwd) || driveRelative ? cwd : `${env.cwd}${P.sep}${cwd}`
|
|
556
|
+
const raw = P.isAbsolute(path) ? path : `${absoluteCwd}${P.sep}${path}`
|
|
557
|
+
const physical = /(?:^|[\\/])\.\.(?:[\\/]|$)/u.test(raw) ? raw : P.resolve(absoluteCwd, path)
|
|
558
|
+
/* v8 ignore next -- Native Windows tests cover DOS drive-relative resolution; POSIX preserves physical traversal. */
|
|
559
|
+
return env.platform === 'win32' ? P.resolve(absoluteCwd, path) : physical
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
// A missing target keeps its identity across creation: the nearest existing ancestor's realpath plus the rest.
|
|
563
|
+
const resolveTarget = async (cwd: string, path: string): Promise<{ display: string; real: string }> => {
|
|
564
|
+
if (path.trim().length === 0) throw fail('FS_NOT_FOUND', 'file_path must be a non-empty string')
|
|
565
|
+
const display = displayPath(cwd, path)
|
|
566
|
+
try {
|
|
567
|
+
return { display, real: await fs.realpath(display) }
|
|
568
|
+
} catch (error) {
|
|
569
|
+
/* v8 ignore next -- Windows reports this case as ENOENT and repairs it in the ancestor walk below. */
|
|
570
|
+
if (codeOf(error) === 'ENOTDIR') throw fail('FS_NOT_FOUND', `cannot resolve "${display}": a parent path segment is not a directory`)
|
|
571
|
+
if (codeOf(error) !== 'ENOENT') throw classify('resolve', display, error)
|
|
572
|
+
}
|
|
573
|
+
const missing = [P.basename(display)]
|
|
574
|
+
for (let ancestor = P.dirname(display); ; ancestor = P.dirname(ancestor)) {
|
|
575
|
+
try {
|
|
576
|
+
const real = await fs.realpath(ancestor)
|
|
577
|
+
/* v8 ignore next -- POSIX rejects this traversal; Windows normalizes parent segments before filesystem lookup. */
|
|
578
|
+
if (missing.includes('..')) throw fail('FS_NOT_FOUND', `cannot resolve "${display}": parent traversal crosses a missing directory`)
|
|
579
|
+
// Windows realpaths a regular file where POSIX reports ENOTDIR for `file/child`.
|
|
580
|
+
/* v8 ignore next 3 -- native Windows coverage exercises this repair. */
|
|
581
|
+
if (env.platform === 'win32' && !(await fs.stat(real)).isDirectory()) {
|
|
582
|
+
throw fail('FS_NOT_FOUND', `cannot resolve "${display}": a parent path segment is not a directory`)
|
|
583
|
+
}
|
|
584
|
+
return { display, real: P.join(real, ...missing) }
|
|
585
|
+
} catch (error) {
|
|
586
|
+
/* v8 ignore next -- native Windows coverage exercises the failures raised above. */
|
|
587
|
+
if (coded(error)) throw error
|
|
588
|
+
/* v8 ignore next -- needs an ancestor realpath fault after the full path reported ENOENT. */
|
|
589
|
+
if (codeOf(error) !== 'ENOENT') throw classify('resolve', display, error)
|
|
590
|
+
/* v8 ignore next -- the filesystem root always realpaths, so the walk ends before reaching it. */
|
|
591
|
+
if (P.dirname(ancestor) === ancestor) return { display, real: display }
|
|
592
|
+
missing.unshift(P.basename(ancestor))
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
switch (request.op) {
|
|
598
|
+
case 'resolve': return result('resolve', await resolveTarget(request.cwd ?? env.cwd, request.path))
|
|
599
|
+
case 'stat': {
|
|
600
|
+
const info = await probe(request.path)
|
|
601
|
+
return result('stat', info === null ? null : describe(info))
|
|
602
|
+
}
|
|
603
|
+
case 'list': {
|
|
604
|
+
const { path, display } = request
|
|
605
|
+
checkAborted('list')
|
|
606
|
+
let info: BigIntStats | null
|
|
607
|
+
try {
|
|
608
|
+
info = await fs.stat(path, { bigint: true })
|
|
609
|
+
} catch (error) {
|
|
610
|
+
if (!absent(error)) throw classify('list', display, error)
|
|
611
|
+
info = null
|
|
612
|
+
}
|
|
613
|
+
if (info === null) throw fail('FS_NOT_FOUND', `cannot list "${display}": not found`)
|
|
614
|
+
if (!info.isDirectory()) throw fail('FS_NOT_DIRECTORY', `cannot list "${display}": not a directory`)
|
|
615
|
+
let names: string[]
|
|
616
|
+
try {
|
|
617
|
+
names = await fs.readdir(path, { encoding: 'utf8' })
|
|
618
|
+
} catch (error) {
|
|
619
|
+
/* v8 ignore next -- needs a permission or kernel failure from readdir after a successful directory stat. */
|
|
620
|
+
throw classify('list', display, error)
|
|
621
|
+
}
|
|
622
|
+
const entries: FileOperationResults['list'] = []
|
|
623
|
+
let units = 0
|
|
624
|
+
for (const name of names.sort((left, right) => left.localeCompare(right))) {
|
|
625
|
+
checkAborted('list')
|
|
626
|
+
// A child that cannot be resolved or inspected fails the listing with its own resolution or metadata failure.
|
|
627
|
+
const { real } = await resolveTarget(path, name)
|
|
628
|
+
const child = await probe(real)
|
|
629
|
+
const entry = { name, display: displayPath(display, name), real, info: child === null ? null : describe(child) }
|
|
630
|
+
// The result carries each entry's name, display path and real path, plus its keys, type and version.
|
|
631
|
+
units += entry.name.length + entry.display.length + entry.real.length + 96
|
|
632
|
+
if (!fits(units)) throw tooLarge('list', display)
|
|
633
|
+
entries.push(entry)
|
|
634
|
+
}
|
|
635
|
+
checkAborted('list')
|
|
636
|
+
return result('list', entries)
|
|
637
|
+
}
|
|
638
|
+
case 'lstat': {
|
|
639
|
+
if (request.path.trim().length === 0) throw fail('FS_NOT_FOUND', 'file_path must be a non-empty string')
|
|
640
|
+
const info = await probe(displayPath(request.cwd ?? env.cwd, request.path), false)
|
|
641
|
+
return result('lstat', info === null ? null : describe(info))
|
|
642
|
+
}
|
|
643
|
+
case 'read': {
|
|
644
|
+
const { path, display } = request
|
|
645
|
+
const info = await statRegular(path, display)
|
|
646
|
+
if (!fits(Number(info.size))) throw tooLarge('read', display)
|
|
647
|
+
return result('read', decode(await readFile(path, display, 'read'), 'read', display))
|
|
648
|
+
}
|
|
649
|
+
case 'text': {
|
|
650
|
+
// One step of a streamed read: the same NUL sample and UTF-8 rule a whole-file read applies.
|
|
651
|
+
const { bytes, tail, offset, final, display } = request
|
|
652
|
+
// A whole-file read samples only its leading bytes, so does a stream: a NUL past the sample is not a read failure.
|
|
653
|
+
const sampled = Math.max(0, Math.min(bytes.length, SAMPLE_BYTES - offset))
|
|
654
|
+
assertBytes(bytes.subarray(0, sampled), 'read', display)
|
|
655
|
+
const joined = new Uint8Array(tail.length + bytes.length)
|
|
656
|
+
joined.set(tail)
|
|
657
|
+
joined.set(bytes, tail.length)
|
|
658
|
+
// A step may end inside a character; only the leading bytes of a well-formed but unfinished sequence are carried,
|
|
659
|
+
// so bytes that no boundary explains still report invalid UTF-8.
|
|
660
|
+
for (let cut = 0; cut <= (final ? 0 : Math.min(3, joined.length)); cut += 1) {
|
|
661
|
+
const rest = joined.slice(joined.length - cut)
|
|
662
|
+
if (cut > 0 && !unfinishedSequence(rest)) continue
|
|
663
|
+
try {
|
|
664
|
+
return result('text', {
|
|
665
|
+
// Only the stream's first step may start with a byte order mark to drop, as a whole-file read drops it.
|
|
666
|
+
text: new TextDecoder('utf-8', { fatal: true, ignoreBOM: offset - tail.length > 0 }).decode(joined.subarray(0, joined.length - cut)),
|
|
667
|
+
tail: rest,
|
|
668
|
+
})
|
|
669
|
+
} catch (_invalidCut) {
|
|
670
|
+
// A shorter prefix may decode, or the failure is not a character boundary; `cut` grows by one byte.
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
throw fail('FS_NOT_TEXT', `cannot read "${display}": invalid UTF-8 text`)
|
|
674
|
+
}
|
|
675
|
+
case 'bytes': {
|
|
676
|
+
const { path, display, maxBytes } = request
|
|
677
|
+
const info = await statRegular(path, display)
|
|
678
|
+
if (info.size > maxBytes) throw fail('FS_TOO_LARGE', `cannot read "${display}": ${info.size} bytes exceeds the ${maxBytes}-byte limit`)
|
|
679
|
+
await hooks.inspectReadBytesAfterStat?.(path)
|
|
680
|
+
// Reading one byte beyond the bound detects growth after the size check; chunks hold only what the file has.
|
|
681
|
+
const chunks: Uint8Array[] = []
|
|
682
|
+
let total = 0
|
|
683
|
+
try {
|
|
684
|
+
const handle = await fs.open(path, 'r')
|
|
685
|
+
try {
|
|
686
|
+
while (total <= maxBytes) {
|
|
687
|
+
checkAborted('read')
|
|
688
|
+
const chunk = Buffer.allocUnsafe(Math.min(64 * 1024, maxBytes + 1 - total))
|
|
689
|
+
const { bytesRead } = await handle.read(chunk, 0, chunk.length, null)
|
|
690
|
+
if (bytesRead === 0) break
|
|
691
|
+
chunks.push(chunk.subarray(0, bytesRead))
|
|
692
|
+
total += bytesRead
|
|
693
|
+
}
|
|
694
|
+
} finally {
|
|
695
|
+
await handle.close()
|
|
696
|
+
}
|
|
697
|
+
} catch (error) {
|
|
698
|
+
throw classify('read', display, error)
|
|
699
|
+
}
|
|
700
|
+
// A cancellation that arrives while the last read reaches the end still fails the read.
|
|
701
|
+
checkAborted('read')
|
|
702
|
+
if (total > maxBytes) throw fail('FS_TOO_LARGE', `cannot read "${display}": content exceeds the ${maxBytes}-byte limit`)
|
|
703
|
+
const content = new Uint8Array(total)
|
|
704
|
+
let at = 0
|
|
705
|
+
for (const chunk of chunks) {
|
|
706
|
+
content.set(chunk, at)
|
|
707
|
+
at += chunk.length
|
|
708
|
+
}
|
|
709
|
+
return result('bytes', content)
|
|
710
|
+
}
|
|
711
|
+
case 'write': {
|
|
712
|
+
const { path, display, content, expected, basisMaxBytes } = request
|
|
713
|
+
const existing = await writeTarget(path, display, expected)
|
|
714
|
+
const before = existing !== null && typeof content === 'string' && Buffer.byteLength(content, 'utf8') < basisMaxBytes
|
|
715
|
+
? await basis(path, basisMaxBytes)
|
|
716
|
+
: null
|
|
717
|
+
await publish(path, display, content, existing === null ? undefined : Number(existing.mode & 0o777n), {
|
|
718
|
+
createIfAbsent: expected?.kind === 'createIfAbsent',
|
|
719
|
+
})
|
|
720
|
+
return result('write', { operation: existing === null ? 'create' : 'update', version: await versionAfter(path), before })
|
|
721
|
+
}
|
|
722
|
+
case 'edit': {
|
|
723
|
+
const { path, display, edit, expected } = request
|
|
724
|
+
// The guard precedes matching, so an edit based on an old read reports a stale version, not a match failure.
|
|
725
|
+
const existing = await requireFile(path, display, 'edit', expected)
|
|
726
|
+
if (!fits(Number(existing.size))) throw tooLarge('edit', display)
|
|
727
|
+
const { content: before, crlf } = await readForEdit(path, display)
|
|
728
|
+
const after = literalEdit(before, edit, display)
|
|
729
|
+
if (!fits(before.length + after.length)) throw tooLarge('edit', display)
|
|
730
|
+
await publish(path, display, restore(after, crlf), Number(existing.mode & 0o777n))
|
|
731
|
+
return result('edit', { version: await versionAfter(path), before, after })
|
|
732
|
+
}
|
|
733
|
+
case 'load': {
|
|
734
|
+
const { path, display, verb, expected, destination } = request
|
|
735
|
+
const existing = await requireFile(path, display, verb, expected)
|
|
736
|
+
if (destination !== undefined) await writeTarget(destination.path, destination.display, destination.expected)
|
|
737
|
+
if (!fits(Number(existing.size))) throw tooLarge(verb, display)
|
|
738
|
+
return result('load', { ...await readForEdit(path, display), version: versionOf(existing) })
|
|
739
|
+
}
|
|
740
|
+
case 'store': {
|
|
741
|
+
const { path, display, verb, content, crlf, version } = request
|
|
742
|
+
const existing = await requireFile(path, display, verb, version)
|
|
743
|
+
await publish(path, display, restore(content, crlf), Number(existing.mode & 0o777n))
|
|
744
|
+
return result('store', { version: await versionAfter(path) })
|
|
745
|
+
}
|
|
746
|
+
case 'delete': {
|
|
747
|
+
const { path, display, expected, basisMaxBytes } = request
|
|
748
|
+
await requireFile(path, display, 'delete', expected)
|
|
749
|
+
const before = await basis(path, basisMaxBytes)
|
|
750
|
+
await hooks.inspectBeforeMutation?.(path)
|
|
751
|
+
checkAborted('delete')
|
|
752
|
+
const failure = await remove(path, display)
|
|
753
|
+
if (failure !== null) throw fail(failure.code, failure.message, failure.cause)
|
|
754
|
+
return result('delete', { before })
|
|
755
|
+
}
|
|
756
|
+
case 'move': {
|
|
757
|
+
const { source, sourceDisplay, sourceVersion, destination, destinationDisplay, content, crlf, expected, basisMaxBytes } = request
|
|
758
|
+
if (source === destination) throw fail('FS_SAME_TARGET', `cannot move "${sourceDisplay}" to itself`)
|
|
759
|
+
const sourceInfo = await requireFile(source, sourceDisplay, 'move', sourceVersion)
|
|
760
|
+
if (env.sandbox !== undefined && !(await env.sandbox.canWrite(source))) {
|
|
761
|
+
throw fail('FS_SANDBOX_DENIED', `cannot move "${sourceDisplay}": file access denied under ${env.sandbox.mode} mode`)
|
|
762
|
+
}
|
|
763
|
+
const existing = await writeTarget(destination, destinationDisplay, expected)
|
|
764
|
+
const stored = restore(content, crlf)
|
|
765
|
+
const before = existing !== null && Buffer.byteLength(stored, 'utf8') < basisMaxBytes ? await basis(destination, basisMaxBytes) : null
|
|
766
|
+
await hooks.inspectBeforeMutation?.(source)
|
|
767
|
+
checkAborted('move')
|
|
768
|
+
// After this checkpoint both effects complete and are reported, even if cancellation arrives.
|
|
769
|
+
await publish(destination, destinationDisplay, stored, Number(sourceInfo.mode & 0o777n), {
|
|
770
|
+
createIfAbsent: expected?.kind === 'createIfAbsent', existingDestination: existing !== null, cancellable: false,
|
|
771
|
+
})
|
|
772
|
+
const operation = existing === null ? 'create' : 'update'
|
|
773
|
+
const version = await versionAfter(destination)
|
|
774
|
+
const failure = await remove(source, sourceDisplay)
|
|
775
|
+
const sourceFailure = failure === null ? null : { code: failure.code, message: failure.message }
|
|
776
|
+
return result('move', { operation, version, before, sourceFailure })
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
/**
|
|
782
|
+
* The `FsError` for a failure of {@link fileOperation}; a failure without an `FS_*` code is a defect and is returned
|
|
783
|
+
* unchanged.
|
|
784
|
+
* @param error - the caught value.
|
|
785
|
+
* @returns the typed failure, keeping the original `cause`.
|
|
786
|
+
*/
|
|
787
|
+
export function fileOperationError(error: unknown): unknown {
|
|
788
|
+
if (error instanceof FsError || !(error instanceof Error)) return error
|
|
789
|
+
const code = FS_ERROR_CODES.find(known => known === (error as { code?: unknown }).code)
|
|
790
|
+
if (code === undefined) return error
|
|
791
|
+
return new FsError(error.message, code, error.cause === undefined ? undefined : { cause: error.cause })
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
/** Runs one {@link fileOperation} on some machine; every filesystem failure rejects as an `FsError`. */
|
|
795
|
+
export type FileOperationRunner = <R extends FileOperationRequest>(request: R, signal?: AbortSignal) => Promise<FileOperationResults[R['op']]>
|
|
796
|
+
|
|
797
|
+
/** The `FileSystem` operations built on a {@link FileOperationRunner}. */
|
|
798
|
+
export type SharedFileOperations = Pick<FileSystem,
|
|
799
|
+
| 'resolve' | 'processPath' | 'stat' | 'lstat' | 'readText' | 'readBytes' | 'listDir'
|
|
800
|
+
| 'writeText' | 'writeBytes' | 'editText' | 'patchText' | 'deleteFile' | 'moveFile'>
|
|
801
|
+
|
|
802
|
+
/**
|
|
803
|
+
* The `FileSystem` operations of one machine. Patch hunks apply in the calling process between a `load` and a
|
|
804
|
+
* `store` (or `move`) guarded by the loaded version, so a file that changes in between fails `FS_STALE_VERSION`.
|
|
805
|
+
* @param run - runs one operation on the machine.
|
|
806
|
+
* @param options - `keyOf` and `pathOf` convert between a realpath and a target key; `cwd` is the default directory of
|
|
807
|
+
* relative paths (undefined: the machine's); `expandPath` rewrites a requested path first; `basisMaxBytes` bounds
|
|
808
|
+
* each diff basis; `maxTextUnits` bounds, in UTF-16 units, the loaded text plus its patched text for a patch or a
|
|
809
|
+
* move with hunks (`FS_TOO_LARGE`), as an execution environment's connection requires.
|
|
810
|
+
* @returns the operations; mutations hold no locks of their own.
|
|
811
|
+
*/
|
|
812
|
+
export function fileOperations(run: FileOperationRunner, options: {
|
|
813
|
+
readonly keyOf: (real: string) => string
|
|
814
|
+
readonly pathOf: (target: FsTarget) => string
|
|
815
|
+
readonly cwd: string | undefined
|
|
816
|
+
readonly expandPath?: (path: string) => string
|
|
817
|
+
readonly basisMaxBytes: number
|
|
818
|
+
readonly maxTextUnits?: number
|
|
819
|
+
}): SharedFileOperations {
|
|
820
|
+
const { keyOf, pathOf, basisMaxBytes } = options
|
|
821
|
+
const expand = options.expandPath ?? (path => path)
|
|
822
|
+
const checked = async <T>(verb: string, signal: AbortSignal | undefined, operation: () => Promise<T>): Promise<T> => {
|
|
823
|
+
const abort = (): void => { if (signal?.aborted === true) throw new FsError(`${verb} aborted`, 'FS_ABORTED') }
|
|
824
|
+
abort()
|
|
825
|
+
const result = await operation()
|
|
826
|
+
abort()
|
|
827
|
+
return result
|
|
828
|
+
}
|
|
829
|
+
const metadata = (info: FileOperationInfo) => ({ version: FsVersion(info.version), type: info.type, size: info.size })
|
|
830
|
+
const patched = (target: FsTarget, content: string, hunks: readonly PatchHunk[] | undefined): string => {
|
|
831
|
+
if (hunks === undefined) return content
|
|
832
|
+
const result = applyHunks(content, hunks)
|
|
833
|
+
if (!result.ok) {
|
|
834
|
+
throw new FsError(`cannot patch "${target.displayPath}": hunk at patch line ${result.failure.hunkLineNumber} (${result.failure.stage}) does not match`, 'FS_PATCH_MISMATCH')
|
|
835
|
+
}
|
|
836
|
+
if (options.maxTextUnits !== undefined && content.length + result.after.length > options.maxTextUnits) {
|
|
837
|
+
throw new FsError(`cannot patch "${target.displayPath}": larger than the environment connection carries`, 'FS_TOO_LARGE')
|
|
838
|
+
}
|
|
839
|
+
return result.after
|
|
840
|
+
}
|
|
841
|
+
const bounded = (text: string): string | null => Buffer.byteLength(text, 'utf8') < basisMaxBytes ? text : null
|
|
842
|
+
const cwdOf = (cwd: string | undefined): string | undefined => cwd ?? options.cwd
|
|
843
|
+
return {
|
|
844
|
+
async resolve(path, opts) {
|
|
845
|
+
const { display, real } = await checked(
|
|
846
|
+
'resolve', opts?.signal, () => run({ op: 'resolve', path: expand(path), cwd: cwdOf(opts?.cwd) }, opts?.signal),
|
|
847
|
+
)
|
|
848
|
+
return { targetKey: FsTargetKey(keyOf(real)), displayPath: display }
|
|
849
|
+
},
|
|
850
|
+
processPath: pathOf,
|
|
851
|
+
async stat(target, signal) {
|
|
852
|
+
const info = await checked('stat', signal, () => run({ op: 'stat', path: pathOf(target) }, signal))
|
|
853
|
+
// `stat` follows links, so the type is never a link.
|
|
854
|
+
return info === null ? undefined : { ...metadata(info), type: info.type as 'file' | 'directory' | 'other' }
|
|
855
|
+
},
|
|
856
|
+
async lstat(path, opts, signal) {
|
|
857
|
+
const info = await checked('lstat', signal, () => run({ op: 'lstat', path: expand(path), cwd: cwdOf(opts?.cwd) }, signal))
|
|
858
|
+
return info === null ? undefined : metadata(info)
|
|
859
|
+
},
|
|
860
|
+
readText: (target, signal) => run({ op: 'read', path: pathOf(target), display: target.displayPath }, signal),
|
|
861
|
+
readBytes: (target, signal, maxBytes) => run({ op: 'bytes', path: pathOf(target), display: target.displayPath, maxBytes }, signal),
|
|
862
|
+
async listDir(target, signal): Promise<FsDirEntry[]> {
|
|
863
|
+
const entries = await run({ op: 'list', path: pathOf(target), display: target.displayPath }, signal)
|
|
864
|
+
return entries.map(({ name, display, real, info }) => ({
|
|
865
|
+
name,
|
|
866
|
+
type: (info?.type ?? 'other') as FsDirEntry['type'],
|
|
867
|
+
target: { targetKey: FsTargetKey(keyOf(real)), displayPath: display },
|
|
868
|
+
...info === null ? {} : { version: FsVersion(info.version) },
|
|
869
|
+
...info?.type === 'file' ? { size: info.size } : {},
|
|
870
|
+
}))
|
|
871
|
+
},
|
|
872
|
+
async writeText(target, content, expected, signal) {
|
|
873
|
+
const outcome = await run({ op: 'write', path: pathOf(target), display: target.displayPath, content, expected, basisMaxBytes }, signal)
|
|
874
|
+
// LF-normalized to share the diff basis with `before`: a CRLF overwrite must not read as every line changed.
|
|
875
|
+
return { ...outcome, version: FsVersion(outcome.version), after: content.replaceAll('\r\n', '\n') }
|
|
876
|
+
},
|
|
877
|
+
async writeBytes(target, data, expected, signal) {
|
|
878
|
+
const outcome = await run({ op: 'write', path: pathOf(target), display: target.displayPath, content: data, expected, basisMaxBytes: 0 }, signal)
|
|
879
|
+
return { operation: outcome.operation, version: FsVersion(outcome.version) }
|
|
880
|
+
},
|
|
881
|
+
async editText(target, edit, expected, signal) {
|
|
882
|
+
const outcome = await run({ op: 'edit', path: pathOf(target), display: target.displayPath, edit, expected: expected?.version }, signal)
|
|
883
|
+
return { ...outcome, version: FsVersion(outcome.version) }
|
|
884
|
+
},
|
|
885
|
+
async patchText(target, hunks, expected, signal) {
|
|
886
|
+
const loaded = await run({ op: 'load', path: pathOf(target), display: target.displayPath, verb: 'patch', expected: expected?.version }, signal)
|
|
887
|
+
const after = patched(target, loaded.content, hunks)
|
|
888
|
+
const stored = await run({
|
|
889
|
+
op: 'store', path: pathOf(target), display: target.displayPath, verb: 'patch', content: after, crlf: loaded.crlf, version: loaded.version,
|
|
890
|
+
}, signal)
|
|
891
|
+
return { version: FsVersion(stored.version), before: loaded.content, after }
|
|
892
|
+
},
|
|
893
|
+
deleteFile: (target, expected, signal) =>
|
|
894
|
+
run({ op: 'delete', path: pathOf(target), display: target.displayPath, expected: expected?.version, basisMaxBytes }, signal),
|
|
895
|
+
async moveFile(source, destination, moveOptions, signal) {
|
|
896
|
+
if (source.targetKey === destination.targetKey) throw new FsError(`cannot move "${source.displayPath}" to itself`, 'FS_SAME_TARGET')
|
|
897
|
+
const loaded = await run({
|
|
898
|
+
op: 'load', path: pathOf(source), display: source.displayPath, verb: 'move', expected: moveOptions.expectedSource?.version,
|
|
899
|
+
destination: { path: pathOf(destination), display: destination.displayPath, expected: moveOptions.expectedDestination },
|
|
900
|
+
}, signal)
|
|
901
|
+
const after = patched(source, loaded.content, moveOptions.hunks)
|
|
902
|
+
const moved = await run({
|
|
903
|
+
op: 'move', source: pathOf(source), sourceDisplay: source.displayPath, sourceVersion: loaded.version,
|
|
904
|
+
destination: pathOf(destination), destinationDisplay: destination.displayPath, content: after, crlf: loaded.crlf,
|
|
905
|
+
expected: moveOptions.expectedDestination, basisMaxBytes,
|
|
906
|
+
}, signal)
|
|
907
|
+
const outcome = { operation: moved.operation, version: FsVersion(moved.version), before: moved.before, after }
|
|
908
|
+
const sourceBefore = bounded(loaded.content)
|
|
909
|
+
if (moved.sourceFailure === null) return { sourceBefore, destination: outcome, sourceDeleted: true }
|
|
910
|
+
return { sourceBefore, destination: outcome, sourceDeleted: false, sourceFailure: moved.sourceFailure }
|
|
911
|
+
},
|
|
912
|
+
}
|
|
913
|
+
}
|