diff --git a/src/clients/fs/FileSystemAccessApiFsClient.ts b/src/clients/fs/FileSystemAccessApiFsClient.ts index 9baa942..a31c5c0 100644 --- a/src/clients/fs/FileSystemAccessApiFsClient.ts +++ b/src/clients/fs/FileSystemAccessApiFsClient.ts @@ -124,6 +124,14 @@ const DefaultFileSystemAccessApiClientOptions: FileSystemAccessApiClientOptions * ``` */ export class FileSystemAccessApiFsClient implements FsClient { + /** + * Set once `move()` has been rejected with `NotAllowedError`, so later renames + * go straight to the copy fallback instead of failing first every time. + * Shared by all instances, since it reflects what the browser supports. + * @internal + */ + static moveNotAllowed = false + private readonly textEncoder = new TextEncoder() private directoryHandlesCache = new Map() private readonly options: FileSystemAccessApiClientOptions @@ -274,10 +282,19 @@ export class FileSystemAccessApiFsClient implements FsClient { // Strategy 1: Native move() — zero-copy rename, supported in Chrome and Safari OPFS. // Always pass (directory, newName) form — Safari doesn't support the move(newName) shorthand. - if (typeof fileHandle.move === 'function') { + if (typeof fileHandle.move === 'function' && !FileSystemAccessApiFsClient.moveNotAllowed) { const newDir = oldFolder === newFolder ? oldDir : await this.getDirectoryByPath(newFolder) - await fileHandle.move(newDir, newName) - return + try { + await fileHandle.move(newDir, newName) + return + } catch (error) { + // Chromium 124 and older (including Android WebViews that can't be updated) expose move() + // but reject every call with NotAllowedError. Remember that and fall back to copying. + if (!(error instanceof DOMException && error.name === ErrorNames.NotAllowedError)) { + throw error + } + FileSystemAccessApiFsClient.moveNotAllowed = true + } } // Strategy 2: Streaming copy — read in chunks, write via stream. Never loads entire file. diff --git a/tests/FileSystemAccessApiFsClient.test.ts b/tests/FileSystemAccessApiFsClient.test.ts new file mode 100644 index 0000000..a6c1987 --- /dev/null +++ b/tests/FileSystemAccessApiFsClient.test.ts @@ -0,0 +1,93 @@ +import { FileSystemAccessApiFsClient } from 'git-essentials/clients/fs/FileSystemAccessApiFsClient' + +import { expectToFailAsync } from './helpers/assertionHelper' +import { FakeDirectoryHandle, FakeFileHandle, MoveBehavior, makeFakeOpfsRoot } from './helpers/fakeOpfs' + +describe('FileSystemAccessApiFsClient', () => { + beforeEach(() => { + FileSystemAccessApiFsClient.moveNotAllowed = false + }) + + async function setup(moveBehavior: MoveBehavior) { + const root = makeFakeOpfsRoot(moveBehavior) + const fs = new FileSystemAccessApiFsClient(root as unknown as FileSystemDirectoryHandle) + await fs.mkdir('/repo') + await fs.mkdir('/repo/pack') + await fs.writeFile('/repo/tmp.pack', 'pack data') + const repoDir = root.entries.get('repo') as FakeDirectoryHandle + return { fs, repoDir } + } + + describe('rename', () => { + it('moves a file with move() when the browser allows it', async () => { + // arrange + const { fs, repoDir } = await setup('supported') + const handle = repoDir.entries.get('tmp.pack') as FakeFileHandle + + // act + await fs.rename('/repo/tmp.pack', '/repo/pack/pack-1.pack') + + // assert + expect(handle.moveCalls).toBe(1) + expect(await fs.exists('/repo/tmp.pack')).toBe(false) + expect(await fs.readFile('/repo/pack/pack-1.pack', { encoding: 'utf8' })).toBe('pack data') + expect(FileSystemAccessApiFsClient.moveNotAllowed).toBe(false) + }) + + it('copies the file when move() is rejected with NotAllowedError', async () => { + // arrange + const { fs, repoDir } = await setup('notAllowed') + const handle = repoDir.entries.get('tmp.pack') as FakeFileHandle + + // act + await fs.rename('/repo/tmp.pack', '/repo/pack/pack-1.pack') + + // assert + expect(handle.moveCalls).toBe(1) + expect(await fs.exists('/repo/tmp.pack')).toBe(false) + expect(await fs.readFile('/repo/pack/pack-1.pack', { encoding: 'utf8' })).toBe('pack data') + expect(FileSystemAccessApiFsClient.moveNotAllowed).toBe(true) + }) + + it('skips move() on later renames once it was rejected', async () => { + // arrange + const { fs, repoDir } = await setup('notAllowed') + await fs.rename('/repo/tmp.pack', '/repo/pack/pack-1.pack') + await fs.writeFile('/repo/tmp2.pack', 'more data') + const secondHandle = repoDir.entries.get('tmp2.pack') as FakeFileHandle + + // act + await fs.rename('/repo/tmp2.pack', '/repo/pack/pack-2.pack') + + // assert + expect(secondHandle.moveCalls).toBe(0) + expect(await fs.readFile('/repo/pack/pack-2.pack', { encoding: 'utf8' })).toBe('more data') + }) + + it('copies the file when move() is missing', async () => { + // arrange + const { fs } = await setup('missing') + + // act + await fs.rename('/repo/tmp.pack', '/repo/pack/pack-1.pack') + + // assert + expect(await fs.exists('/repo/tmp.pack')).toBe(false) + expect(await fs.readFile('/repo/pack/pack-1.pack', { encoding: 'utf8' })).toBe('pack data') + }) + + it('rethrows other move() errors', async () => { + // arrange + const { fs, repoDir } = await setup('supported') + const handle = repoDir.entries.get('tmp.pack') as FakeFileHandle + handle.move = async () => { throw new DOMException('locked', 'NoModificationAllowedError') } + + // act & assert + await expectToFailAsync( + () => fs.rename('/repo/tmp.pack', '/repo/pack/pack-1.pack'), + (err) => err.name === 'NoModificationAllowedError') + expect(await fs.exists('/repo/tmp.pack')).toBe(true) + expect(FileSystemAccessApiFsClient.moveNotAllowed).toBe(false) + }) + }) +}) diff --git a/tests/helpers/fakeOpfs.ts b/tests/helpers/fakeOpfs.ts new file mode 100644 index 0000000..356f6bb --- /dev/null +++ b/tests/helpers/fakeOpfs.ts @@ -0,0 +1,120 @@ +/** + * A small in-memory stand-in for the Origin Private File System handles, + * enough to drive `FileSystemAccessApiFsClient` under Node. + */ + +export type MoveBehavior = 'supported' | 'notAllowed' | 'missing' + +function domError(name: string, message = name) { + return new DOMException(message, name) +} + +export class FakeFileHandle { + readonly kind = 'file' + data = new Uint8Array() + lastModified = Date.now() + moveCalls = 0 + move?: (directory: FakeDirectoryHandle, newName: string) => Promise + + constructor(public name: string, public parent: FakeDirectoryHandle, moveBehavior: MoveBehavior) { + if (moveBehavior !== 'missing') { + this.move = async (directory: FakeDirectoryHandle, newName: string) => { + this.moveCalls++ + if (moveBehavior === 'notAllowed') { + // Matches what Chromium 114 to 124 throw for every move() call in OPFS. + throw domError('NotAllowedError', 'The request is not allowed by the user agent or the platform in the current context.') + } + this.parent.entries.delete(this.name) + this.name = newName + this.parent = directory + directory.entries.set(newName, this) + } + } + } + + async getFile() { + return new File([this.data], this.name, { lastModified: this.lastModified }) + } + + async createWritable() { + const chunks: Uint8Array[] = [] + return { + write: async (data: string | Uint8Array) => { + chunks.push(typeof data === 'string' ? new TextEncoder().encode(data) : new Uint8Array(data)) + }, + close: async () => { + const size = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0) + const result = new Uint8Array(size) + let offset = 0 + for (const chunk of chunks) { + result.set(chunk, offset) + offset += chunk.byteLength + } + this.data = result + this.lastModified = Date.now() + } + } + } +} + +export class FakeDirectoryHandle { + readonly kind = 'directory' + readonly entries = new Map() + + constructor(public name: string, private readonly moveBehavior: MoveBehavior) {} + + async getDirectoryHandle(name: string, options: { create?: boolean } = {}) { + const entry = this.entries.get(name) + if (entry instanceof FakeDirectoryHandle) { + return entry + } + if (entry) { + throw domError('TypeMismatchError') + } + if (!options.create) { + throw domError('NotFoundError') + } + const directory = new FakeDirectoryHandle(name, this.moveBehavior) + this.entries.set(name, directory) + return directory + } + + async getFileHandle(name: string, options: { create?: boolean } = {}) { + const entry = this.entries.get(name) + if (entry instanceof FakeFileHandle) { + return entry + } + if (entry) { + throw domError('TypeMismatchError') + } + if (!options.create) { + throw domError('NotFoundError') + } + const file = new FakeFileHandle(name, this, this.moveBehavior) + this.entries.set(name, file) + return file + } + + async removeEntry(name: string, options: { recursive?: boolean } = {}) { + const entry = this.entries.get(name) + if (!entry) { + throw domError('NotFoundError') + } + if (entry instanceof FakeDirectoryHandle && entry.entries.size > 0 && !options.recursive) { + throw domError('InvalidModificationError') + } + this.entries.delete(name) + } + + async *keys() { + yield* this.entries.keys() + } + + async *values() { + yield* this.entries.values() + } +} + +export function makeFakeOpfsRoot(moveBehavior: MoveBehavior) { + return new FakeDirectoryHandle('', moveBehavior) +}