@typescript/vfs 1.5.0 → 1.5.1

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/dist/vfs.esm.js CHANGED
@@ -1,27 +1,22 @@
1
1
  function _extends() {
2
- _extends = Object.assign || function (target) {
2
+ _extends = Object.assign ? Object.assign.bind() : function (target) {
3
3
  for (var i = 1; i < arguments.length; i++) {
4
4
  var source = arguments[i];
5
-
6
5
  for (var key in source) {
7
6
  if (Object.prototype.hasOwnProperty.call(source, key)) {
8
7
  target[key] = source[key];
9
8
  }
10
9
  }
11
10
  }
12
-
13
11
  return target;
14
12
  };
15
-
16
13
  return _extends.apply(this, arguments);
17
14
  }
18
15
 
19
16
  var hasLocalStorage = false;
20
-
21
17
  try {
22
18
  hasLocalStorage = typeof localStorage !== "undefined";
23
19
  } catch (error) {}
24
-
25
20
  var hasProcess = typeof process !== "undefined";
26
21
  var shouldDebug = hasLocalStorage && /*#__PURE__*/localStorage.getItem("DEBUG") || hasProcess && process.env.DEBUG;
27
22
  var debugLog = shouldDebug ? console.log : function (_message) {
@@ -37,26 +32,20 @@ var debugLog = shouldDebug ? console.log : function (_message) {
37
32
  * @param compilerOptions the options for this compiler run
38
33
  * @param customTransformers custom transformers for this compiler run
39
34
  */
40
-
41
35
  function createVirtualTypeScriptEnvironment(sys, rootFiles, ts, compilerOptions, customTransformers) {
42
36
  if (compilerOptions === void 0) {
43
37
  compilerOptions = {};
44
38
  }
45
-
46
39
  var mergedCompilerOpts = _extends({}, defaultCompilerOptions(ts), compilerOptions);
47
-
48
40
  var _createVirtualLanguag = createVirtualLanguageServiceHost(sys, rootFiles, mergedCompilerOpts, ts, customTransformers),
49
- languageServiceHost = _createVirtualLanguag.languageServiceHost,
50
- _updateFile = _createVirtualLanguag.updateFile;
51
-
41
+ languageServiceHost = _createVirtualLanguag.languageServiceHost,
42
+ _updateFile = _createVirtualLanguag.updateFile;
52
43
  var languageService = ts.createLanguageService(languageServiceHost);
53
44
  var diagnostics = languageService.getCompilerOptionsDiagnostics();
54
-
55
45
  if (diagnostics.length) {
56
46
  var compilerHost = createVirtualCompilerHost(sys, compilerOptions, ts);
57
47
  throw new Error(ts.formatDiagnostics(diagnostics, compilerHost.compilerHost));
58
48
  }
59
-
60
49
  return {
61
50
  // @ts-ignore
62
51
  name: "vfs",
@@ -64,7 +53,6 @@ function createVirtualTypeScriptEnvironment(sys, rootFiles, ts, compilerOptions,
64
53
  languageService: languageService,
65
54
  getSourceFile: function getSourceFile(fileName) {
66
55
  var _languageService$getP;
67
-
68
56
  return (_languageService$getP = languageService.getProgram()) == null ? void 0 : _languageService$getP.getSourceFile(fileName);
69
57
  },
70
58
  createFile: function createFile(fileName, content) {
@@ -72,26 +60,23 @@ function createVirtualTypeScriptEnvironment(sys, rootFiles, ts, compilerOptions,
72
60
  },
73
61
  updateFile: function updateFile(fileName, content, optPrevTextSpan) {
74
62
  var prevSourceFile = languageService.getProgram().getSourceFile(fileName);
75
-
76
63
  if (!prevSourceFile) {
77
64
  throw new Error("Did not find a source file for " + fileName);
78
65
  }
79
-
80
- var prevFullContents = prevSourceFile.text; // TODO: Validate if the default text span has a fencepost error?
81
-
66
+ var prevFullContents = prevSourceFile.text;
67
+ // TODO: Validate if the default text span has a fencepost error?
82
68
  var prevTextSpan = optPrevTextSpan != null ? optPrevTextSpan : ts.createTextSpan(0, prevFullContents.length);
83
69
  var newText = prevFullContents.slice(0, prevTextSpan.start) + content + prevFullContents.slice(prevTextSpan.start + prevTextSpan.length);
84
70
  var newSourceFile = ts.updateSourceFile(prevSourceFile, newText, {
85
71
  span: prevTextSpan,
86
72
  newLength: content.length
87
73
  });
88
-
89
74
  _updateFile(newSourceFile);
90
75
  }
91
76
  };
92
- } // TODO: This could be replaced by grabbing: https://github.com/microsoft/TypeScript/blob/main/src/lib/libs.json
77
+ }
78
+ // TODO: This could be replaced by grabbing: https://github.com/microsoft/TypeScript/blob/main/src/lib/libs.json
93
79
  // and then using that to generate the list of files from the server, but it is not included in the npm package
94
-
95
80
  /**
96
81
  * Grab the list of lib files for a particular target, will return a bit more than necessary (by including
97
82
  * the dom) but that's OK, we're really working with the constraint that you can't get a list of files
@@ -100,27 +85,24 @@ function createVirtualTypeScriptEnvironment(sys, rootFiles, ts, compilerOptions,
100
85
  * @param target The compiler settings target baseline
101
86
  * @param ts A copy of the TypeScript module
102
87
  */
103
-
104
88
  var knownLibFilesForCompilerOptions = function knownLibFilesForCompilerOptions(compilerOptions, ts) {
105
89
  var target = compilerOptions.target || ts.ScriptTarget.ES5;
106
- var lib = compilerOptions.lib || []; // Note that this will include files which can't be found for particular versions of TS
90
+ var lib = compilerOptions.lib || [];
91
+ // Note that this will include files which can't be found for particular versions of TS
107
92
  // TODO: Replace this with some sort of API call if https://github.com/microsoft/TypeScript/pull/54011
108
93
  // or similar is merged.
109
-
110
94
  var files = ["lib.d.ts", "lib.decorators.d.ts", "lib.decorators.legacy.d.ts", "lib.dom.d.ts", "lib.dom.iterable.d.ts", "lib.webworker.d.ts", "lib.webworker.importscripts.d.ts", "lib.webworker.iterable.d.ts", "lib.scripthost.d.ts", "lib.es5.d.ts", "lib.es6.d.ts", "lib.es2015.collection.d.ts", "lib.es2015.core.d.ts", "lib.es2015.d.ts", "lib.es2015.generator.d.ts", "lib.es2015.iterable.d.ts", "lib.es2015.promise.d.ts", "lib.es2015.proxy.d.ts", "lib.es2015.reflect.d.ts", "lib.es2015.symbol.d.ts", "lib.es2015.symbol.wellknown.d.ts", "lib.es2016.array.include.d.ts", "lib.es2016.d.ts", "lib.es2016.full.d.ts", "lib.es2017.d.ts", "lib.es2017.date.d.ts", "lib.es2017.full.d.ts", "lib.es2017.intl.d.ts", "lib.es2017.object.d.ts", "lib.es2017.sharedmemory.d.ts", "lib.es2017.string.d.ts", "lib.es2017.typedarrays.d.ts", "lib.es2018.asyncgenerator.d.ts", "lib.es2018.asynciterable.d.ts", "lib.es2018.d.ts", "lib.es2018.full.d.ts", "lib.es2018.intl.d.ts", "lib.es2018.promise.d.ts", "lib.es2018.regexp.d.ts", "lib.es2019.array.d.ts", "lib.es2019.d.ts", "lib.es2019.full.d.ts", "lib.es2019.intl.d.ts", "lib.es2019.object.d.ts", "lib.es2019.string.d.ts", "lib.es2019.symbol.d.ts", "lib.es2020.bigint.d.ts", "lib.es2020.d.ts", "lib.es2020.date.d.ts", "lib.es2020.full.d.ts", "lib.es2020.intl.d.ts", "lib.es2020.number.d.ts", "lib.es2020.promise.d.ts", "lib.es2020.sharedmemory.d.ts", "lib.es2020.string.d.ts", "lib.es2020.symbol.wellknown.d.ts", "lib.es2021.d.ts", "lib.es2021.full.d.ts", "lib.es2021.intl.d.ts", "lib.es2021.promise.d.ts", "lib.es2021.string.d.ts", "lib.es2021.weakref.d.ts", "lib.es2022.array.d.ts", "lib.es2022.d.ts", "lib.es2022.error.d.ts", "lib.es2022.full.d.ts", "lib.es2022.intl.d.ts", "lib.es2022.object.d.ts", "lib.es2022.regexp.d.ts", "lib.es2022.sharedmemory.d.ts", "lib.es2022.string.d.ts", "lib.es2023.array.d.ts", "lib.es2023.collection.d.ts", "lib.es2023.d.ts", "lib.es2023.full.d.ts", "lib.esnext.array.d.ts", "lib.esnext.asynciterable.d.ts", "lib.esnext.bigint.d.ts", "lib.esnext.d.ts", "lib.esnext.decorators.d.ts", "lib.esnext.disposable.d.ts", "lib.esnext.full.d.ts", "lib.esnext.intl.d.ts", "lib.esnext.promise.d.ts", "lib.esnext.string.d.ts", "lib.esnext.symbol.d.ts", "lib.esnext.weakref.d.ts"];
111
95
  var targetToCut = ts.ScriptTarget[target];
112
96
  var matches = files.filter(function (f) {
113
97
  return f.startsWith("lib." + targetToCut.toLowerCase());
114
98
  });
115
99
  var targetCutIndex = files.indexOf(matches.pop());
116
-
117
100
  var getMax = function getMax(array) {
118
101
  return array && array.length ? array.reduce(function (max, current) {
119
102
  return current > max ? current : max;
120
103
  }) : undefined;
121
- }; // Find the index for everything in
122
-
123
-
104
+ };
105
+ // Find the index for everything in
124
106
  var indexesForCutting = lib.map(function (lib) {
125
107
  var matches = files.filter(function (f) {
126
108
  return f.startsWith("lib." + lib.toLowerCase());
@@ -140,16 +122,13 @@ var knownLibFilesForCompilerOptions = function knownLibFilesForCompilerOptions(c
140
122
  * The first two args are un-used, but kept around so as to not cause a
141
123
  * semver major bump for no gain to module users.
142
124
  */
143
-
144
125
  var createDefaultMapFromNodeModules = function createDefaultMapFromNodeModules(_compilerOptions, _ts, tsLibDirectory) {
145
126
  var path = requirePath();
146
127
  var fs = requireFS();
147
-
148
128
  var getLib = function getLib(name) {
149
129
  var lib = tsLibDirectory || path.dirname(require.resolve("typescript"));
150
130
  return fs.readFileSync(path.join(lib, name), "utf8");
151
131
  };
152
-
153
132
  var libFiles = fs.readdirSync(tsLibDirectory || path.dirname(require.resolve("typescript")));
154
133
  var knownLibFiles = libFiles.filter(function (f) {
155
134
  return f.startsWith("lib.") && f.endsWith(".d.ts");
@@ -163,18 +142,15 @@ var createDefaultMapFromNodeModules = function createDefaultMapFromNodeModules(_
163
142
  /**
164
143
  * Adds recursively files from the FS into the map based on the folder
165
144
  */
166
-
167
145
  var addAllFilesFromFolder = function addAllFilesFromFolder(map, workingDir) {
168
146
  var path = requirePath();
169
147
  var fs = requireFS();
170
-
171
148
  var walk = function walk(dir) {
172
149
  var results = [];
173
150
  var list = fs.readdirSync(dir);
174
151
  list.forEach(function (file) {
175
152
  file = path.join(dir, file);
176
153
  var stat = fs.statSync(file);
177
-
178
154
  if (stat && stat.isDirectory()) {
179
155
  /* Recurse into a subdirectory */
180
156
  results = results.concat(walk(file));
@@ -185,20 +161,17 @@ var addAllFilesFromFolder = function addAllFilesFromFolder(map, workingDir) {
185
161
  });
186
162
  return results;
187
163
  };
188
-
189
164
  var allFiles = walk(workingDir);
190
165
  allFiles.forEach(function (lib) {
191
166
  var fsPath = "/node_modules/@types" + lib.replace(workingDir, "");
192
167
  var content = fs.readFileSync(lib, "utf8");
193
168
  var validExtensions = [".ts", ".tsx"];
194
-
195
169
  if (validExtensions.includes(path.extname(fsPath))) {
196
170
  map.set(fsPath, content);
197
171
  }
198
172
  });
199
173
  };
200
174
  /** Adds all files from node_modules/@types into the FS Map */
201
-
202
175
  var addFilesForTypesIntoFolder = function addFilesForTypesIntoFolder(map) {
203
176
  return addAllFilesFromFolder(map, "node_modules/@types");
204
177
  };
@@ -214,22 +187,18 @@ var addFilesForTypesIntoFolder = function addFilesForTypesIntoFolder(map) {
214
187
  * @param fetcher an optional replacement for the global fetch function (tests mainly)
215
188
  * @param storer an optional replacement for the localStorage global (tests mainly)
216
189
  */
217
-
218
190
  var createDefaultMapFromCDN = function createDefaultMapFromCDN(options, version, cache, ts, lzstring, fetcher, storer) {
219
191
  var fetchlike = fetcher || fetch;
220
192
  var fsMap = new Map();
221
193
  var files = knownLibFilesForCompilerOptions(options, ts);
222
194
  var prefix = "https://typescript.azureedge.net/cdn/" + version + "/typescript/lib/";
223
-
224
195
  function zip(str) {
225
196
  return lzstring ? lzstring.compressToUTF16(str) : str;
226
197
  }
227
-
228
198
  function unzip(str) {
229
199
  return lzstring ? lzstring.decompressFromUTF16(str) : str;
230
- } // Map the known libs to a node fetch promise, then return the contents
231
-
232
-
200
+ }
201
+ // Map the known libs to a node fetch promise, then return the contents
233
202
  function uncached() {
234
203
  return Promise.all(files.map(function (lib) {
235
204
  return fetchlike(prefix + lib).then(function (resp) {
@@ -239,11 +208,11 @@ var createDefaultMapFromCDN = function createDefaultMapFromCDN(options, version,
239
208
  contents.forEach(function (text, index) {
240
209
  return fsMap.set("/" + files[index], text);
241
210
  });
242
- }) // Return a NOOP for .d.ts files which aren't in the current build of TypeScript
211
+ })
212
+ // Return a NOOP for .d.ts files which aren't in the current build of TypeScript
243
213
  ["catch"](function () {});
244
- } // A localstorage and lzzip aware version of the lib files
245
-
246
-
214
+ }
215
+ // A localstorage and lzzip aware version of the lib files
247
216
  function cached() {
248
217
  var storelike = storer || localStorage;
249
218
  var keys = Object.keys(storelike);
@@ -256,7 +225,6 @@ var createDefaultMapFromCDN = function createDefaultMapFromCDN(options, version,
256
225
  return Promise.all(files.map(function (lib) {
257
226
  var cacheKey = "ts-lib-" + version + "-" + lib;
258
227
  var content = storelike.getItem(cacheKey);
259
-
260
228
  if (!content) {
261
229
  // Make the API call and store the text concent in the cache
262
230
  return fetchlike(prefix + lib).then(function (resp) {
@@ -264,7 +232,8 @@ var createDefaultMapFromCDN = function createDefaultMapFromCDN(options, version,
264
232
  }).then(function (t) {
265
233
  storelike.setItem(cacheKey, zip(t));
266
234
  return t;
267
- }) // Return a NOOP for .d.ts files which aren't in the current build of TypeScript
235
+ })
236
+ // Return a NOOP for .d.ts files which aren't in the current build of TypeScript
268
237
  ["catch"](function () {});
269
238
  } else {
270
239
  return Promise.resolve(unzip(content));
@@ -278,23 +247,19 @@ var createDefaultMapFromCDN = function createDefaultMapFromCDN(options, version,
278
247
  });
279
248
  });
280
249
  }
281
-
282
250
  var func = cache ? cached : uncached;
283
251
  return func().then(function () {
284
252
  return fsMap;
285
253
  });
286
254
  };
287
-
288
255
  function notImplemented(methodName) {
289
256
  throw new Error("Method '" + methodName + "' is not implemented.");
290
257
  }
291
-
292
258
  function audit(name, fn) {
293
259
  return function () {
294
260
  for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
295
261
  args[_key] = arguments[_key];
296
262
  }
297
-
298
263
  var res = fn.apply(void 0, args);
299
264
  var smallres = typeof res === "string" ? res.slice(0, 80) + "..." : res;
300
265
  debugLog.apply(void 0, ["> " + name].concat(args));
@@ -303,8 +268,6 @@ function audit(name, fn) {
303
268
  };
304
269
  }
305
270
  /** The default compiler options if TypeScript could ever change the compiler options */
306
-
307
-
308
271
  var defaultCompilerOptions = function defaultCompilerOptions(ts) {
309
272
  return _extends({}, ts.getDefaultCompilerOptions(), {
310
273
  jsx: ts.JsxEmit.React,
@@ -316,9 +279,8 @@ var defaultCompilerOptions = function defaultCompilerOptions(ts) {
316
279
  skipDefaultLibCheck: true,
317
280
  moduleResolution: ts.ModuleResolutionKind.NodeJs
318
281
  });
319
- }; // "/DOM.d.ts" => "/lib.dom.d.ts"
320
-
321
-
282
+ };
283
+ // "/DOM.d.ts" => "/lib.dom.d.ts"
322
284
  var libize = function libize(path) {
323
285
  return path.replace("/", "/lib.").toLowerCase();
324
286
  };
@@ -326,8 +288,6 @@ var libize = function libize(path) {
326
288
  * Creates an in-memory System object which can be used in a TypeScript program, this
327
289
  * is what provides read/write aspects of the virtual fs
328
290
  */
329
-
330
-
331
291
  function createSystem(files) {
332
292
  return {
333
293
  args: [],
@@ -379,13 +339,12 @@ function createSystem(files) {
379
339
  * a set of virtual files which are prioritised over the FS versions, then a path to the root of your
380
340
  * project (basically the folder your node_modules lives)
381
341
  */
382
-
383
342
  function createFSBackedSystem(files, _projectRoot, ts, tsLibDirectory) {
384
343
  // We need to make an isolated folder for the tsconfig, but also need to be able to resolve the
385
344
  // existing node_modules structures going back through the history
386
345
  var root = _projectRoot + "/vfs";
387
- var path = requirePath(); // The default System in TypeScript
388
-
346
+ var path = requirePath();
347
+ // The default System in TypeScript
389
348
  var nodeSys = ts.sys;
390
349
  var tsLib = tsLibDirectory != null ? tsLibDirectory : path.dirname(require.resolve("typescript"));
391
350
  return {
@@ -404,15 +363,13 @@ function createFSBackedSystem(files, _projectRoot, ts, tsLibDirectory) {
404
363
  }),
405
364
  exit: nodeSys.exit,
406
365
  fileExists: audit("fileExists", function (fileName) {
407
- if (files.has(fileName)) return true; // Don't let other tsconfigs end up touching the vfs
408
-
366
+ if (files.has(fileName)) return true;
367
+ // Don't let other tsconfigs end up touching the vfs
409
368
  if (fileName.includes("tsconfig.json") || fileName.includes("tsconfig.json")) return false;
410
-
411
369
  if (fileName.startsWith("/lib")) {
412
370
  var tsLibName = tsLib + "/" + fileName.replace("/", "");
413
371
  return nodeSys.fileExists(tsLibName);
414
372
  }
415
-
416
373
  return nodeSys.fileExists(fileName);
417
374
  }),
418
375
  getCurrentDirectory: function getCurrentDirectory() {
@@ -431,19 +388,15 @@ function createFSBackedSystem(files, _projectRoot, ts, tsLibDirectory) {
431
388
  }),
432
389
  readFile: audit("readFile", function (fileName) {
433
390
  if (files.has(fileName)) return files.get(fileName);
434
-
435
391
  if (fileName.startsWith("/lib")) {
436
392
  var tsLibName = tsLib + "/" + fileName.replace("/", "");
437
393
  var result = nodeSys.readFile(tsLibName);
438
-
439
394
  if (!result) {
440
395
  var libs = nodeSys.readDirectory(tsLib);
441
396
  throw new Error("TSVFS: A request was made for " + tsLibName + " but there wasn't a file found in the file map. You likely have a mismatch in the compiler options for the CDN download vs the compiler program. Existing Libs: " + libs + ".");
442
397
  }
443
-
444
398
  return result;
445
399
  }
446
-
447
400
  return nodeSys.readFile(fileName);
448
401
  }),
449
402
  resolvePath: function resolvePath(path) {
@@ -465,15 +418,12 @@ function createFSBackedSystem(files, _projectRoot, ts, tsLibDirectory) {
465
418
  * which works with TypeScript objects - returns both a compiler host, and a way to add new SourceFile
466
419
  * instances to the in-memory file system.
467
420
  */
468
-
469
421
  function createVirtualCompilerHost(sys, compilerOptions, ts) {
470
422
  var sourceFiles = new Map();
471
-
472
423
  var save = function save(sourceFile) {
473
424
  sourceFiles.set(sourceFile.fileName, sourceFile);
474
425
  return sourceFile;
475
426
  };
476
-
477
427
  var vHost = {
478
428
  compilerHost: _extends({}, sys, {
479
429
  getCanonicalFileName: function getCanonicalFileName(fileName) {
@@ -482,6 +432,7 @@ function createVirtualCompilerHost(sys, compilerOptions, ts) {
482
432
  getDefaultLibFileName: function getDefaultLibFileName() {
483
433
  return "/" + ts.getDefaultLibFileName(compilerOptions);
484
434
  },
435
+ // '/lib.d.ts',
485
436
  // getDefaultLibLocation: () => '/',
486
437
  getDirectories: function getDirectories() {
487
438
  return [];
@@ -508,17 +459,13 @@ function createVirtualCompilerHost(sys, compilerOptions, ts) {
508
459
  /**
509
460
  * Creates an object which can host a language service against the virtual file-system
510
461
  */
511
-
512
462
  function createVirtualLanguageServiceHost(sys, rootFiles, compilerOptions, ts, customTransformers) {
513
463
  var fileNames = [].concat(rootFiles);
514
-
515
464
  var _createVirtualCompile = createVirtualCompilerHost(sys, compilerOptions, ts),
516
- compilerHost = _createVirtualCompile.compilerHost,
517
- _updateFile2 = _createVirtualCompile.updateFile;
518
-
465
+ compilerHost = _createVirtualCompile.compilerHost,
466
+ _updateFile2 = _createVirtualCompile.updateFile;
519
467
  var fileVersions = new Map();
520
468
  var projectVersion = 0;
521
-
522
469
  var languageServiceHost = _extends({}, compilerHost, {
523
470
  getProjectVersion: function getProjectVersion() {
524
471
  return projectVersion.toString();
@@ -542,11 +489,9 @@ function createVirtualLanguageServiceHost(sys, rootFiles, compilerOptions, ts, c
542
489
  },
543
490
  getScriptSnapshot: function getScriptSnapshot(fileName) {
544
491
  var contents = sys.readFile(fileName);
545
-
546
- if (contents) {
492
+ if (contents && typeof contents === "string") {
547
493
  return ts.ScriptSnapshot.fromString(contents);
548
494
  }
549
-
550
495
  return;
551
496
  },
552
497
  getScriptVersion: function getScriptVersion(fileName) {
@@ -554,27 +499,22 @@ function createVirtualLanguageServiceHost(sys, rootFiles, compilerOptions, ts, c
554
499
  },
555
500
  writeFile: sys.writeFile
556
501
  });
557
-
558
502
  var lsHost = {
559
503
  languageServiceHost: languageServiceHost,
560
504
  updateFile: function updateFile(sourceFile) {
561
505
  projectVersion++;
562
506
  fileVersions.set(sourceFile.fileName, projectVersion.toString());
563
-
564
507
  if (!fileNames.includes(sourceFile.fileName)) {
565
508
  fileNames.push(sourceFile.fileName);
566
509
  }
567
-
568
510
  _updateFile2(sourceFile);
569
511
  }
570
512
  };
571
513
  return lsHost;
572
514
  }
573
-
574
515
  var requirePath = function requirePath() {
575
516
  return require(String.fromCharCode(112, 97, 116, 104));
576
517
  };
577
-
578
518
  var requireFS = function requireFS() {
579
519
  return require(String.fromCharCode(102, 115));
580
520
  };