custom-worker.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // This example uses @typescript/vfs to create a virtual TS program
  2. // which can do work on a bg thread.
  3. // This version of the vfs edits the global scope (in the case of a webworker, this is 'self')
  4. importScripts("https://unpkg.com/@typescript/vfs@1.3.0/dist/vfs.globals.js")
  5. /** @type { import("@typescript/vfs") } */
  6. const tsvfs = globalThis.tsvfs
  7. /** @type {import("../src/tsWorker").CustomTSWebWorkerFactory }*/
  8. const worker = (TypeScriptWorker, ts, libFileMap) => {
  9. return class MonacoTSWorker extends TypeScriptWorker {
  10. // Adds a custom function to the webworker
  11. async getDTSEmitForFile(fileName) {
  12. const result = await this.getEmitOutput(fileName)
  13. const firstDTS = result.outputFiles.find(o => o.name.endsWith(".d.ts"))
  14. return (firstDTS && firstDTS.text) || ""
  15. }
  16. async printAST(fileName) {
  17. console.log("Creating virtual TS project")
  18. const compilerOptions = this.getCompilationSettings()
  19. const fsMap = new Map()
  20. for (const key of Object.keys(libFileMap)) {
  21. fsMap.set(key, "/" + libFileMap[key])
  22. }
  23. const thisCode = await this.getScriptText(fileName)
  24. fsMap.set("index.ts", thisCode)
  25. console.log("Starting up TS program")
  26. const system = tsvfs.createSystem(fsMap)
  27. const host = tsvfs.createVirtualCompilerHost(system, compilerOptions, ts)
  28. const program = ts.createProgram({
  29. rootNames: [...fsMap.keys()],
  30. options: compilerOptions,
  31. host: host.compilerHost,
  32. })
  33. // Now I can look at the AST for the .ts file too
  34. const mainSrcFile = program.getSourceFile("index.ts")
  35. let miniAST = "SourceFile"
  36. const recurse = (parent, depth) => {
  37. if (depth > 5) return
  38. ts.forEachChild(parent, node => {
  39. const spaces = " ".repeat(depth + 1)
  40. miniAST += `\n${spaces}${ts.SyntaxKind[node.kind]}`
  41. recurse(node, depth + 1)
  42. })
  43. }
  44. recurse(mainSrcFile, 0)
  45. return miniAST
  46. }
  47. }
  48. }
  49. self.customTSWorkerFactory = worker