@jupyterlite/contents 0.1.0-alpha.13 → 0.1.0-alpha.17

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/lib/contents.d.ts CHANGED
@@ -1,27 +1,9 @@
1
- import { Contents as ServerContents, ServerConnection } from '@jupyterlab/services';
2
- import { ModelDB } from '@jupyterlab/observables';
3
- import { ISignal } from '@lumino/signaling';
1
+ import { Contents as ServerContents } from '@jupyterlab/services';
4
2
  import { IContents } from './tokens';
5
3
  /**
6
4
  * A class to handle requests to /api/contents
7
5
  */
8
6
  export declare class Contents implements IContents {
9
- /**
10
- * A signal emitted when the file has changed.
11
- */
12
- get fileChanged(): ISignal<ServerContents.IManager, ServerContents.IChangedArgs>;
13
- /**
14
- * Test whether the manager has been disposed.
15
- */
16
- get isDisposed(): boolean;
17
- /**
18
- * Return the server settings.
19
- */
20
- get serverSettings(): ServerConnection.ISettings;
21
- /**
22
- * Dispose of the resources held by the manager.
23
- */
24
- dispose(): void;
25
7
  /**
26
8
  * Create a new untitled file or directory in the specified directory path.
27
9
  *
@@ -29,7 +11,7 @@ export declare class Contents implements IContents {
29
11
  *
30
12
  * @returns A promise which resolves with the created file content when the file is created.
31
13
  */
32
- newUntitled(options?: ServerContents.ICreateOptions): Promise<ServerContents.IModel>;
14
+ newUntitled(options?: ServerContents.ICreateOptions): Promise<ServerContents.IModel | null>;
33
15
  /**
34
16
  * Copy a file into a given directory.
35
17
  *
@@ -51,32 +33,7 @@ export declare class Contents implements IContents {
51
33
  *
52
34
  * @returns A promise which resolves with the file content.
53
35
  */
54
- get(path: string, options?: ServerContents.IFetchOptions): Promise<ServerContents.IModel>;
55
- /**
56
- * retrieve the contents for this path from the union of local storage and
57
- * `api/contents/{path}/all.json`.
58
- *
59
- * @param path - The contents path to retrieve
60
- *
61
- * @returns A promise which resolves with a Map of contents, keyed by local file name
62
- */
63
- getFolder(path: string): Promise<ServerContents.IModel>;
64
- private _serverContents;
65
- /**
66
- * retrieve the contents for this path from `__index__.json` in the appropriate
67
- * folder.
68
- *
69
- * @param newLocalPath - The new file path.
70
- *
71
- * @returns A promise which resolves with a Map of contents, keyed by local file name
72
- */
73
- getServerDirectory(path: string): Promise<Map<string, ServerContents.IModel>>;
74
- /**
75
- * Attempt to recover the model from `{:path}/__all__.json` file, fall back to
76
- * deriving the model (including content) off the file in `/files/`. Otherwise
77
- * return `null`.
78
- */
79
- getServerContents(path: string, options?: ServerContents.IFetchOptions): Promise<ServerContents.IModel | null>;
36
+ get(path: string, options?: ServerContents.IFetchOptions): Promise<ServerContents.IModel | null>;
80
37
  /**
81
38
  * Rename a file or directory.
82
39
  *
@@ -94,7 +51,7 @@ export declare class Contents implements IContents {
94
51
  *
95
52
  * @returns A promise which resolves with the file content model when the file is saved.
96
53
  */
97
- save(path: string, options?: Partial<ServerContents.IModel>): Promise<ServerContents.IModel>;
54
+ save(path: string, options?: Partial<ServerContents.IModel>): Promise<ServerContents.IModel | null>;
98
55
  /**
99
56
  * Delete a file.
100
57
  *
@@ -138,67 +95,29 @@ export declare class Contents implements IContents {
138
95
  */
139
96
  deleteCheckpoint(path: string, checkpointID: string): Promise<void>;
140
97
  /**
141
- * Add an `IDrive` to the manager.
142
- */
143
- addDrive(drive: ServerContents.IDrive): void;
144
- /**
145
- * Given a path of the form `drive:local/portion/of/it.txt`
146
- * get the local part of it.
147
- *
148
- * @param path: the path.
149
- *
150
- * @returns The local part of the path.
151
- */
152
- localPath(path: string): string;
153
- /**
154
- * Normalize a global path. Reduces '..' and '.' parts, and removes
155
- * leading slashes from the local part of the path, while retaining
156
- * the drive name if it exists.
157
- *
158
- * @param path: the path.
159
- *
160
- * @returns The normalized path.
161
- */
162
- normalize(path: string): string;
163
- /**
164
- * Resolve a global path, starting from the root path. Behaves like
165
- * posix-path.resolve, with 3 differences:
166
- * - will never prepend cwd
167
- * - if root has a drive name, the result is prefixed with "<drive>:"
168
- * - before adding drive name, leading slashes are removed
169
- *
170
- * @param path: the path.
171
- *
172
- * @returns The normalized path.
173
- */
174
- resolvePath(root: string, path: string): string;
175
- /**
176
- * Given a path of the form `drive:local/portion/of/it.txt`
177
- * get the name of the drive. If the path is missing
178
- * a drive portion, returns an empty string.
98
+ * retrieve the contents for this path from the union of local storage and
99
+ * `api/contents/{path}/all.json`.
179
100
  *
180
- * @param path: the path.
101
+ * @param path - The contents path to retrieve
181
102
  *
182
- * @returns The drive name for the path, or the empty string.
103
+ * @returns A promise which resolves with a Map of contents, keyed by local file name
183
104
  */
184
- driveName(path: string): string;
105
+ private _getFolder;
185
106
  /**
186
- * Given a path, get a ModelDB.IFactory from the
187
- * relevant backend. Returns `null` if the backend
188
- * does not provide one.
107
+ * Attempt to recover the model from `{:path}/__all__.json` file, fall back to
108
+ * deriving the model (including content) off the file in `/files/`. Otherwise
109
+ * return `null`.
189
110
  */
190
- getModelDBFactory(path: string): ModelDB.IFactory | null;
111
+ private _getServerContents;
191
112
  /**
192
- * Get an encoded download url given a file path.
193
- *
194
- * @param path - An absolute POSIX file path on the server.
113
+ * retrieve the contents for this path from `__index__.json` in the appropriate
114
+ * folder.
195
115
  *
196
- * #### Notes
197
- * It is expected that the path contains no relative paths.
116
+ * @param newLocalPath - The new file path.
198
117
  *
199
- * The returned URL may include a query parameter.
118
+ * @returns A promise which resolves with a Map of contents, keyed by local file name
200
119
  */
201
- getDownloadUrl(path: string): Promise<string>;
120
+ private _getServerDirectory;
202
121
  /**
203
122
  * Increment the counter for a given file type.
204
123
  * Used to avoid collisions when creating new untitled files.
@@ -206,8 +125,7 @@ export declare class Contents implements IContents {
206
125
  * @param type The file type to increment the counter for.
207
126
  */
208
127
  private _incrementCounter;
209
- private _isDisposed;
210
- private _fileChanged;
128
+ private _serverContents;
211
129
  private _storage;
212
130
  private _counters;
213
131
  private _checkpoints;
package/lib/contents.js CHANGED
@@ -1,7 +1,5 @@
1
1
  import { PageConfig, URLExt } from '@jupyterlab/coreutils';
2
- import { ServerConnection } from '@jupyterlab/services';
3
2
  import { PathExt } from '@jupyterlab/coreutils';
4
- import { Signal } from '@lumino/signaling';
5
3
  import localforage from 'localforage';
6
4
  /**
7
5
  * The name of the local storage.
@@ -11,14 +9,23 @@ const STORAGE_NAME = 'JupyterLite Storage';
11
9
  * The number of checkpoints to save.
12
10
  */
13
11
  const N_CHECKPOINTS = 5;
12
+ /**
13
+ * A list of mime types of text files
14
+ */
15
+ const EXTRA_TEXT_MIME_TYPES = new Set([
16
+ 'application/javascript',
17
+ 'application/json',
18
+ 'application/manifest+json',
19
+ 'application/x-python-code',
20
+ 'application/xml',
21
+ 'image/svg+xml'
22
+ ]);
14
23
  /**
15
24
  * A class to handle requests to /api/contents
16
25
  */
17
26
  export class Contents {
18
27
  constructor() {
19
28
  this._serverContents = new Map();
20
- this._isDisposed = false;
21
- this._fileChanged = new Signal(this);
22
29
  this._storage = localforage.createInstance({
23
30
  name: STORAGE_NAME,
24
31
  description: 'Offline Storage for Notebooks and Files',
@@ -38,31 +45,6 @@ export class Contents {
38
45
  version: 1
39
46
  });
40
47
  }
41
- /**
42
- * A signal emitted when the file has changed.
43
- */
44
- get fileChanged() {
45
- return this._fileChanged;
46
- }
47
- /**
48
- * Test whether the manager has been disposed.
49
- */
50
- get isDisposed() {
51
- return this._isDisposed;
52
- }
53
- /**
54
- * Return the server settings.
55
- */
56
- get serverSettings() {
57
- // TODO: placeholder
58
- return ServerConnection.makeSettings();
59
- }
60
- /**
61
- * Dispose of the resources held by the manager.
62
- */
63
- dispose() {
64
- throw new Error('Method not implemented.');
65
- }
66
48
  /**
67
49
  * Create a new untitled file or directory in the specified directory path.
68
50
  *
@@ -75,16 +57,36 @@ export class Contents {
75
57
  const path = (_a = options === null || options === void 0 ? void 0 : options.path) !== null && _a !== void 0 ? _a : '';
76
58
  const type = (_b = options === null || options === void 0 ? void 0 : options.type) !== null && _b !== void 0 ? _b : 'notebook';
77
59
  const created = new Date().toISOString();
78
- const prefix = path ? `${path}/` : '';
79
- let file;
60
+ let dirname = PathExt.dirname(path);
61
+ const basename = PathExt.basename(path);
62
+ const extname = PathExt.extname(path);
63
+ const item = await this.get(dirname);
64
+ // handle the case of "Save As", where the path points to the new file
65
+ // to create, e.g. subfolder/example-copy.ipynb
80
66
  let name = '';
67
+ if (path && !extname && item) {
68
+ // directory
69
+ dirname = `${path}/`;
70
+ name = '';
71
+ }
72
+ else if (dirname && basename) {
73
+ // file in a subfolder
74
+ dirname = `${dirname}/`;
75
+ name = basename;
76
+ }
77
+ else {
78
+ // file at the top level
79
+ dirname = '';
80
+ name = path;
81
+ }
82
+ let file;
81
83
  switch (type) {
82
84
  case 'directory': {
83
85
  const counter = await this._incrementCounter('directory');
84
- name += `Untitled Folder${counter || ''}`;
86
+ name = `Untitled Folder${counter || ''}`;
85
87
  file = {
86
88
  name,
87
- path: `${prefix}${name}`,
89
+ path: `${dirname}${name}`,
88
90
  last_modified: created,
89
91
  created,
90
92
  format: 'text',
@@ -99,10 +101,10 @@ export class Contents {
99
101
  case 'file': {
100
102
  const ext = (_c = options === null || options === void 0 ? void 0 : options.ext) !== null && _c !== void 0 ? _c : '.txt';
101
103
  const counter = await this._incrementCounter('file');
102
- name += `untitled${counter || ''}${ext}`;
104
+ name = name || `untitled${counter || ''}${ext}`;
103
105
  file = {
104
106
  name,
105
- path: `${prefix}${name}`,
107
+ path: `${dirname}${name}`,
106
108
  last_modified: created,
107
109
  created,
108
110
  format: 'text',
@@ -117,10 +119,10 @@ export class Contents {
117
119
  }
118
120
  default: {
119
121
  const counter = await this._incrementCounter('notebook');
120
- name += `Untitled${counter || ''}.ipynb`;
122
+ name = name || `Untitled${counter || ''}.ipynb`;
121
123
  file = {
122
124
  name,
123
- path: `${prefix}${name}`,
125
+ path: `${dirname}${name}`,
124
126
  last_modified: created,
125
127
  created,
126
128
  format: 'json',
@@ -133,7 +135,7 @@ export class Contents {
133
135
  break;
134
136
  }
135
137
  }
136
- const key = `${prefix}${name}`;
138
+ const key = file.path;
137
139
  await this._storage.setItem(key, file);
138
140
  return file;
139
141
  }
@@ -160,6 +162,9 @@ export class Contents {
160
162
  }
161
163
  const toPath = `${toDir}${name}`;
162
164
  let item = await this.get(path, { content: true });
165
+ if (!item) {
166
+ throw Error(`Could not find file with path ${path}`);
167
+ }
163
168
  item = {
164
169
  ...item,
165
170
  name,
@@ -180,13 +185,13 @@ export class Contents {
180
185
  // remove leading slash
181
186
  path = decodeURIComponent(path.replace(/^\//, ''));
182
187
  if (path === '') {
183
- return await this.getFolder(path);
188
+ return await this._getFolder(path);
184
189
  }
185
190
  const item = await this._storage.getItem(path);
186
- const serverItem = await this.getServerContents(path, options);
191
+ const serverItem = await this._getServerContents(path, options);
187
192
  const model = (item || serverItem);
188
193
  if (!model) {
189
- throw Error(`Could not find file with path ${path}`);
194
+ return null;
190
195
  }
191
196
  if (!(options === null || options === void 0 ? void 0 : options.content)) {
192
197
  return {
@@ -207,7 +212,7 @@ export class Contents {
207
212
  });
208
213
  const serverContents = serverItem
209
214
  ? serverItem.content
210
- : Array.from((await this.getServerDirectory(path)).values());
215
+ : Array.from((await this._getServerDirectory(path)).values());
211
216
  for (const file of serverContents) {
212
217
  if (!contentMap.has(file.name)) {
213
218
  contentMap.set(file.name, file);
@@ -229,131 +234,6 @@ export class Contents {
229
234
  }
230
235
  return model;
231
236
  }
232
- /**
233
- * retrieve the contents for this path from the union of local storage and
234
- * `api/contents/{path}/all.json`.
235
- *
236
- * @param path - The contents path to retrieve
237
- *
238
- * @returns A promise which resolves with a Map of contents, keyed by local file name
239
- */
240
- async getFolder(path) {
241
- const content = new Map();
242
- await this._storage.iterate((item, key) => {
243
- if (key.includes('/')) {
244
- return;
245
- }
246
- const file = item;
247
- content.set(file.path, file);
248
- });
249
- // layer in contents that don't have local overwrites
250
- for (const file of (await this.getServerDirectory(path)).values()) {
251
- if (!content.has(file.path)) {
252
- content.set(file.path, file);
253
- }
254
- }
255
- return {
256
- name: '',
257
- path,
258
- last_modified: new Date(0).toISOString(),
259
- created: new Date(0).toISOString(),
260
- format: 'json',
261
- mimetype: 'application/json',
262
- content: Array.from(content.values()),
263
- size: undefined,
264
- writable: true,
265
- type: 'directory'
266
- };
267
- }
268
- /**
269
- * retrieve the contents for this path from `__index__.json` in the appropriate
270
- * folder.
271
- *
272
- * @param newLocalPath - The new file path.
273
- *
274
- * @returns A promise which resolves with a Map of contents, keyed by local file name
275
- */
276
- async getServerDirectory(path) {
277
- const content = this._serverContents.get(path) || new Map();
278
- if (!this._serverContents.has(path)) {
279
- const apiURL = URLExt.join(PageConfig.getBaseUrl(), 'api/contents', path, 'all.json');
280
- try {
281
- const response = await fetch(apiURL);
282
- const json = JSON.parse(await response.text());
283
- for (const file of json['content']) {
284
- content.set(file.name, file);
285
- }
286
- }
287
- catch (err) {
288
- console.warn(`don't worry, about ${err}... nothing's broken. if there had been a
289
- file at ${apiURL}, you might see some more files.`);
290
- }
291
- this._serverContents.set(path, content);
292
- }
293
- return content;
294
- }
295
- /**
296
- * Attempt to recover the model from `{:path}/__all__.json` file, fall back to
297
- * deriving the model (including content) off the file in `/files/`. Otherwise
298
- * return `null`.
299
- */
300
- async getServerContents(path, options) {
301
- const name = PathExt.basename(path);
302
- const parentContents = await this.getServerDirectory(URLExt.join(path, '..'));
303
- let model = parentContents.get(name) || {
304
- name,
305
- path,
306
- last_modified: new Date(0).toISOString(),
307
- created: new Date(0).toISOString(),
308
- format: 'text',
309
- mimetype: 'text/plain',
310
- type: 'file',
311
- writable: true,
312
- content: null
313
- };
314
- if (options === null || options === void 0 ? void 0 : options.content) {
315
- if (model.type === 'directory') {
316
- const serverContents = await this.getServerDirectory(path);
317
- model = { ...model, content: Array.from(serverContents.values()) };
318
- }
319
- else {
320
- const fileUrl = URLExt.join(PageConfig.getBaseUrl(), 'files', path);
321
- const response = await fetch(fileUrl);
322
- if (!response.ok) {
323
- return null;
324
- }
325
- const mimetype = model.mimetype || response.headers.get('Content-Type');
326
- if (model.type === 'notebook' ||
327
- (mimetype === null || mimetype === void 0 ? void 0 : mimetype.indexOf('json')) !== -1 ||
328
- path.match(/\.(ipynb|[^/]*json[^/]*)$/)) {
329
- model = {
330
- ...model,
331
- content: await response.json(),
332
- format: 'json',
333
- mimetype: model.mimetype || 'application/json'
334
- };
335
- // TODO: this is not great, need a better oracle
336
- }
337
- else if (mimetype.indexOf('xml') !== -1 || mimetype.indexOf('text') !== -1) {
338
- model = {
339
- ...model,
340
- content: await response.text(),
341
- format: 'text',
342
- mimetype: mimetype || 'text/plain'
343
- };
344
- }
345
- else {
346
- model = {
347
- ...model,
348
- content: btoa(String.fromCharCode(...new Uint8Array(await response.arrayBuffer()))),
349
- format: 'base64',
350
- mimetype: mimetype || 'octet/stream'
351
- };
352
- }
353
- }
354
- }
355
- return model;
356
- }
357
237
  /**
358
238
  * Rename a file or directory.
359
239
  *
@@ -400,9 +280,10 @@ export class Contents {
400
280
  */
401
281
  async save(path, options = {}) {
402
282
  var _a;
403
- let item = await this.get(path);
283
+ path = decodeURIComponent(path);
284
+ let item = (await this.get(path)) || (await this.newUntitled({ path }));
404
285
  if (!item) {
405
- item = await this.newUntitled({ path });
286
+ return null;
406
287
  }
407
288
  // override with the new values
408
289
  const modified = new Date().toISOString();
@@ -458,7 +339,11 @@ export class Contents {
458
339
  */
459
340
  async createCheckpoint(path) {
460
341
  var _a;
342
+ path = decodeURIComponent(path);
461
343
  const item = await this.get(path, { content: true });
344
+ if (!item) {
345
+ throw Error(`Could not find file with path ${path}`);
346
+ }
462
347
  const copies = ((_a = (await this._checkpoints.getItem(path))) !== null && _a !== void 0 ? _a : []).filter(item => !!item);
463
348
  copies.push(item);
464
349
  // keep only a certain amount of checkpoints per file
@@ -501,6 +386,7 @@ export class Contents {
501
386
  * @returns A promise which resolves when the checkpoint is restored.
502
387
  */
503
388
  async restoreCheckpoint(path, checkpointID) {
389
+ path = decodeURIComponent(path);
504
390
  const copies = ((await this._checkpoints.getItem(path)) ||
505
391
  []);
506
392
  const id = parseInt(checkpointID);
@@ -516,6 +402,7 @@ export class Contents {
516
402
  * @returns A promise which resolves when the checkpoint is deleted.
517
403
  */
518
404
  async deleteCheckpoint(path, checkpointID) {
405
+ path = decodeURIComponent(path);
519
406
  const copies = ((await this._checkpoints.getItem(path)) ||
520
407
  []);
521
408
  const id = parseInt(checkpointID);
@@ -523,80 +410,136 @@ export class Contents {
523
410
  await this._checkpoints.setItem(path, copies);
524
411
  }
525
412
  /**
526
- * Add an `IDrive` to the manager.
527
- */
528
- addDrive(drive) {
529
- throw new Error('Method not implemented.');
530
- }
531
- /**
532
- * Given a path of the form `drive:local/portion/of/it.txt`
533
- * get the local part of it.
534
- *
535
- * @param path: the path.
536
- *
537
- * @returns The local part of the path.
538
- */
539
- localPath(path) {
540
- throw new Error('Method not implemented.');
541
- }
542
- /**
543
- * Normalize a global path. Reduces '..' and '.' parts, and removes
544
- * leading slashes from the local part of the path, while retaining
545
- * the drive name if it exists.
546
- *
547
- * @param path: the path.
548
- *
549
- * @returns The normalized path.
550
- */
551
- normalize(path) {
552
- throw new Error('Method not implemented.');
553
- }
554
- /**
555
- * Resolve a global path, starting from the root path. Behaves like
556
- * posix-path.resolve, with 3 differences:
557
- * - will never prepend cwd
558
- * - if root has a drive name, the result is prefixed with "<drive>:"
559
- * - before adding drive name, leading slashes are removed
560
- *
561
- * @param path: the path.
562
- *
563
- * @returns The normalized path.
564
- */
565
- resolvePath(root, path) {
566
- throw new Error('Method not implemented.');
567
- }
568
- /**
569
- * Given a path of the form `drive:local/portion/of/it.txt`
570
- * get the name of the drive. If the path is missing
571
- * a drive portion, returns an empty string.
413
+ * retrieve the contents for this path from the union of local storage and
414
+ * `api/contents/{path}/all.json`.
572
415
  *
573
- * @param path: the path.
416
+ * @param path - The contents path to retrieve
574
417
  *
575
- * @returns The drive name for the path, or the empty string.
418
+ * @returns A promise which resolves with a Map of contents, keyed by local file name
576
419
  */
577
- driveName(path) {
578
- throw new Error('Method not implemented.');
420
+ async _getFolder(path) {
421
+ const content = new Map();
422
+ await this._storage.iterate((item, key) => {
423
+ if (key.includes('/')) {
424
+ return;
425
+ }
426
+ const file = item;
427
+ content.set(file.path, file);
428
+ });
429
+ // layer in contents that don't have local overwrites
430
+ for (const file of (await this._getServerDirectory(path)).values()) {
431
+ if (!content.has(file.path)) {
432
+ content.set(file.path, file);
433
+ }
434
+ }
435
+ if (path && content.size === 0) {
436
+ return null;
437
+ }
438
+ return {
439
+ name: '',
440
+ path,
441
+ last_modified: new Date(0).toISOString(),
442
+ created: new Date(0).toISOString(),
443
+ format: 'json',
444
+ mimetype: 'application/json',
445
+ content: Array.from(content.values()),
446
+ size: undefined,
447
+ writable: true,
448
+ type: 'directory'
449
+ };
579
450
  }
580
451
  /**
581
- * Given a path, get a ModelDB.IFactory from the
582
- * relevant backend. Returns `null` if the backend
583
- * does not provide one.
452
+ * Attempt to recover the model from `{:path}/__all__.json` file, fall back to
453
+ * deriving the model (including content) off the file in `/files/`. Otherwise
454
+ * return `null`.
584
455
  */
585
- getModelDBFactory(path) {
586
- throw new Error('Method not implemented.');
456
+ async _getServerContents(path, options) {
457
+ const name = PathExt.basename(path);
458
+ const parentContents = await this._getServerDirectory(URLExt.join(path, '..'));
459
+ let model = parentContents.get(name);
460
+ if (!model) {
461
+ return null;
462
+ }
463
+ model = model || {
464
+ name,
465
+ path,
466
+ last_modified: new Date(0).toISOString(),
467
+ created: new Date(0).toISOString(),
468
+ format: 'text',
469
+ mimetype: 'text/plain',
470
+ type: 'file',
471
+ writable: true,
472
+ content: null
473
+ };
474
+ if (options === null || options === void 0 ? void 0 : options.content) {
475
+ if (model.type === 'directory') {
476
+ const serverContents = await this._getServerDirectory(path);
477
+ model = { ...model, content: Array.from(serverContents.values()) };
478
+ }
479
+ else {
480
+ const fileUrl = URLExt.join(PageConfig.getBaseUrl(), 'files', path);
481
+ const response = await fetch(fileUrl);
482
+ if (!response.ok) {
483
+ return null;
484
+ }
485
+ const mimetype = model.mimetype || response.headers.get('Content-Type');
486
+ if (model.type === 'notebook' ||
487
+ (mimetype === null || mimetype === void 0 ? void 0 : mimetype.indexOf('json')) !== -1 ||
488
+ path.match(/\.(ipynb|[^/]*json[^/]*)$/)) {
489
+ model = {
490
+ ...model,
491
+ content: await response.json(),
492
+ format: 'json',
493
+ mimetype: model.mimetype || 'application/json'
494
+ };
495
+ }
496
+ else if (mimetype.indexOf('text') !== -1 ||
497
+ EXTRA_TEXT_MIME_TYPES.has(mimetype)) {
498
+ model = {
499
+ ...model,
500
+ content: await response.text(),
501
+ format: 'text',
502
+ mimetype: mimetype || 'text/plain'
503
+ };
504
+ }
505
+ else {
506
+ model = {
507
+ ...model,
508
+ content: btoa(String.fromCharCode(...new Uint8Array(await response.arrayBuffer()))),
509
+ format: 'base64',
510
+ mimetype: mimetype || 'octet/stream'
511
+ };
512
+ }
513
+ }
514
+ }
515
+ return model;
587
516
  }
588
517
  /**
589
- * Get an encoded download url given a file path.
590
- *
591
- * @param path - An absolute POSIX file path on the server.
518
+ * retrieve the contents for this path from `__index__.json` in the appropriate
519
+ * folder.
592
520
  *
593
- * #### Notes
594
- * It is expected that the path contains no relative paths.
521
+ * @param newLocalPath - The new file path.
595
522
  *
596
- * The returned URL may include a query parameter.
523
+ * @returns A promise which resolves with a Map of contents, keyed by local file name
597
524
  */
598
- getDownloadUrl(path) {
599
- throw new Error('Method not implemented.');
525
+ async _getServerDirectory(path) {
526
+ const content = this._serverContents.get(path) || new Map();
527
+ if (!this._serverContents.has(path)) {
528
+ const apiURL = URLExt.join(PageConfig.getBaseUrl(), 'api/contents', path, 'all.json');
529
+ try {
530
+ const response = await fetch(apiURL);
531
+ const json = JSON.parse(await response.text());
532
+ for (const file of json['content']) {
533
+ content.set(file.name, file);
534
+ }
535
+ }
536
+ catch (err) {
537
+ console.warn(`don't worry, about ${err}... nothing's broken. if there had been a
538
+ file at ${apiURL}, you might see some more files.`);
539
+ }
540
+ this._serverContents.set(path, content);
541
+ }
542
+ return content;
600
543
  }
601
544
  /**
602
545
  * Increment the counter for a given file type.
package/lib/tokens.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Contents } from '@jupyterlab/services';
1
+ import { Contents as ServerContents } from '@jupyterlab/services';
2
2
  import { Token } from '@lumino/coreutils';
3
3
  /**
4
4
  * The token for the settings service.
@@ -7,5 +7,95 @@ export declare const IContents: Token<IContents>;
7
7
  /**
8
8
  * The interface for the contents service.
9
9
  */
10
- export interface IContents extends Contents.IManager {
10
+ export interface IContents {
11
+ /**
12
+ * Create a new untitled file or directory in the specified directory path.
13
+ *
14
+ * @param options: The options used to create the file.
15
+ *
16
+ * @returns A promise which resolves with the created file content when the file is created.
17
+ */
18
+ newUntitled(options?: ServerContents.ICreateOptions): Promise<ServerContents.IModel | null>;
19
+ /**
20
+ * Copy a file into a given directory.
21
+ *
22
+ * @param path - The original file path.
23
+ * @param toDir - The destination directory path.
24
+ *
25
+ * @returns A promise which resolves with the new contents model when the
26
+ * file is copied.
27
+ *
28
+ * #### Notes
29
+ * The server will select the name of the copied file.
30
+ */
31
+ copy(path: string, toDir: string): Promise<ServerContents.IModel>;
32
+ /**
33
+ * Get a file or directory.
34
+ *
35
+ * @param path: The path to the file.
36
+ * @param options: The options used to fetch the file.
37
+ *
38
+ * @returns A promise which resolves with the file content.
39
+ */
40
+ get(path: string, options?: ServerContents.IFetchOptions): Promise<ServerContents.IModel | null>;
41
+ /**
42
+ * Rename a file or directory.
43
+ *
44
+ * @param oldLocalPath - The original file path.
45
+ * @param newLocalPath - The new file path.
46
+ *
47
+ * @returns A promise which resolves with the new file content model when the file is renamed.
48
+ */
49
+ rename(oldLocalPath: string, newLocalPath: string): Promise<ServerContents.IModel>;
50
+ /**
51
+ * Save a file.
52
+ *
53
+ * @param path - The desired file path.
54
+ * @param options - Optional overrides to the model.
55
+ *
56
+ * @returns A promise which resolves with the file content model when the file is saved.
57
+ */
58
+ save(path: string, options?: Partial<ServerContents.IModel>): Promise<ServerContents.IModel | null>;
59
+ /**
60
+ * Delete a file.
61
+ *
62
+ * @param path - The path to the file.
63
+ */
64
+ delete(path: string): Promise<void>;
65
+ /**
66
+ * Create a checkpoint for a file.
67
+ *
68
+ * @param path - The path of the file.
69
+ *
70
+ * @returns A promise which resolves with the new checkpoint model when the
71
+ * checkpoint is created.
72
+ */
73
+ createCheckpoint(path: string): Promise<ServerContents.ICheckpointModel>;
74
+ /**
75
+ * List available checkpoints for a file.
76
+ *
77
+ * @param path - The path of the file.
78
+ *
79
+ * @returns A promise which resolves with a list of checkpoint models for
80
+ * the file.
81
+ */
82
+ listCheckpoints(path: string): Promise<ServerContents.ICheckpointModel[]>;
83
+ /**
84
+ * Restore a file to a known checkpoint state.
85
+ *
86
+ * @param path - The path of the file.
87
+ * @param checkpointID - The id of the checkpoint to restore.
88
+ *
89
+ * @returns A promise which resolves when the checkpoint is restored.
90
+ */
91
+ restoreCheckpoint(path: string, checkpointID: string): Promise<void>;
92
+ /**
93
+ * Delete a checkpoint for a file.
94
+ *
95
+ * @param path - The path of the file.
96
+ * @param checkpointID - The id of the checkpoint to delete.
97
+ *
98
+ * @returns A promise which resolves when the checkpoint is deleted.
99
+ */
100
+ deleteCheckpoint(path: string, checkpointID: string): Promise<void>;
11
101
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jupyterlite/contents",
3
- "version": "0.1.0-alpha.13",
3
+ "version": "0.1.0-alpha.17",
4
4
  "description": "JupyterLite - Contents",
5
5
  "homepage": "https://github.com/jupyterlite/jupyterlite",
6
6
  "bugs": {
@@ -42,16 +42,15 @@
42
42
  "watch": "tsc -b --watch"
43
43
  },
44
44
  "dependencies": {
45
- "@jupyterlab/nbformat": "~3.1.12",
46
- "@jupyterlab/services": "~6.1.12",
45
+ "@jupyterlab/nbformat": "~3.2.0",
46
+ "@jupyterlab/services": "~6.2.0",
47
47
  "@lumino/coreutils": "^1.8.0",
48
- "@lumino/signaling": "^1.7.0",
49
48
  "localforage": "^1.9.0"
50
49
  },
51
50
  "devDependencies": {
52
51
  "@babel/core": "^7.11.6",
53
52
  "@babel/preset-env": "^7.12.1",
54
- "@jupyterlab/testutils": "~3.1.12",
53
+ "@jupyterlab/testutils": "~3.2.0",
55
54
  "@types/jest": "^26.0.10",
56
55
  "jest": "^26.4.2",
57
56
  "rimraf": "~3.0.0",