forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodeSandboxEditorFS.ts
More file actions
335 lines (271 loc) · 8.15 KB
/
CodeSandboxEditorFS.ts
File metadata and controls
335 lines (271 loc) · 8.15 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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
import { ApiError, ErrorCode } from '../core/api_error';
import { File } from '../core/file';
import { FileFlag } from '../core/file_flag';
/* eslint-disable */
import {
BFSCallback,
BFSOneArgCallback,
FileSystem,
FileSystemOptions,
SynchronousFileSystem,
} from '../core/file_system';
import { FileType, default as Stats } from '../core/node_fs_stats';
import PreloadFile from '../generic/preload_file';
function blobToBuffer(blob: Blob, cb: (err: any | undefined | null, result?: Buffer) => void) {
if (typeof Blob === 'undefined' || !(blob instanceof Blob)) {
throw new Error('first argument must be a Blob');
}
if (typeof cb !== 'function') {
throw new Error('second argument must be a function');
}
const reader = new FileReader();
function onLoadEnd(e: any) {
reader.removeEventListener('loadend', onLoadEnd, false);
if (e.error) {
cb(e.error);
} else {
// @ts-ignore
cb(null, Buffer.from(reader.result));
}
}
reader.addEventListener('loadend', onLoadEnd, false);
reader.readAsArrayBuffer(blob);
}
export interface IModule {
path: string;
updatedAt: string;
insertedAt: string;
}
export type IFile = IModule & {
code: string | undefined;
savedCode: string | null;
isBinary: boolean;
type: 'file';
}
export type IDirectory = IModule & {
type: 'directory';
}
export interface IManager {
getSandboxFs: () => {
[path: string]: IFile | IDirectory;
};
}
function getCode(savedCode: string | null | undefined, code: string | undefined) {
if (savedCode === null) {
return code || '';
}
return savedCode || '';
}
class CodeSandboxFile extends PreloadFile<CodeSandboxEditorFS> implements File {
constructor(
_fs: CodeSandboxEditorFS,
_path: string,
_flag: FileFlag,
_stat: Stats,
contents?: Buffer
) {
super(_fs, _path, _flag, _stat, contents);
}
public sync(cb: BFSOneArgCallback): void {
if (this.isDirty()) {
const buffer = this.getBuffer();
this._fs._sync(
this.getPath(),
buffer,
(e: ApiError | undefined | null, stat?: Stats) => {
if (!e) {
this.resetDirty();
}
cb(e);
}
);
} else {
cb();
}
}
public close(cb: BFSOneArgCallback): void {
this.sync(cb);
}
public syncSync(): void {
if (this.isDirty()) {
this._fs._syncSync(this.getPath(), this.getBuffer());
this.resetDirty();
}
}
public closeSync(): void {
this.syncSync();
}
}
export interface ICodeSandboxFileSystemOptions {
api: IManager;
}
export default class CodeSandboxEditorFS extends SynchronousFileSystem
implements FileSystem {
public static readonly Name = 'CodeSandboxEditorFS';
public static readonly Options: FileSystemOptions = {
api: {
type: 'object',
description: 'The CodeSandbox Editor',
validator: (opt: IManager, cb: BFSOneArgCallback): void => {
if (opt) {
cb();
} else {
cb(new ApiError(ErrorCode.EINVAL, 'Manager is invalid'));
}
},
},
};
/**
* Creates an InMemoryFileSystem instance.
*/
public static Create(
options: ICodeSandboxFileSystemOptions,
cb: BFSCallback<CodeSandboxEditorFS>
): void {
cb(null, new CodeSandboxEditorFS(options.api));
}
public static isAvailable(): boolean {
return true;
}
private api: IManager;
constructor(api: IManager) {
super();
this.api = api;
}
public getName(): string {
return 'CodeSandboxEditorFS';
}
public isReadOnly(): boolean {
return false;
}
public supportsProps(): boolean {
return false;
}
public supportsSynch(): boolean {
return true;
}
public empty(mainCb: BFSOneArgCallback): void {
throw new Error('Empty not supported');
}
public renameSync(oldPath: string, newPath: string) {
throw new Error('Rename not supported');
}
public statSync(p: string, isLstate: boolean): Stats {
const modules = this.api.getSandboxFs();
const moduleInfo = modules[p];
if (!moduleInfo) {
const modulesStartingWithPath = Object.keys(modules).filter(
(pa: string) => pa.startsWith(p.endsWith('/') ? p : p + '/') || pa === p
);
if (modulesStartingWithPath.length > 0) {
return new Stats(FileType.DIRECTORY, 0);
} else {
throw ApiError.FileError(ErrorCode.ENOENT, p);
}
}
if (moduleInfo.type === 'directory') {
return new Stats(
FileType.DIRECTORY,
4096,
undefined,
+new Date(),
+new Date(moduleInfo.updatedAt),
+new Date(moduleInfo.insertedAt)
);
} else {
return new Stats(
FileType.FILE,
getCode(moduleInfo.savedCode, moduleInfo.code).length,
undefined,
+new Date(),
+new Date(moduleInfo.updatedAt),
+new Date(moduleInfo.insertedAt)
);
}
}
public createFileSync(p: string, flag: FileFlag, mode: number): File {
throw new Error('Create file not supported');
}
public open(p: string, flag: FileFlag, mode: number, cb: BFSCallback<File>): void {
const moduleInfo = this.api.getSandboxFs()[p];
if (!moduleInfo) {
cb(ApiError.ENOENT(p));
return;
}
if (moduleInfo.type === 'directory') {
const stats = new Stats(FileType.DIRECTORY, 4096, undefined, +new Date(), +new Date(moduleInfo.updatedAt), +new Date(moduleInfo.insertedAt));
cb(null, new CodeSandboxFile(this, p, flag, stats));
} else {
const { isBinary, savedCode, code } = moduleInfo;
if (isBinary) {
fetch(getCode(savedCode, code)).then(x => x.blob()).then(blob => {
const stats = new Stats(FileType.FILE, blob.size, undefined, +new Date(), +new Date(moduleInfo.updatedAt), +new Date(moduleInfo.insertedAt));
blobToBuffer(blob, (err, r) => {
if (err) {
cb(err);
return;
}
cb(undefined, new CodeSandboxFile(this, p, flag, stats, r));
});
});
return;
}
const buffer = Buffer.from(getCode(savedCode, code));
const stats = new Stats(FileType.FILE, buffer.length, undefined, +new Date(), +new Date(moduleInfo.updatedAt), +new Date(moduleInfo.insertedAt));
cb(null, new CodeSandboxFile(this, p, flag, stats, buffer));
}
}
public openFileSync(p: string, flag: FileFlag, mode: number): File {
const moduleInfo = this.api.getSandboxFs()[p];
if (!moduleInfo) {
throw ApiError.ENOENT(p);
}
if (moduleInfo.type === 'directory') {
const stats = new Stats(FileType.DIRECTORY, 4096, undefined, +new Date(), +new Date(moduleInfo.updatedAt), +new Date(moduleInfo.insertedAt));
return new CodeSandboxFile(this, p, flag, stats);
} else {
const { savedCode, code } = moduleInfo;
const buffer = Buffer.from(getCode(savedCode, code));
const stats = new Stats(FileType.FILE, buffer.length, undefined, +new Date(), +new Date(moduleInfo.updatedAt), +new Date(moduleInfo.insertedAt));
return new CodeSandboxFile(this, p, flag, stats, buffer);
}
}
public writeFileSync() {
// Stubbed
}
public rmdirSync(p: string) {
// Stubbed
}
public mkdirSync(p: string) {
// Stubbed
}
public unlinkSync(p: string) {
// Stubbed
}
public readdirSync(path: string): string[] {
const paths = Object.keys(this.api.getSandboxFs());
const p = path.endsWith('/') ? path : path + '/';
const pathsInDir = paths.filter((secondP: string) => secondP.startsWith(p));
if (pathsInDir.length === 0) {
return [];
}
const directChildren: Set<string> = new Set();
const currentPathLength = p.split('/').length;
pathsInDir
.filter((np: string) => np.split('/').length >= currentPathLength)
.forEach((np: string) => {
const parts = np.split('/');
parts.length = currentPathLength;
directChildren.add(parts.join('/'));
});
const pathArray = Array.from(directChildren).map(pa => pa.replace(p, ''));
return pathArray;
}
public _sync(p: string, data: Buffer, cb: BFSCallback<Stats>): void {
// Stubbed
cb(null, undefined);
}
public _syncSync(p: string, data: Buffer): void {
// Stubbed
}
}