feat: support in-memory template mapping, inspired by @jg-rp #714

This commit is contained in:
Harttle
2024-07-08 02:25:25 +08:00
parent 834328b9cb
commit df27ac6947
5 changed files with 115 additions and 0 deletions
+17
View File
@@ -0,0 +1,17 @@
import { MapFS } from './map-fs'
describe('MapFS', () => {
const fs = new MapFS({})
it('should resolve relative file paths', () => {
expect(fs.resolve('foo/bar', 'coo', '')).toEqual('foo/bar/coo')
})
it('should resolve to parent', () => {
expect(fs.resolve('foo/bar', '../coo', '')).toEqual('foo/coo')
})
it('should resolve to root', () => {
expect(fs.resolve('foo/bar', '../../coo', '')).toEqual('coo')
})
it('should resolve exceeding root', () => {
expect(fs.resolve('foo/bar', '../../../coo', '')).toEqual('coo')
})
})
+43
View File
@@ -0,0 +1,43 @@
import { isNil } from '../util'
export class MapFS {
constructor (private mapping: {[key: string]: string}) {}
public sep = '/'
async exists (filepath: string) {
return this.existsSync(filepath)
}
existsSync (filepath: string) {
return !isNil(this.mapping[filepath])
}
async readFile (filepath: string) {
return this.readFileSync(filepath)
}
readFileSync (filepath: string) {
const content = this.mapping[filepath]
if (isNil(content)) throw new Error(`ENOENT: ${filepath}`)
return content
}
dirname (filepath: string) {
const segments = filepath.split(this.sep)
segments.pop()
return segments.join(this.sep)
}
resolve (dir: string, file: string, ext: string) {
file += ext
if (dir === '.') return file
const segments = dir.split(this.sep)
for (const segment of file.split(this.sep)) {
if (segment === '.' || segment === '') continue
else if (segment === '..') segments.pop()
else segments.push(segment)
}
return segments.join(this.sep)
}
}