-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathLocalFileSystem.ts
More file actions
258 lines (181 loc) · 7.04 KB
/
Copy pathLocalFileSystem.ts
File metadata and controls
258 lines (181 loc) · 7.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
import { basename, parse, resolve, sep } from 'pathe'
import { BaseEntry, BaseFileSystem, StreamableLike } from './BaseFileSystem'
import { del, get, keys, set } from 'idb-keyval'
import * as JSONC from 'jsonc-parser'
export class LocalFileSystem extends BaseFileSystem {
private textEncoder = new TextEncoder()
private textDecoder = new TextDecoder()
private rootName: string | null = null
private pathsToWatch: string[] = []
public setRootName(name: string) {
this.rootName = name
}
public async readFile(path: string): Promise<ArrayBuffer> {
if (this.rootName === null) throw new Error('Root name not set')
path = resolve('/', path)
const data = (await get(`localFileSystem/${this.rootName}${path}`)).content
// @ts-ignore TS being weird about errors
if (data instanceof Uint8Array) return data.buffer
// @ts-ignore array buffer yes....
return this.textEncoder.encode(data).buffer
}
public async readFileText(path: string): Promise<string> {
if (this.rootName === null) throw new Error('Root name not set')
path = resolve('/', path)
try {
const content = (await get(`localFileSystem/${this.rootName}${path}`)).content
if (typeof content === 'string') return content
return this.textDecoder.decode(new Uint8Array(content))
} catch (error) {
console.error(`Failed to read file text "${path}"`)
throw error
}
}
public async readFileJson(path: string): Promise<any> {
path = resolve('/', path)
return JSONC.parse(await this.readFileText(path))
}
public async readFileDataUrl(path: string): Promise<string> {
if (this.rootName === null) throw new Error('Root name not set')
path = resolve('/', path)
try {
const content = (await get(`localFileSystem/${this.rootName}${path}`)).content
if (typeof content === 'string') throw new Error('Reading string as Data Url is not supported yet!')
const file = new File([new Blob([new Uint8Array(content)])], basename(path))
const reader = new FileReader()
return new Promise((resolve) => {
reader.onload = () => {
resolve(reader.result as string)
}
reader.readAsDataURL(file)
})
} catch (error) {
console.error(`Failed to read file as data Url "${path}"`)
throw error
}
}
public async writeFile(path: string, content: FileSystemWriteChunkType) {
if (this.rootName === null) throw new Error('Root name not set')
path = resolve('/', path)
await set(`localFileSystem/${this.rootName}${path}`, {
kind: 'file',
content,
})
if (
this.pathsToWatch.find((watchPath) => path.startsWith(watchPath)) !== undefined &&
this.watchPathsToIgnore.find((watchPath) => path.startsWith(watchPath)) === undefined
)
this.pathUpdated.dispatch(path)
}
public async writeFileStreaming(path: string, stream: StreamableLike) {
if (this.rootName === null) throw new Error('Root name not set')
path = resolve('/', path)
const chunks: Uint8Array[] = []
let totalLength = 0
await new Promise<void>((resolve) => {
stream.ondata = (error, data, final) => {
chunks.push(data)
totalLength += data.length
if (final) resolve()
}
stream.start()
})
const content = new Uint8Array(totalLength)
let writePosition = 0
for (const chunk of chunks) {
content.set(chunk, writePosition)
writePosition += chunk.length
}
await set(`localFileSystem/${this.rootName}${path}`, {
kind: 'file',
content,
})
if (
this.pathsToWatch.find((watchPath) => path.startsWith(watchPath)) !== undefined &&
this.watchPathsToIgnore.find((watchPath) => path.startsWith(watchPath)) === undefined
)
this.pathUpdated.dispatch(path)
}
public async removeFile(path: string) {
if (this.rootName === null) throw new Error('Root name not set')
path = resolve('/', path)
await del(`localFileSystem/${this.rootName}${path}`)
if (
this.pathsToWatch.find((watchPath) => path.startsWith(watchPath)) !== undefined &&
this.watchPathsToIgnore.find((watchPath) => path.startsWith(watchPath)) === undefined
)
this.pathUpdated.dispatch(path)
}
public async makeDirectory(path: string) {
if (this.rootName === null) throw new Error('Root name not set')
path = resolve('/', path)
await set(`localFileSystem/${this.rootName}${path}`, {
kind: 'directory',
})
if (
this.pathsToWatch.find((watchPath) => path.startsWith(watchPath)) !== undefined &&
this.watchPathsToIgnore.find((watchPath) => path.startsWith(watchPath)) === undefined
)
this.pathUpdated.dispatch(path)
}
public async removeDirectory(path: string) {
if (this.rootName === null) throw new Error('Root name not set')
path = resolve('/', path)
// Remove the directory entry itself as well as every file and subdirectory nested inside of it.
// idb-keyval has no concept of folders, so deleting only the directory key would orphan its children.
const directoryKey = `localFileSystem/${this.rootName}${path}`
const childPrefix = `${directoryKey}/`
const childKeys = (await keys()).filter((key) => key.toString().startsWith(childPrefix))
await Promise.all([del(directoryKey), ...childKeys.map((key) => del(key))])
if (
this.pathsToWatch.find((watchPath) => path.startsWith(watchPath)) !== undefined &&
this.watchPathsToIgnore.find((watchPath) => path.startsWith(watchPath)) === undefined
)
this.pathUpdated.dispatch(path)
}
public async ensureDirectory(path: string): Promise<void> {
if (this.rootName === null) throw new Error('Root name not set')
path = resolve('/', path)
const directoryNames = parse(path).dir.split(sep)
if (directoryNames[0] === '' || directoryNames[0] === '.') directoryNames.shift()
let currentPath = ''
for (const directoryName of directoryNames) {
currentPath += '/' + directoryName
if (!(await this.exists(currentPath))) await this.makeDirectory(currentPath)
}
}
public async exists(path: string): Promise<boolean> {
if (this.rootName === null) throw new Error('Root name not set')
path = resolve('/', path)
return (await get(`localFileSystem/${this.rootName}${path}`)) !== undefined
}
public async allEntries(): Promise<string[]> {
if (this.rootName === null) throw new Error('Root name not set')
const allKeys = await keys()
const localFSKeys = allKeys
.map((key) => key.toString())
.filter((key) => key.startsWith(`localFileSystem/${this.rootName}/`))
.map((key) => key.substring(`localFileSystem/${this.rootName}`.length))
return localFSKeys
}
public async readDirectoryEntries(path: string): Promise<BaseEntry[]> {
if (this.rootName === null) throw new Error('Root name not set')
path = resolve('/', path)
const allEntries = await this.allEntries()
const entries = allEntries.filter((entry) => parse(entry).dir === path)
return Promise.all(
entries.map(async (entryPath) => {
const entry = await get(`localFileSystem/${this.rootName}${entryPath}`)
return new BaseEntry(entryPath, entry.kind)
})
)
}
public async watch(path: string) {
path = resolve('/', path)
this.pathsToWatch.push(path)
}
public async unwatch(path: string) {
path = resolve('/', path)
this.pathsToWatch.splice(this.pathsToWatch.indexOf(path), 1)
}
}