-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLocalStorageFileSystem.js
130 lines (116 loc) · 2.96 KB
/
LocalStorageFileSystem.js
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
import DummyFsWatcher from "./DummyFsWatcher.js";
import {fileUtil} from "@spyglassmc/core";
import Base64 from "../Util/Base64.js";
/**
* @implements {import("@spyglassmc/core").ExternalFileSystem}
*/
export default class LocalStorageFileSystem {
static KEY_PREFIX = 'spyglassmc-browser-fs';
/** @type {Object} */ states;
/** @type {string} */ id;
/**
* @param {string} id
*/
constructor(id) {
this.id = id;
this.states = JSON.parse(localStorage.getItem(this.getKey()) ?? '{}');
}
/**
* Save the states to local storage
*/
saveStates() {
localStorage.setItem(this.getKey(), JSON.stringify(this.states));
}
/**
* Get the key for the states in local storage
*
* @return {string}
*/
getKey() {
return `${this.constructor.KEY_PREFIX}-${this.id}`;
}
/**
* @inheritDoc
*/
async chmod(_location, _mode) {
}
/**
* @inheritDoc
*/
async mkdir(location, _options) {
location = fileUtil.ensureEndingSlash(location.toString());
if (this.states[location]) {
throw new Error(`EEXIST: ${location}`);
}
this.states[location] = { type: 'directory' };
this.saveStates();
}
/**
* @inheritDoc
*/
async readdir(_location) {
// Not implemented
return [];
}
/**
* @inheritDoc
*/
async readFile(location) {
location = location.toString();
let entry = this.states[location];
if (!entry) {
throw new Error(`ENOENT: ${location}`);
}
else if (entry.type === 'directory') {
throw new Error(`EISDIR: ${location}`);
}
return Base64.decode(entry.content);
}
/**
* @inheritDoc
*/
async showFile(_path) {
throw new Error('showFile not supported on browser');
}
/**
* @inheritDoc
*/
async stat(location) {
location = location.toString();
let entry = this.states[location];
if (!entry) {
throw new Error(`ENOENT: ${location}`);
}
return { isDirectory: () => entry.type === 'directory', isFile: () => entry.type === 'file' };
}
/**
* @inheritDoc
*/
async unlink(location) {
location = location.toString();
let entry = this.states[location];
if (!entry) {
throw new Error(`ENOENT: ${location}`);
}
delete this.states[location];
this.saveStates();
}
/**
* @inheritDoc
*/
watch(_locations) {
return new DummyFsWatcher();
}
/**
* @inheritDoc
*/
async writeFile(location, data, _options) {
location = location.toString();
if (typeof data === 'string') {
data = new TextEncoder().encode(data);
}
data = Base64.encode(data);
this.states[location] = { type: 'file', content: data };
this.saveStates();
}
}