-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathBrowserFileSystem.ts
More file actions
107 lines (82 loc) · 2.89 KB
/
BrowserFileSystem.ts
File metadata and controls
107 lines (82 loc) · 2.89 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
import { BacktraceAttachment, BacktraceStringAttachment, FileSystem } from '@backtrace/sdk-core';
const PREFIX = 'backtrace__';
export class BrowserFileSystem implements FileSystem {
constructor(private readonly _storage = window.localStorage) {}
public async readDir(dir: string): Promise<string[]> {
return this.readDirSync(dir);
}
public readDirSync(dir: string): string[] {
dir = this.resolvePath(this.ensureTrailingSlash(dir));
const result: string[] = [];
for (const key in this._storage) {
if (key.startsWith(dir)) {
result.push(key.substring(dir.length));
}
}
return result;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public async createDir(_dir: string): Promise<void> {
return;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public createDirSync(_dir: string): void {
return;
}
public async readFile(path: string): Promise<string> {
return this.readFileSync(path);
}
public readFileSync(path: string): string {
const result = this._storage.getItem(this.resolvePath(path));
if (!result) {
throw new Error('path does not exist');
}
return result;
}
public async writeFile(path: string, content: string): Promise<void> {
return this.writeFileSync(path, content);
}
public writeFileSync(path: string, content: string): void {
this._storage.setItem(this.resolvePath(path), content);
}
public async unlink(path: string): Promise<void> {
return this.unlinkSync(path);
}
public unlinkSync(path: string): void {
this._storage.removeItem(this.resolvePath(path));
}
public async exists(path: string): Promise<boolean> {
return this.existsSync(path);
}
public existsSync(path: string): boolean {
return this.resolvePath(path) in this._storage;
}
public createAttachment(path: string, name?: string): BacktraceAttachment {
return new BacktraceStringAttachment(name ?? this.basename(path), this.readFileSync(path));
}
private resolvePath(key: string) {
return PREFIX + this.ensureLeadingSlash(key);
}
private basename(path: string) {
const lastSlashIndex = path.lastIndexOf('/');
return lastSlashIndex === -1 ? path : path.substring(lastSlashIndex + 1);
}
private ensureLeadingSlash(path: string) {
if (path === '/') {
return '/';
}
while (path.startsWith('/')) {
path = path.substring(1);
}
return '/' + path;
}
private ensureTrailingSlash(path: string) {
if (path === '/') {
return path;
}
while (path.endsWith('/')) {
path = path.substring(0, path.length - 1);
}
return path + '/';
}
}