@jupyterlite/contents 0.2.1 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +7 -6
- package/src/broadcast.ts +180 -0
- package/src/contents.ts +819 -0
- package/src/drivefs.ts +566 -0
- package/src/emscripten.ts +126 -0
- package/src/index.ts +8 -0
- package/src/tokens.ts +202 -0
package/src/contents.ts
ADDED
|
@@ -0,0 +1,819 @@
|
|
|
1
|
+
import { PageConfig, URLExt } from '@jupyterlab/coreutils';
|
|
2
|
+
|
|
3
|
+
import { Contents as ServerContents } from '@jupyterlab/services';
|
|
4
|
+
|
|
5
|
+
import { INotebookContent } from '@jupyterlab/nbformat';
|
|
6
|
+
|
|
7
|
+
import { PathExt } from '@jupyterlab/coreutils';
|
|
8
|
+
|
|
9
|
+
import type localforage from 'localforage';
|
|
10
|
+
|
|
11
|
+
import { IContents, MIME, FILE } from './tokens';
|
|
12
|
+
import { PromiseDelegate } from '@lumino/coreutils';
|
|
13
|
+
|
|
14
|
+
export type IModel = ServerContents.IModel;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The name of the local storage.
|
|
18
|
+
*/
|
|
19
|
+
const DEFAULT_STORAGE_NAME = 'JupyterLite Storage';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The number of checkpoints to save.
|
|
23
|
+
*/
|
|
24
|
+
const N_CHECKPOINTS = 5;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* A class to handle requests to /api/contents
|
|
28
|
+
*/
|
|
29
|
+
export class Contents implements IContents {
|
|
30
|
+
/**
|
|
31
|
+
* Construct a new localForage-powered contents provider
|
|
32
|
+
*/
|
|
33
|
+
constructor(options: Contents.IOptions) {
|
|
34
|
+
this._localforage = options.localforage;
|
|
35
|
+
this._storageName = options.storageName || DEFAULT_STORAGE_NAME;
|
|
36
|
+
this._storageDrivers = options.storageDrivers || null;
|
|
37
|
+
this._ready = new PromiseDelegate();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Finish any initialization after server has started and all extensions are applied.
|
|
42
|
+
*/
|
|
43
|
+
async initialize() {
|
|
44
|
+
await this.initStorage();
|
|
45
|
+
this._ready.resolve(void 0);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Initialize all storage instances
|
|
50
|
+
*/
|
|
51
|
+
protected async initStorage(): Promise<void> {
|
|
52
|
+
this._storage = this.createDefaultStorage();
|
|
53
|
+
this._counters = this.createDefaultCounters();
|
|
54
|
+
this._checkpoints = this.createDefaultCheckpoints();
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* A promise that resolves once all storage is fully initialized.
|
|
59
|
+
*/
|
|
60
|
+
get ready(): Promise<void> {
|
|
61
|
+
return this._ready.promise;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* A lazy reference to the underlying storage.
|
|
66
|
+
*/
|
|
67
|
+
protected get storage(): Promise<LocalForage> {
|
|
68
|
+
return this.ready.then(() => this._storage as LocalForage);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* A lazy reference to the underlying counters.
|
|
73
|
+
*/
|
|
74
|
+
protected get counters(): Promise<LocalForage> {
|
|
75
|
+
return this.ready.then(() => this._counters as LocalForage);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* A lazy reference to the underlying checkpoints.
|
|
80
|
+
*/
|
|
81
|
+
protected get checkpoints(): Promise<LocalForage> {
|
|
82
|
+
return this.ready.then(() => this._checkpoints as LocalForage);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Get default options for localForage instances
|
|
87
|
+
*/
|
|
88
|
+
protected get defaultStorageOptions(): LocalForageOptions {
|
|
89
|
+
const driver =
|
|
90
|
+
this._storageDrivers && this._storageDrivers.length ? this._storageDrivers : null;
|
|
91
|
+
return {
|
|
92
|
+
version: 1,
|
|
93
|
+
name: this._storageName,
|
|
94
|
+
...(driver ? { driver } : {}),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Initialize the default storage for contents.
|
|
100
|
+
*/
|
|
101
|
+
protected createDefaultStorage(): LocalForage {
|
|
102
|
+
return this._localforage.createInstance({
|
|
103
|
+
description: 'Offline Storage for Notebooks and Files',
|
|
104
|
+
storeName: 'files',
|
|
105
|
+
...this.defaultStorageOptions,
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Initialize the default storage for counting file suffixes.
|
|
111
|
+
*/
|
|
112
|
+
protected createDefaultCounters(): LocalForage {
|
|
113
|
+
return this._localforage.createInstance({
|
|
114
|
+
description: 'Store the current file suffix counters',
|
|
115
|
+
storeName: 'counters',
|
|
116
|
+
...this.defaultStorageOptions,
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Create the default checkpoint storage.
|
|
122
|
+
*/
|
|
123
|
+
protected createDefaultCheckpoints(): LocalForage {
|
|
124
|
+
return this._localforage.createInstance({
|
|
125
|
+
description: 'Offline Storage for Checkpoints',
|
|
126
|
+
storeName: 'checkpoints',
|
|
127
|
+
...this.defaultStorageOptions,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Create a new untitled file or directory in the specified directory path.
|
|
133
|
+
*
|
|
134
|
+
* @param options: The options used to create the file.
|
|
135
|
+
*
|
|
136
|
+
* @returns A promise which resolves with the created file content when the file is created.
|
|
137
|
+
*/
|
|
138
|
+
async newUntitled(options?: ServerContents.ICreateOptions): Promise<IModel | null> {
|
|
139
|
+
const path = options?.path ?? '';
|
|
140
|
+
const type = options?.type ?? 'notebook';
|
|
141
|
+
const created = new Date().toISOString();
|
|
142
|
+
|
|
143
|
+
let dirname = PathExt.dirname(path);
|
|
144
|
+
const basename = PathExt.basename(path);
|
|
145
|
+
const extname = PathExt.extname(path);
|
|
146
|
+
const item = await this.get(dirname);
|
|
147
|
+
|
|
148
|
+
// handle the case of "Save As", where the path points to the new file
|
|
149
|
+
// to create, e.g. subfolder/example-copy.ipynb
|
|
150
|
+
let name = '';
|
|
151
|
+
if (path && !extname && item) {
|
|
152
|
+
// directory
|
|
153
|
+
dirname = `${path}/`;
|
|
154
|
+
name = '';
|
|
155
|
+
} else if (dirname && basename) {
|
|
156
|
+
// file in a subfolder
|
|
157
|
+
dirname = `${dirname}/`;
|
|
158
|
+
name = basename;
|
|
159
|
+
} else {
|
|
160
|
+
// file at the top level
|
|
161
|
+
dirname = '';
|
|
162
|
+
name = path;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
let file: IModel;
|
|
166
|
+
switch (type) {
|
|
167
|
+
case 'directory': {
|
|
168
|
+
const counter = await this._incrementCounter('directory');
|
|
169
|
+
name = `Untitled Folder${counter || ''}`;
|
|
170
|
+
file = {
|
|
171
|
+
name,
|
|
172
|
+
path: `${dirname}${name}`,
|
|
173
|
+
last_modified: created,
|
|
174
|
+
created,
|
|
175
|
+
format: 'json',
|
|
176
|
+
mimetype: '',
|
|
177
|
+
content: null,
|
|
178
|
+
size: 0,
|
|
179
|
+
writable: true,
|
|
180
|
+
type: 'directory',
|
|
181
|
+
};
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
case 'notebook': {
|
|
185
|
+
const counter = await this._incrementCounter('notebook');
|
|
186
|
+
name = name || `Untitled${counter || ''}.ipynb`;
|
|
187
|
+
file = {
|
|
188
|
+
name,
|
|
189
|
+
path: `${dirname}${name}`,
|
|
190
|
+
last_modified: created,
|
|
191
|
+
created,
|
|
192
|
+
format: 'json',
|
|
193
|
+
mimetype: MIME.JSON,
|
|
194
|
+
content: Private.EMPTY_NB,
|
|
195
|
+
size: JSON.stringify(Private.EMPTY_NB).length,
|
|
196
|
+
writable: true,
|
|
197
|
+
type: 'notebook',
|
|
198
|
+
};
|
|
199
|
+
break;
|
|
200
|
+
}
|
|
201
|
+
default: {
|
|
202
|
+
const ext = options?.ext ?? '.txt';
|
|
203
|
+
const counter = await this._incrementCounter('file');
|
|
204
|
+
const mimetype = FILE.getType(ext) || MIME.OCTET_STREAM;
|
|
205
|
+
|
|
206
|
+
let format: ServerContents.FileFormat;
|
|
207
|
+
if (FILE.hasFormat(ext, 'text') || mimetype.indexOf('text') !== -1) {
|
|
208
|
+
format = 'text';
|
|
209
|
+
} else if (ext.indexOf('json') !== -1 || ext.indexOf('ipynb') !== -1) {
|
|
210
|
+
format = 'json';
|
|
211
|
+
} else {
|
|
212
|
+
format = 'base64';
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
name = name || `untitled${counter || ''}${ext}`;
|
|
216
|
+
file = {
|
|
217
|
+
name,
|
|
218
|
+
path: `${dirname}${name}`,
|
|
219
|
+
last_modified: created,
|
|
220
|
+
created,
|
|
221
|
+
format,
|
|
222
|
+
mimetype,
|
|
223
|
+
content: '',
|
|
224
|
+
size: 0,
|
|
225
|
+
writable: true,
|
|
226
|
+
type: 'file',
|
|
227
|
+
};
|
|
228
|
+
break;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const key = file.path;
|
|
233
|
+
await (await this.storage).setItem(key, file);
|
|
234
|
+
return file;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Copy a file into a given directory.
|
|
239
|
+
*
|
|
240
|
+
* @param path - The original file path.
|
|
241
|
+
* @param toDir - The destination directory path.
|
|
242
|
+
*
|
|
243
|
+
* @returns A promise which resolves with the new contents model when the
|
|
244
|
+
* file is copied.
|
|
245
|
+
*
|
|
246
|
+
* #### Notes
|
|
247
|
+
* The server will select the name of the copied file.
|
|
248
|
+
*/
|
|
249
|
+
async copy(path: string, toDir: string): Promise<IModel> {
|
|
250
|
+
let name = PathExt.basename(path);
|
|
251
|
+
toDir = toDir === '' ? '' : `${toDir.slice(1)}/`;
|
|
252
|
+
// TODO: better handle naming collisions with existing files
|
|
253
|
+
while (await this.get(`${toDir}${name}`, { content: true })) {
|
|
254
|
+
const ext = PathExt.extname(name);
|
|
255
|
+
const base = name.replace(ext, '');
|
|
256
|
+
name = `${base} (copy)${ext}`;
|
|
257
|
+
}
|
|
258
|
+
const toPath = `${toDir}${name}`;
|
|
259
|
+
let item = await this.get(path, { content: true });
|
|
260
|
+
if (!item) {
|
|
261
|
+
throw Error(`Could not find file with path ${path}`);
|
|
262
|
+
}
|
|
263
|
+
item = {
|
|
264
|
+
...item,
|
|
265
|
+
name,
|
|
266
|
+
path: toPath,
|
|
267
|
+
};
|
|
268
|
+
await (await this.storage).setItem(toPath, item);
|
|
269
|
+
return item;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Get a file or directory.
|
|
274
|
+
*
|
|
275
|
+
* @param path: The path to the file.
|
|
276
|
+
* @param options: The options used to fetch the file.
|
|
277
|
+
*
|
|
278
|
+
* @returns A promise which resolves with the file content.
|
|
279
|
+
*/
|
|
280
|
+
async get(
|
|
281
|
+
path: string,
|
|
282
|
+
options?: ServerContents.IFetchOptions,
|
|
283
|
+
): Promise<IModel | null> {
|
|
284
|
+
// remove leading slash
|
|
285
|
+
path = decodeURIComponent(path.replace(/^\//, ''));
|
|
286
|
+
|
|
287
|
+
if (path === '') {
|
|
288
|
+
return await this._getFolder(path);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const storage = await this.storage;
|
|
292
|
+
const item = await storage.getItem(path);
|
|
293
|
+
const serverItem = await this._getServerContents(path, options);
|
|
294
|
+
|
|
295
|
+
const model = (item || serverItem) as IModel | null;
|
|
296
|
+
|
|
297
|
+
if (!model) {
|
|
298
|
+
return null;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
if (!options?.content) {
|
|
302
|
+
return {
|
|
303
|
+
size: 0,
|
|
304
|
+
...model,
|
|
305
|
+
content: null,
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// for directories, find all files with the path as the prefix
|
|
310
|
+
if (model.type === 'directory') {
|
|
311
|
+
const contentMap = new Map<string, IModel>();
|
|
312
|
+
await storage.iterate<IModel, void>((file, key) => {
|
|
313
|
+
// use an additional slash to not include the directory itself
|
|
314
|
+
if (key === `${path}/${file.name}`) {
|
|
315
|
+
contentMap.set(file.name, file);
|
|
316
|
+
}
|
|
317
|
+
});
|
|
318
|
+
|
|
319
|
+
const serverContents: IModel[] = serverItem
|
|
320
|
+
? serverItem.content
|
|
321
|
+
: Array.from((await this._getServerDirectory(path)).values());
|
|
322
|
+
for (const file of serverContents) {
|
|
323
|
+
if (!contentMap.has(file.name)) {
|
|
324
|
+
contentMap.set(file.name, file);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const content = [...contentMap.values()];
|
|
329
|
+
|
|
330
|
+
return {
|
|
331
|
+
name: PathExt.basename(path),
|
|
332
|
+
path,
|
|
333
|
+
last_modified: model.last_modified,
|
|
334
|
+
created: model.created,
|
|
335
|
+
format: 'json',
|
|
336
|
+
mimetype: MIME.JSON,
|
|
337
|
+
content,
|
|
338
|
+
size: 0,
|
|
339
|
+
writable: true,
|
|
340
|
+
type: 'directory',
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
return model;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Rename a file or directory.
|
|
348
|
+
*
|
|
349
|
+
* @param oldLocalPath - The original file path.
|
|
350
|
+
* @param newLocalPath - The new file path.
|
|
351
|
+
*
|
|
352
|
+
* @returns A promise which resolves with the new file content model when the file is renamed.
|
|
353
|
+
*/
|
|
354
|
+
async rename(oldLocalPath: string, newLocalPath: string): Promise<IModel> {
|
|
355
|
+
const path = decodeURIComponent(oldLocalPath);
|
|
356
|
+
const file = await this.get(path, { content: true });
|
|
357
|
+
if (!file) {
|
|
358
|
+
throw Error(`Could not find file with path ${path}`);
|
|
359
|
+
}
|
|
360
|
+
const modified = new Date().toISOString();
|
|
361
|
+
const name = PathExt.basename(newLocalPath);
|
|
362
|
+
const newFile = {
|
|
363
|
+
...file,
|
|
364
|
+
name,
|
|
365
|
+
path: newLocalPath,
|
|
366
|
+
last_modified: modified,
|
|
367
|
+
};
|
|
368
|
+
const storage = await this.storage;
|
|
369
|
+
await storage.setItem(newLocalPath, newFile);
|
|
370
|
+
// remove the old file
|
|
371
|
+
await storage.removeItem(path);
|
|
372
|
+
// remove the corresponding checkpoint
|
|
373
|
+
await (await this.checkpoints).removeItem(path);
|
|
374
|
+
// if a directory, recurse through all children
|
|
375
|
+
if (file.type === 'directory') {
|
|
376
|
+
let child: IModel;
|
|
377
|
+
for (child of file.content) {
|
|
378
|
+
await this.rename(
|
|
379
|
+
URLExt.join(oldLocalPath, child.name),
|
|
380
|
+
URLExt.join(newLocalPath, child.name),
|
|
381
|
+
);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
return newFile;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* Save a file.
|
|
390
|
+
*
|
|
391
|
+
* @param path - The desired file path.
|
|
392
|
+
* @param options - Optional overrides to the model.
|
|
393
|
+
*
|
|
394
|
+
* @returns A promise which resolves with the file content model when the file is saved.
|
|
395
|
+
*/
|
|
396
|
+
async save(path: string, options: Partial<IModel> = {}): Promise<IModel | null> {
|
|
397
|
+
path = decodeURIComponent(path);
|
|
398
|
+
|
|
399
|
+
// process the file if coming from an upload
|
|
400
|
+
const ext = PathExt.extname(options.name ?? '');
|
|
401
|
+
const chunk = options.chunk;
|
|
402
|
+
|
|
403
|
+
// retrieve the content if it is a later chunk or the last one
|
|
404
|
+
// the new content will then be appended to the existing one
|
|
405
|
+
const chunked = chunk ? chunk > 1 || chunk === -1 : false;
|
|
406
|
+
let item: IModel | null = await this.get(path, { content: chunked });
|
|
407
|
+
|
|
408
|
+
if (!item) {
|
|
409
|
+
item = await this.newUntitled({ path, ext, type: 'file' });
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
if (!item) {
|
|
413
|
+
return null;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// keep a reference to the original content
|
|
417
|
+
const originalContent = item.content;
|
|
418
|
+
|
|
419
|
+
const modified = new Date().toISOString();
|
|
420
|
+
// override with the new values
|
|
421
|
+
item = {
|
|
422
|
+
...item,
|
|
423
|
+
...options,
|
|
424
|
+
last_modified: modified,
|
|
425
|
+
};
|
|
426
|
+
|
|
427
|
+
if (options.content && options.format === 'base64') {
|
|
428
|
+
const lastChunk = chunk ? chunk === -1 : true;
|
|
429
|
+
|
|
430
|
+
if (ext === '.ipynb') {
|
|
431
|
+
const content = this._handleChunk(options.content, originalContent, chunked);
|
|
432
|
+
item = {
|
|
433
|
+
...item,
|
|
434
|
+
content: lastChunk ? JSON.parse(content) : content,
|
|
435
|
+
format: 'json',
|
|
436
|
+
type: 'notebook',
|
|
437
|
+
size: content.length,
|
|
438
|
+
};
|
|
439
|
+
} else if (FILE.hasFormat(ext, 'json')) {
|
|
440
|
+
const content = this._handleChunk(options.content, originalContent, chunked);
|
|
441
|
+
item = {
|
|
442
|
+
...item,
|
|
443
|
+
content: lastChunk ? JSON.parse(content) : content,
|
|
444
|
+
format: 'json',
|
|
445
|
+
type: 'file',
|
|
446
|
+
size: content.length,
|
|
447
|
+
};
|
|
448
|
+
} else if (FILE.hasFormat(ext, 'text')) {
|
|
449
|
+
const content = this._handleChunk(options.content, originalContent, chunked);
|
|
450
|
+
item = {
|
|
451
|
+
...item,
|
|
452
|
+
content,
|
|
453
|
+
format: 'text',
|
|
454
|
+
type: 'file',
|
|
455
|
+
size: content.length,
|
|
456
|
+
};
|
|
457
|
+
} else {
|
|
458
|
+
const content = options.content;
|
|
459
|
+
item = {
|
|
460
|
+
...item,
|
|
461
|
+
content,
|
|
462
|
+
size: atob(content).length,
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
await (await this.storage).setItem(path, item);
|
|
468
|
+
return item;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* Delete a file from browser storage.
|
|
473
|
+
*
|
|
474
|
+
* Has no effect on server-backed files, which will re-appear with their
|
|
475
|
+
* original timestamp.
|
|
476
|
+
*
|
|
477
|
+
* @param path - The path to the file.
|
|
478
|
+
*/
|
|
479
|
+
async delete(path: string): Promise<void> {
|
|
480
|
+
path = decodeURIComponent(path);
|
|
481
|
+
const slashed = `${path}/`;
|
|
482
|
+
const toDelete = (await (await this.storage).keys()).filter(
|
|
483
|
+
(key) => key === path || key.startsWith(slashed),
|
|
484
|
+
);
|
|
485
|
+
await Promise.all(toDelete.map(this.forgetPath, this));
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/**
|
|
489
|
+
* Remove the localForage and checkpoints for a path.
|
|
490
|
+
*
|
|
491
|
+
* @param path - The path to the file
|
|
492
|
+
*/
|
|
493
|
+
protected async forgetPath(path: string): Promise<void> {
|
|
494
|
+
await Promise.all([
|
|
495
|
+
(await this.storage).removeItem(path),
|
|
496
|
+
(await this.checkpoints).removeItem(path),
|
|
497
|
+
]);
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/**
|
|
501
|
+
* Create a checkpoint for a file.
|
|
502
|
+
*
|
|
503
|
+
* @param path - The path of the file.
|
|
504
|
+
*
|
|
505
|
+
* @returns A promise which resolves with the new checkpoint model when the
|
|
506
|
+
* checkpoint is created.
|
|
507
|
+
*/
|
|
508
|
+
async createCheckpoint(path: string): Promise<ServerContents.ICheckpointModel> {
|
|
509
|
+
const checkpoints = await this.checkpoints;
|
|
510
|
+
path = decodeURIComponent(path);
|
|
511
|
+
const item = await this.get(path, { content: true });
|
|
512
|
+
if (!item) {
|
|
513
|
+
throw Error(`Could not find file with path ${path}`);
|
|
514
|
+
}
|
|
515
|
+
const copies = (((await checkpoints.getItem(path)) as IModel[]) ?? []).filter(
|
|
516
|
+
Boolean,
|
|
517
|
+
);
|
|
518
|
+
copies.push(item);
|
|
519
|
+
// keep only a certain amount of checkpoints per file
|
|
520
|
+
if (copies.length > N_CHECKPOINTS) {
|
|
521
|
+
copies.splice(0, copies.length - N_CHECKPOINTS);
|
|
522
|
+
}
|
|
523
|
+
await checkpoints.setItem(path, copies);
|
|
524
|
+
const id = `${copies.length - 1}`;
|
|
525
|
+
return { id, last_modified: (item as IModel).last_modified };
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/**
|
|
529
|
+
* List available checkpoints for a file.
|
|
530
|
+
*
|
|
531
|
+
* @param path - The path of the file.
|
|
532
|
+
*
|
|
533
|
+
* @returns A promise which resolves with a list of checkpoint models for
|
|
534
|
+
* the file.
|
|
535
|
+
*/
|
|
536
|
+
async listCheckpoints(path: string): Promise<ServerContents.ICheckpointModel[]> {
|
|
537
|
+
const copies: IModel[] = (await (await this.checkpoints).getItem(path)) || [];
|
|
538
|
+
return copies.filter(Boolean).map(this.normalizeCheckpoint, this);
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
protected normalizeCheckpoint(
|
|
542
|
+
model: IModel,
|
|
543
|
+
id: number,
|
|
544
|
+
): ServerContents.ICheckpointModel {
|
|
545
|
+
return { id: id.toString(), last_modified: model.last_modified };
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* Restore a file to a known checkpoint state.
|
|
550
|
+
*
|
|
551
|
+
* @param path - The path of the file.
|
|
552
|
+
* @param checkpointID - The id of the checkpoint to restore.
|
|
553
|
+
*
|
|
554
|
+
* @returns A promise which resolves when the checkpoint is restored.
|
|
555
|
+
*/
|
|
556
|
+
async restoreCheckpoint(path: string, checkpointID: string): Promise<void> {
|
|
557
|
+
path = decodeURIComponent(path);
|
|
558
|
+
const copies = ((await (await this.checkpoints).getItem(path)) || []) as IModel[];
|
|
559
|
+
const id = parseInt(checkpointID);
|
|
560
|
+
const item = copies[id];
|
|
561
|
+
await (await this.storage).setItem(path, item);
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* Delete a checkpoint for a file.
|
|
566
|
+
*
|
|
567
|
+
* @param path - The path of the file.
|
|
568
|
+
* @param checkpointID - The id of the checkpoint to delete.
|
|
569
|
+
*
|
|
570
|
+
* @returns A promise which resolves when the checkpoint is deleted.
|
|
571
|
+
*/
|
|
572
|
+
async deleteCheckpoint(path: string, checkpointID: string): Promise<void> {
|
|
573
|
+
path = decodeURIComponent(path);
|
|
574
|
+
const copies = ((await (await this.checkpoints).getItem(path)) || []) as IModel[];
|
|
575
|
+
const id = parseInt(checkpointID);
|
|
576
|
+
copies.splice(id, 1);
|
|
577
|
+
await (await this.checkpoints).setItem(path, copies);
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/**
|
|
581
|
+
* Handle a chunk of a file.
|
|
582
|
+
* Decode and unescape a base64-encoded string.
|
|
583
|
+
* @param content the content to process
|
|
584
|
+
*
|
|
585
|
+
* @returns the decoded string, appended to the original content if chunked
|
|
586
|
+
* /
|
|
587
|
+
*/
|
|
588
|
+
private _handleChunk(
|
|
589
|
+
newContent: string,
|
|
590
|
+
originalContent: string,
|
|
591
|
+
chunked?: boolean,
|
|
592
|
+
): string {
|
|
593
|
+
const escaped = decodeURIComponent(escape(atob(newContent)));
|
|
594
|
+
const content = chunked ? originalContent + escaped : escaped;
|
|
595
|
+
return content;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* retrieve the contents for this path from the union of local storage and
|
|
600
|
+
* `api/contents/{path}/all.json`.
|
|
601
|
+
*
|
|
602
|
+
* @param path - The contents path to retrieve
|
|
603
|
+
*
|
|
604
|
+
* @returns A promise which resolves with a Map of contents, keyed by local file name
|
|
605
|
+
*/
|
|
606
|
+
private async _getFolder(path: string): Promise<IModel | null> {
|
|
607
|
+
const content = new Map<string, IModel>();
|
|
608
|
+
const storage = await this.storage;
|
|
609
|
+
await storage.iterate<IModel, void>((file, key) => {
|
|
610
|
+
if (key.includes('/')) {
|
|
611
|
+
return;
|
|
612
|
+
}
|
|
613
|
+
content.set(file.path, file);
|
|
614
|
+
});
|
|
615
|
+
|
|
616
|
+
// layer in contents that don't have local overwrites
|
|
617
|
+
for (const file of (await this._getServerDirectory(path)).values()) {
|
|
618
|
+
if (!content.has(file.path)) {
|
|
619
|
+
content.set(file.path, file);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
if (path && content.size === 0) {
|
|
624
|
+
return null;
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
return {
|
|
628
|
+
name: '',
|
|
629
|
+
path,
|
|
630
|
+
last_modified: new Date(0).toISOString(),
|
|
631
|
+
created: new Date(0).toISOString(),
|
|
632
|
+
format: 'json',
|
|
633
|
+
mimetype: MIME.JSON,
|
|
634
|
+
content: Array.from(content.values()),
|
|
635
|
+
size: 0,
|
|
636
|
+
writable: true,
|
|
637
|
+
type: 'directory',
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
/**
|
|
642
|
+
* Attempt to recover the model from `{:path}/__all__.json` file, fall back to
|
|
643
|
+
* deriving the model (including content) off the file in `/files/`. Otherwise
|
|
644
|
+
* return `null`.
|
|
645
|
+
*/
|
|
646
|
+
private async _getServerContents(
|
|
647
|
+
path: string,
|
|
648
|
+
options?: ServerContents.IFetchOptions,
|
|
649
|
+
): Promise<IModel | null> {
|
|
650
|
+
const name = PathExt.basename(path);
|
|
651
|
+
const parentContents = await this._getServerDirectory(URLExt.join(path, '..'));
|
|
652
|
+
let model = parentContents.get(name);
|
|
653
|
+
if (!model) {
|
|
654
|
+
return null;
|
|
655
|
+
}
|
|
656
|
+
model = model || {
|
|
657
|
+
name,
|
|
658
|
+
path,
|
|
659
|
+
last_modified: new Date(0).toISOString(),
|
|
660
|
+
created: new Date(0).toISOString(),
|
|
661
|
+
format: 'text',
|
|
662
|
+
mimetype: MIME.PLAIN_TEXT,
|
|
663
|
+
type: 'file',
|
|
664
|
+
writable: true,
|
|
665
|
+
size: 0,
|
|
666
|
+
content: '',
|
|
667
|
+
};
|
|
668
|
+
|
|
669
|
+
if (options?.content) {
|
|
670
|
+
if (model.type === 'directory') {
|
|
671
|
+
const serverContents = await this._getServerDirectory(path);
|
|
672
|
+
model = { ...model, content: Array.from(serverContents.values()) };
|
|
673
|
+
} else {
|
|
674
|
+
const fileUrl = URLExt.join(PageConfig.getBaseUrl(), 'files', path);
|
|
675
|
+
const response = await fetch(fileUrl);
|
|
676
|
+
if (!response.ok) {
|
|
677
|
+
return null;
|
|
678
|
+
}
|
|
679
|
+
const mimetype = model.mimetype || response.headers.get('Content-Type');
|
|
680
|
+
const ext = PathExt.extname(name);
|
|
681
|
+
|
|
682
|
+
if (
|
|
683
|
+
model.type === 'notebook' ||
|
|
684
|
+
FILE.hasFormat(ext, 'json') ||
|
|
685
|
+
mimetype?.indexOf('json') !== -1 ||
|
|
686
|
+
path.match(/\.(ipynb|[^/]*json[^/]*)$/)
|
|
687
|
+
) {
|
|
688
|
+
const contentText = await response.text();
|
|
689
|
+
model = {
|
|
690
|
+
...model,
|
|
691
|
+
content: JSON.parse(contentText),
|
|
692
|
+
format: 'json',
|
|
693
|
+
mimetype: model.mimetype || MIME.JSON,
|
|
694
|
+
size: contentText.length,
|
|
695
|
+
};
|
|
696
|
+
} else if (FILE.hasFormat(ext, 'text') || mimetype.indexOf('text') !== -1) {
|
|
697
|
+
const contentText = await response.text();
|
|
698
|
+
model = {
|
|
699
|
+
...model,
|
|
700
|
+
content: contentText,
|
|
701
|
+
format: 'text',
|
|
702
|
+
mimetype: mimetype || MIME.PLAIN_TEXT,
|
|
703
|
+
size: contentText.length,
|
|
704
|
+
};
|
|
705
|
+
} else {
|
|
706
|
+
const contentBytes = await response.arrayBuffer();
|
|
707
|
+
const contentBuffer = new Uint8Array(contentBytes);
|
|
708
|
+
model = {
|
|
709
|
+
...model,
|
|
710
|
+
content: btoa(contentBuffer.reduce(this.reduceBytesToString, '')),
|
|
711
|
+
format: 'base64',
|
|
712
|
+
mimetype: mimetype || MIME.OCTET_STREAM,
|
|
713
|
+
size: contentBuffer.length,
|
|
714
|
+
};
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
return model;
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/**
|
|
723
|
+
* A reducer for turning arbitrary binary into a string
|
|
724
|
+
*/
|
|
725
|
+
protected reduceBytesToString = (data: string, byte: number): string => {
|
|
726
|
+
return data + String.fromCharCode(byte);
|
|
727
|
+
};
|
|
728
|
+
|
|
729
|
+
/**
|
|
730
|
+
* retrieve the contents for this path from `__index__.json` in the appropriate
|
|
731
|
+
* folder.
|
|
732
|
+
*
|
|
733
|
+
* @param newLocalPath - The new file path.
|
|
734
|
+
*
|
|
735
|
+
* @returns A promise which resolves with a Map of contents, keyed by local file name
|
|
736
|
+
*/
|
|
737
|
+
private async _getServerDirectory(path: string): Promise<Map<string, IModel>> {
|
|
738
|
+
const content = this._serverContents.get(path) || new Map();
|
|
739
|
+
|
|
740
|
+
if (!this._serverContents.has(path)) {
|
|
741
|
+
const apiURL = URLExt.join(
|
|
742
|
+
PageConfig.getBaseUrl(),
|
|
743
|
+
'api/contents',
|
|
744
|
+
path,
|
|
745
|
+
'all.json',
|
|
746
|
+
);
|
|
747
|
+
|
|
748
|
+
try {
|
|
749
|
+
const response = await fetch(apiURL);
|
|
750
|
+
const json = JSON.parse(await response.text());
|
|
751
|
+
for (const file of json['content'] as IModel[]) {
|
|
752
|
+
content.set(file.name, file);
|
|
753
|
+
}
|
|
754
|
+
} catch (err) {
|
|
755
|
+
console.warn(
|
|
756
|
+
`don't worry, about ${err}... nothing's broken. If there had been a
|
|
757
|
+
file at ${apiURL}, you might see some more files.`,
|
|
758
|
+
);
|
|
759
|
+
}
|
|
760
|
+
this._serverContents.set(path, content);
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
return content;
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
/**
|
|
767
|
+
* Increment the counter for a given file type.
|
|
768
|
+
* Used to avoid collisions when creating new untitled files.
|
|
769
|
+
*
|
|
770
|
+
* @param type The file type to increment the counter for.
|
|
771
|
+
*/
|
|
772
|
+
private async _incrementCounter(type: ServerContents.ContentType): Promise<number> {
|
|
773
|
+
const counters = await this.counters;
|
|
774
|
+
const current = ((await counters.getItem(type)) as number) ?? -1;
|
|
775
|
+
const counter = current + 1;
|
|
776
|
+
await counters.setItem(type, counter);
|
|
777
|
+
return counter;
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
private _serverContents = new Map<string, Map<string, IModel>>();
|
|
781
|
+
private _storageName: string = DEFAULT_STORAGE_NAME;
|
|
782
|
+
private _storageDrivers: string[] | null = null;
|
|
783
|
+
private _ready: PromiseDelegate<void>;
|
|
784
|
+
private _storage: LocalForage | undefined;
|
|
785
|
+
private _counters: LocalForage | undefined;
|
|
786
|
+
private _checkpoints: LocalForage | undefined;
|
|
787
|
+
private _localforage: typeof localforage;
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
/**
|
|
791
|
+
* A namespace for contents information.
|
|
792
|
+
*/
|
|
793
|
+
export namespace Contents {
|
|
794
|
+
export interface IOptions {
|
|
795
|
+
/**
|
|
796
|
+
* The name of the storage instance on e.g. IndexedDB, localStorage
|
|
797
|
+
*/
|
|
798
|
+
storageName?: string | null;
|
|
799
|
+
storageDrivers?: string[] | null;
|
|
800
|
+
localforage: typeof localforage;
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/**
|
|
805
|
+
* A namespace for private data.
|
|
806
|
+
*/
|
|
807
|
+
namespace Private {
|
|
808
|
+
/**
|
|
809
|
+
* The content for an empty notebook.
|
|
810
|
+
*/
|
|
811
|
+
export const EMPTY_NB: INotebookContent = {
|
|
812
|
+
metadata: {
|
|
813
|
+
orig_nbformat: 4,
|
|
814
|
+
},
|
|
815
|
+
nbformat_minor: 4,
|
|
816
|
+
nbformat: 4,
|
|
817
|
+
cells: [],
|
|
818
|
+
};
|
|
819
|
+
}
|