@teambit/typescript 0.0.526 → 0.0.530

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.
@@ -343,7 +343,7 @@ class TypescriptCompiler {
343
343
 
344
344
  async writeTsConfig(dirs) {
345
345
  const tsconfigStr = this.stringifyTsconfig(this.options.tsconfig);
346
- await Promise.all(dirs.map(capsuleDir => _fsExtra().default.writeFile(_path().default.join(capsuleDir, 'tsconfig.json'), tsconfigStr)));
346
+ await Promise.all(dirs.map(dir => _fsExtra().default.writeFile(_path().default.join(dir, 'tsconfig.json'), tsconfigStr)));
347
347
  }
348
348
 
349
349
  stringifyTsconfig(tsconfig) {
@@ -1 +1 @@
1
- {"version":3,"sources":["typescript.compiler.ts"],"names":["TypescriptCompiler","constructor","id","logger","options","tsModule","distDir","distGlobPatterns","shouldCopyNonSupportedFiles","artifactName","tsconfig","compilerOptions","outDir","displayConfig","stringifyTsconfig","transpileFile","fileContent","isFileSupported","filePath","compilerOptionsFromTsconfig","convertCompilerOptionsFromJson","errors","length","formattedErrors","formatDiagnosticsWithColorAndContext","getFormatDiagnosticsHost","Error","sourceRoot","componentDir","rootDir","result","transpileModule","fileName","reportDiagnostics","diagnostics","formatHost","error","outputPath","replaceFileExtToJs","outputFiles","outputText","sourceMapText","push","preBuild","context","capsules","capsuleNetwork","seedersCapsules","capsuleDirs","map","capsule","path","writeTsConfig","writeTypes","writeNpmIgnore","build","componentsResults","runTscBuild","artifacts","getArtifactDefinition","postBuild","Promise","all","packageJson","PackageJsonFile","loadFromCapsuleSync","packageJsonObject","types","write","generatedBy","name","globPatterns","getDistPathBySrcPath","srcPath","fileWithJSExtIfNeeded","join","isJsAndCompile","compileJs","endsWith","isJsxAndCompile","compileJsx","network","capsulesRootDir","graphCapsules","getAllCapsuleDirs","getCanonicalFileName","p","getCurrentDirectory","getNewLine","sys","newLine","currentComponentResult","reportDiagnostic","diagnostic","errorStr","process","stdout","isTTY","formatDiagnostic","file","BitError","consoleFailure","component","reportSolutionBuilderStatus","diag","msg","messageText","debug","errorCounter","errorCount","info","host","createSolutionBuilderHost","undefined","writeProjectReferencesTsConfig","solutionBuilder","createSolutionBuilder","verbose","nextProject","longProcessLogger","createLongProcessLogger","getNextInvalidatedProject","capsulePath","project","replace","currentComponentId","getIdByPathInCapsule","logProgress","toString","getCapsule","startTime","Date","now","done","endTime","end","dirs","typePath","contents","fs","readFile","filename","basename","dir","pathExists","outputFile","NPM_IGNORE_FILE","npmIgnorePath","npmIgnoreEntriesStr","appendFile","projects","files","references","tsconfigStr","writeFile","capsuleDir","JSON","stringify","fileExtension","extname","RegExp","version"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;;;;;AAGO,MAAMA,kBAAN,CAA6C;AAKlDC,EAAAA,WAAW,CACAC,EADA,EAEDC,MAFC,EAGDC,OAHC,EAIDC,QAJC,EAKT;AAAA;;AAAA,SAJSH,EAIT,GAJSA,EAIT;AAAA,SAHQC,MAGR,GAHQA,MAGR;AAAA,SAFQC,OAER,GAFQA,OAER;AAAA,SADQC,QACR,GADQA,QACR;AAAA;AAAA;AAAA;AAAA;AAAA,yDAYY,YAZZ;AACA,SAAKC,OAAL,GAAeF,OAAO,CAACE,OAAR,IAAmB,MAAlC;AACA,SAAKC,gBAAL,GAAwBH,OAAO,CAACG,gBAAR,IAA4B,CAAE,GAAE,KAAKD,OAAQ,KAAjB,EAAwB,IAAG,KAAKA,OAAQ,uBAAxC,CAApD;AACA,SAAKE,2BAAL,GACE,OAAOJ,OAAO,CAACI,2BAAf,KAA+C,SAA/C,GAA2DJ,OAAO,CAACI,2BAAnE,GAAiG,IADnG;AAEA,SAAKC,YAAL,GAAoBL,O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AV,EAAmB,eAAnB,CAAb,EAAkD4H,WAAlD,CAAN;AACD;;AAE0B,QAAbrG,aAAa,CAACoF,IAAD,EAAiB;AAC1C,UAAMiB,WAAW,GAAG,KAAK3I,iBAAL,CAAuB,KAAKV,OAAL,CAAaM,QAApC,CAApB;AACA,UAAMmD,OAAO,CAACC,GAAR,CAAY0E,IAAI,CAACvF,GAAL,CAAU0G,UAAD,IAAgBhB,mBAAGe,SAAH,CAAavG,gBAAKwB,IAAL,CAAUgF,UAAV,EAAsB,eAAtB,CAAb,EAAqDF,WAArD,CAAzB,CAAZ,CAAN;AACD;;AAEO3I,EAAAA,iBAAiB,CAACJ,QAAD,EAAW;AAClC,WAAOkJ,IAAI,CAACC,SAAL,CAAenJ,QAAf,EAAyBuG,SAAzB,EAAoC,CAApC,CAAP;AACD;;AAEO3E,EAAAA,kBAAkB,CAACpB,QAAD,EAA2B;AACnD,QAAI,CAAC,KAAKD,eAAL,CAAqBC,QAArB,CAAL,EAAqC,OAAOA,QAAP;;AACrC,UAAM4I,aAAa,GAAG3G,gBAAK4G,OAAL,CAAa7I,QAAb,CAAtB;;AACA,WAAOA,QAAQ,CAAC0G,OAAT,CAAiB,IAAIoC,MAAJ,CAAY,GAAEF,aAAc,GAA5B,CAAjB,EAAkD,KAAlD,CAAP,CAHmD,CAGc;AAClE;;AAEDG,EAAAA,OAAO,GAAG;AACR,WAAO,KAAK5J,QAAL,CAAc4J,OAArB;AACD;;AAxRiD","sourcesContent":["import { BuildContext, BuiltTaskResult, ComponentResult } from '@teambit/builder';\nimport { Compiler, TranspileFileParams, TranspileFileOutput } from '@teambit/compiler';\nimport { Network } from '@teambit/isolator';\nimport { Logger } from '@teambit/logger';\nimport fs from 'fs-extra';\nimport path from 'path';\nimport ts from 'typescript';\nimport { BitError } from '@teambit/bit-error';\nimport PackageJsonFile from '@teambit/legacy/dist/consumer/component/package-json-file';\nimport { TypeScriptCompilerOptions } from './compiler-options';\n\nexport class TypescriptCompiler implements Compiler {\n distDir: string;\n distGlobPatterns: string[];\n shouldCopyNonSupportedFiles: boolean;\n artifactName: string;\n constructor(\n readonly id: string,\n private logger: Logger,\n private options: TypeScriptCompilerOptions,\n private tsModule: typeof ts\n ) {\n this.distDir = options.distDir || 'dist';\n this.distGlobPatterns = options.distGlobPatterns || [`${this.distDir}/**`, `!${this.distDir}/tsconfig.tsbuildinfo`];\n this.shouldCopyNonSupportedFiles =\n typeof options.shouldCopyNonSupportedFiles === 'boolean' ? options.shouldCopyNonSupportedFiles : true;\n this.artifactName = options.artifactName || 'dist';\n this.options.tsconfig ||= {};\n this.options.tsconfig.compilerOptions ||= {};\n // mutate the outDir, otherwise, on capsules, the dists might be written to a different directory and make confusion\n this.options.tsconfig.compilerOptions.outDir = this.distDir;\n }\n\n displayName = 'TypeScript';\n\n displayConfig() {\n return this.stringifyTsconfig(this.options.tsconfig);\n }\n\n /**\n * compile one file on the workspace\n */\n transpileFile(fileContent: string, options: TranspileFileParams): TranspileFileOutput {\n if (!this.isFileSupported(options.filePath)) {\n return null; // file is not supported\n }\n const compilerOptionsFromTsconfig = this.tsModule.convertCompilerOptionsFromJson(\n this.options.tsconfig.compilerOptions,\n '.'\n );\n if (compilerOptionsFromTsconfig.errors.length) {\n // :TODO @david replace to a more concrete error type and put in 'exceptions' directory here.\n const formattedErrors = this.tsModule.formatDiagnosticsWithColorAndContext(\n compilerOptionsFromTsconfig.errors,\n this.getFormatDiagnosticsHost()\n );\n throw new Error(`failed parsing the tsconfig.json.\\n${formattedErrors}`);\n }\n\n const compilerOptions = compilerOptionsFromTsconfig.options;\n compilerOptions.sourceRoot = options.componentDir;\n compilerOptions.rootDir = '.';\n const result = this.tsModule.transpileModule(fileContent, {\n compilerOptions,\n fileName: options.filePath,\n reportDiagnostics: true,\n });\n\n if (result.diagnostics && result.diagnostics.length) {\n const formatHost = this.getFormatDiagnosticsHost();\n const error = this.tsModule.formatDiagnosticsWithColorAndContext(result.diagnostics, formatHost);\n\n // :TODO @david please replace to a more concrete error type and put in 'exceptions' directory here.\n throw new Error(error);\n }\n\n const outputPath = this.replaceFileExtToJs(options.filePath);\n const outputFiles = [{ outputText: result.outputText, outputPath }];\n if (result.sourceMapText) {\n outputFiles.push({\n outputText: result.sourceMapText,\n outputPath: `${outputPath}.map`,\n });\n }\n return outputFiles;\n }\n\n async preBuild(context: BuildContext) {\n const capsules = context.capsuleNetwork.seedersCapsules;\n const capsuleDirs = capsules.map((capsule) => capsule.path);\n await this.writeTsConfig(capsuleDirs);\n await this.writeTypes(capsuleDirs);\n await this.writeNpmIgnore(capsuleDirs);\n }\n\n /**\n * compile multiple components on the capsules\n */\n async build(context: BuildContext): Promise<BuiltTaskResult> {\n const componentsResults = await this.runTscBuild(context.capsuleNetwork);\n\n return {\n artifacts: this.getArtifactDefinition(),\n componentsResults,\n };\n }\n\n async postBuild(context: BuildContext) {\n await Promise.all(\n context.capsuleNetwork.seedersCapsules.map(async (capsule) => {\n const packageJson = PackageJsonFile.loadFromCapsuleSync(capsule.path);\n // the types['index.ts'] is needed only during the build to avoid errors when tsc finds the\n // same type once in the d.ts and once in the ts file.\n if (packageJson.packageJsonObject.types) {\n delete packageJson.packageJsonObject.types;\n await packageJson.write();\n }\n })\n );\n }\n\n getArtifactDefinition() {\n return [\n {\n generatedBy: this.id,\n name: this.artifactName,\n globPatterns: this.distGlobPatterns,\n },\n ];\n }\n\n /**\n * given a source file, return its parallel in the dists. e.g. index.ts => dist/index.js\n */\n getDistPathBySrcPath(srcPath: string) {\n const fileWithJSExtIfNeeded = this.replaceFileExtToJs(srcPath);\n return path.join(this.distDir, fileWithJSExtIfNeeded);\n }\n\n /**\n * whether typescript is able to compile the given path\n */\n isFileSupported(filePath: string): boolean {\n const isJsAndCompile = !!this.options.compileJs && filePath.endsWith('.js');\n const isJsxAndCompile = !!this.options.compileJsx && filePath.endsWith('.jsx');\n return (\n (filePath.endsWith('.ts') || filePath.endsWith('.tsx') || isJsAndCompile || isJsxAndCompile) &&\n !filePath.endsWith('.d.ts')\n );\n }\n\n /**\n * we have two options here:\n * 1. pass all capsules-dir at the second parameter of createSolutionBuilder and then no\n * need to write the main tsconfig.json with all the references.\n * 2. write main tsconfig.json and pass the capsules root-dir.\n * we went with option #2 because it'll be easier for users to go to the capsule-root and run\n * `tsc --build` to debug issues.\n */\n private async runTscBuild(network: Network): Promise<ComponentResult[]> {\n const rootDir = network.capsulesRootDir;\n const capsules = network.graphCapsules;\n const capsuleDirs = capsules.getAllCapsuleDirs();\n const formatHost = {\n getCanonicalFileName: (p) => p,\n getCurrentDirectory: () => '', // it helps to get the files with absolute paths\n getNewLine: () => this.tsModule.sys.newLine,\n };\n const componentsResults: ComponentResult[] = [];\n let currentComponentResult: Partial<ComponentResult> = { errors: [] };\n const reportDiagnostic = (diagnostic: ts.Diagnostic) => {\n const errorStr = process.stdout.isTTY\n ? this.tsModule.formatDiagnosticsWithColorAndContext([diagnostic], formatHost)\n : this.tsModule.formatDiagnostic(diagnostic, formatHost);\n if (!diagnostic.file) {\n // the error is general and not related to a specific file. e.g. tsconfig is missing.\n throw new BitError(errorStr);\n }\n this.logger.consoleFailure(errorStr);\n if (!currentComponentResult.component || !currentComponentResult.errors) {\n throw new Error(`currentComponentResult is not defined yet for ${diagnostic.file}`);\n }\n currentComponentResult.errors.push(errorStr);\n };\n // this only works when `verbose` is `true` in the `ts.createSolutionBuilder` function.\n const reportSolutionBuilderStatus = (diag: ts.Diagnostic) => {\n const msg = diag.messageText as string;\n this.logger.debug(msg);\n };\n const errorCounter = (errorCount: number) => {\n this.logger.info(`total error found: ${errorCount}`);\n };\n const host = this.tsModule.createSolutionBuilderHost(\n undefined,\n undefined,\n reportDiagnostic,\n reportSolutionBuilderStatus,\n errorCounter\n );\n await this.writeProjectReferencesTsConfig(rootDir, capsuleDirs);\n const solutionBuilder = this.tsModule.createSolutionBuilder(host, [rootDir], { verbose: true });\n let nextProject;\n const longProcessLogger = this.logger.createLongProcessLogger('compile typescript components', capsules.length);\n // eslint-disable-next-line no-cond-assign\n while ((nextProject = solutionBuilder.getNextInvalidatedProject())) {\n // regex to make sure it will work correctly for both linux and windows\n // it replaces both /tsconfig.json and \\tsocnfig.json\n const capsulePath = nextProject.project.replace(/[/\\\\]tsconfig.json/, '');\n const currentComponentId = capsules.getIdByPathInCapsule(capsulePath);\n if (!currentComponentId) throw new Error(`unable to find component for ${capsulePath}`);\n longProcessLogger.logProgress(currentComponentId.toString());\n const capsule = capsules.getCapsule(currentComponentId);\n if (!capsule) throw new Error(`unable to find capsule for ${currentComponentId.toString()}`);\n currentComponentResult.component = capsule.component;\n currentComponentResult.startTime = Date.now();\n nextProject.done();\n currentComponentResult.endTime = Date.now();\n componentsResults.push({ ...currentComponentResult } as ComponentResult);\n currentComponentResult = { errors: [] };\n }\n longProcessLogger.end();\n\n return componentsResults;\n }\n\n private getFormatDiagnosticsHost(): ts.FormatDiagnosticsHost {\n return {\n getCanonicalFileName: (p) => p,\n getCurrentDirectory: this.tsModule.sys.getCurrentDirectory,\n getNewLine: () => this.tsModule.sys.newLine,\n };\n }\n\n private async writeTypes(dirs: string[]) {\n await Promise.all(\n this.options.types.map(async (typePath) => {\n const contents = await fs.readFile(typePath, 'utf8');\n const filename = path.basename(typePath);\n\n await Promise.all(\n dirs.map(async (dir) => {\n const filePath = path.join(dir, 'types', filename);\n if (!(await fs.pathExists(filePath))) {\n await fs.outputFile(filePath, contents);\n }\n })\n );\n })\n );\n }\n\n /**\n * when using project-references, typescript adds a file \"tsconfig.tsbuildinfo\" which is not\n * needed for the package.\n */\n private async writeNpmIgnore(dirs: string[]) {\n const NPM_IGNORE_FILE = '.npmignore';\n await Promise.all(\n dirs.map(async (dir) => {\n const npmIgnorePath = path.join(dir, NPM_IGNORE_FILE);\n const npmIgnoreEntriesStr = `\\n${this.distDir}/tsconfig.tsbuildinfo\\n`;\n await fs.appendFile(npmIgnorePath, npmIgnoreEntriesStr);\n })\n );\n }\n\n private async writeProjectReferencesTsConfig(rootDir: string, projects: string[]) {\n const files = [];\n const references = projects.map((project) => ({ path: project }));\n const tsconfig = { files, references };\n const tsconfigStr = this.stringifyTsconfig(tsconfig);\n await fs.writeFile(path.join(rootDir, 'tsconfig.json'), tsconfigStr);\n }\n\n private async writeTsConfig(dirs: string[]) {\n const tsconfigStr = this.stringifyTsconfig(this.options.tsconfig);\n await Promise.all(dirs.map((capsuleDir) => fs.writeFile(path.join(capsuleDir, 'tsconfig.json'), tsconfigStr)));\n }\n\n private stringifyTsconfig(tsconfig) {\n return JSON.stringify(tsconfig, undefined, 2);\n }\n\n private replaceFileExtToJs(filePath: string): string {\n if (!this.isFileSupported(filePath)) return filePath;\n const fileExtension = path.extname(filePath);\n return filePath.replace(new RegExp(`${fileExtension}$`), '.js'); // makes sure it's the last occurrence\n }\n\n version() {\n return this.tsModule.version;\n }\n}\n"]}
1
+ {"version":3,"sources":["typescript.compiler.ts"],"names":["TypescriptCompiler","constructor","id","logger","options","tsModule","distDir","distGlobPatterns","shouldCopyNonSupportedFiles","artifactName","tsconfig","compilerOptions","outDir","displayConfig","stringifyTsconfig","transpileFile","fileContent","isFileSupported","filePath","compilerOptionsFromTsconfig","convertCompilerOptionsFromJson","errors","length","formattedErrors","formatDiagnosticsWithColorAndContext","getFormatDiagnosticsHost","Error","sourceRoot","componentDir","rootDir","result","transpileModule","fileName","reportDiagnostics","diagnostics","formatHost","error","outputPath","replaceFileExtToJs","outputFiles","outputText","sourceMapText","push","preBuild","context","capsules","capsuleNetwork","seedersCapsules","capsuleDirs","map","capsule","path","writeTsConfig","writeTypes","writeNpmIgnore","build","componentsResults","runTscBuild","artifacts","getArtifactDefinition","postBuild","Promise","all","packageJson","PackageJsonFile","loadFromCapsuleSync","packageJsonObject","types","write","generatedBy","name","globPatterns","getDistPathBySrcPath","srcPath","fileWithJSExtIfNeeded","join","isJsAndCompile","compileJs","endsWith","isJsxAndCompile","compileJsx","network","capsulesRootDir","graphCapsules","getAllCapsuleDirs","getCanonicalFileName","p","getCurrentDirectory","getNewLine","sys","newLine","currentComponentResult","reportDiagnostic","diagnostic","errorStr","process","stdout","isTTY","formatDiagnostic","file","BitError","consoleFailure","component","reportSolutionBuilderStatus","diag","msg","messageText","debug","errorCounter","errorCount","info","host","createSolutionBuilderHost","undefined","writeProjectReferencesTsConfig","solutionBuilder","createSolutionBuilder","verbose","nextProject","longProcessLogger","createLongProcessLogger","getNextInvalidatedProject","capsulePath","project","replace","currentComponentId","getIdByPathInCapsule","logProgress","toString","getCapsule","startTime","Date","now","done","endTime","end","dirs","typePath","contents","fs","readFile","filename","basename","dir","pathExists","outputFile","NPM_IGNORE_FILE","npmIgnorePath","npmIgnoreEntriesStr","appendFile","projects","files","references","tsconfigStr","writeFile","JSON","stringify","fileExtension","extname","RegExp","version"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;;;;;AAGO,MAAMA,kBAAN,CAA6C;AAKlDC,EAAAA,WAAW,CACAC,EADA,EAEDC,MAFC,EAGDC,OAHC,EAIDC,QAJC,EAKT;AAAA;;AAAA,SAJSH,EAIT,GAJSA,EAIT;AAAA,SAHQC,MAGR,GAHQA,MAGR;AAAA,SAFQC,OAER,GAFQA,OAER;AAAA,SADQC,QACR,GADQA,QACR;AAAA;AAAA;AAAA;AAAA;AAAA,yDAYY,YAZZ;AACA,SAAKC,OAAL,GAAeF,OAAO,CAACE,OAAR,IAAmB,MAAlC;AACA,SAAKC,gBAAL,GAAwBH,OAAO,CAACG,gBAAR,IAA4B,CAAE,GAAE,KAAKD,OAAQ,KAAjB,EAAwB,IAAG,KAAKA,OAAQ,uBAAxC,CAApD;AACA,SAAKE,2BAAL,GACE,OAAOJ,OAAO,CAACI,2BAAf,KAA+C,SAA/C,GAA2DJ,OAAO,CAACI,2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,mBAAGe,SAAH,CAAavG,gBAAKwB,IAAL,CAAU9C,OAAV,EAAmB,eAAnB,CAAb,EAAkD4H,WAAlD,CAAN;AACD;;AAE0B,QAAbrG,aAAa,CAACoF,IAAD,EAAiB;AAC1C,UAAMiB,WAAW,GAAG,KAAK3I,iBAAL,CAAuB,KAAKV,OAAL,CAAaM,QAApC,CAApB;AACA,UAAMmD,OAAO,CAACC,GAAR,CAAY0E,IAAI,CAACvF,GAAL,CAAU8F,GAAD,IAASJ,mBAAGe,SAAH,CAAavG,gBAAKwB,IAAL,CAAUoE,GAAV,EAAe,eAAf,CAAb,EAA8CU,WAA9C,CAAlB,CAAZ,CAAN;AACD;;AAEO3I,EAAAA,iBAAiB,CAACJ,QAAD,EAAW;AAClC,WAAOiJ,IAAI,CAACC,SAAL,CAAelJ,QAAf,EAAyBuG,SAAzB,EAAoC,CAApC,CAAP;AACD;;AAEO3E,EAAAA,kBAAkB,CAACpB,QAAD,EAA2B;AACnD,QAAI,CAAC,KAAKD,eAAL,CAAqBC,QAArB,CAAL,EAAqC,OAAOA,QAAP;;AACrC,UAAM2I,aAAa,GAAG1G,gBAAK2G,OAAL,CAAa5I,QAAb,CAAtB;;AACA,WAAOA,QAAQ,CAAC0G,OAAT,CAAiB,IAAImC,MAAJ,CAAY,GAAEF,aAAc,GAA5B,CAAjB,EAAkD,KAAlD,CAAP,CAHmD,CAGc;AAClE;;AAEDG,EAAAA,OAAO,GAAG;AACR,WAAO,KAAK3J,QAAL,CAAc2J,OAArB;AACD;;AAxRiD","sourcesContent":["import { BuildContext, BuiltTaskResult, ComponentResult } from '@teambit/builder';\nimport { Compiler, TranspileFileParams, TranspileFileOutput } from '@teambit/compiler';\nimport { Network } from '@teambit/isolator';\nimport { Logger } from '@teambit/logger';\nimport fs from 'fs-extra';\nimport path from 'path';\nimport ts from 'typescript';\nimport { BitError } from '@teambit/bit-error';\nimport PackageJsonFile from '@teambit/legacy/dist/consumer/component/package-json-file';\nimport { TypeScriptCompilerOptions } from './compiler-options';\n\nexport class TypescriptCompiler implements Compiler {\n distDir: string;\n distGlobPatterns: string[];\n shouldCopyNonSupportedFiles: boolean;\n artifactName: string;\n constructor(\n readonly id: string,\n private logger: Logger,\n private options: TypeScriptCompilerOptions,\n private tsModule: typeof ts\n ) {\n this.distDir = options.distDir || 'dist';\n this.distGlobPatterns = options.distGlobPatterns || [`${this.distDir}/**`, `!${this.distDir}/tsconfig.tsbuildinfo`];\n this.shouldCopyNonSupportedFiles =\n typeof options.shouldCopyNonSupportedFiles === 'boolean' ? options.shouldCopyNonSupportedFiles : true;\n this.artifactName = options.artifactName || 'dist';\n this.options.tsconfig ||= {};\n this.options.tsconfig.compilerOptions ||= {};\n // mutate the outDir, otherwise, on capsules, the dists might be written to a different directory and make confusion\n this.options.tsconfig.compilerOptions.outDir = this.distDir;\n }\n\n displayName = 'TypeScript';\n\n displayConfig() {\n return this.stringifyTsconfig(this.options.tsconfig);\n }\n\n /**\n * compile one file on the workspace\n */\n transpileFile(fileContent: string, options: TranspileFileParams): TranspileFileOutput {\n if (!this.isFileSupported(options.filePath)) {\n return null; // file is not supported\n }\n const compilerOptionsFromTsconfig = this.tsModule.convertCompilerOptionsFromJson(\n this.options.tsconfig.compilerOptions,\n '.'\n );\n if (compilerOptionsFromTsconfig.errors.length) {\n // :TODO @david replace to a more concrete error type and put in 'exceptions' directory here.\n const formattedErrors = this.tsModule.formatDiagnosticsWithColorAndContext(\n compilerOptionsFromTsconfig.errors,\n this.getFormatDiagnosticsHost()\n );\n throw new Error(`failed parsing the tsconfig.json.\\n${formattedErrors}`);\n }\n\n const compilerOptions = compilerOptionsFromTsconfig.options;\n compilerOptions.sourceRoot = options.componentDir;\n compilerOptions.rootDir = '.';\n const result = this.tsModule.transpileModule(fileContent, {\n compilerOptions,\n fileName: options.filePath,\n reportDiagnostics: true,\n });\n\n if (result.diagnostics && result.diagnostics.length) {\n const formatHost = this.getFormatDiagnosticsHost();\n const error = this.tsModule.formatDiagnosticsWithColorAndContext(result.diagnostics, formatHost);\n\n // :TODO @david please replace to a more concrete error type and put in 'exceptions' directory here.\n throw new Error(error);\n }\n\n const outputPath = this.replaceFileExtToJs(options.filePath);\n const outputFiles = [{ outputText: result.outputText, outputPath }];\n if (result.sourceMapText) {\n outputFiles.push({\n outputText: result.sourceMapText,\n outputPath: `${outputPath}.map`,\n });\n }\n return outputFiles;\n }\n\n async preBuild(context: BuildContext) {\n const capsules = context.capsuleNetwork.seedersCapsules;\n const capsuleDirs = capsules.map((capsule) => capsule.path);\n await this.writeTsConfig(capsuleDirs);\n await this.writeTypes(capsuleDirs);\n await this.writeNpmIgnore(capsuleDirs);\n }\n\n /**\n * compile multiple components on the capsules\n */\n async build(context: BuildContext): Promise<BuiltTaskResult> {\n const componentsResults = await this.runTscBuild(context.capsuleNetwork);\n\n return {\n artifacts: this.getArtifactDefinition(),\n componentsResults,\n };\n }\n\n async postBuild(context: BuildContext) {\n await Promise.all(\n context.capsuleNetwork.seedersCapsules.map(async (capsule) => {\n const packageJson = PackageJsonFile.loadFromCapsuleSync(capsule.path);\n // the types['index.ts'] is needed only during the build to avoid errors when tsc finds the\n // same type once in the d.ts and once in the ts file.\n if (packageJson.packageJsonObject.types) {\n delete packageJson.packageJsonObject.types;\n await packageJson.write();\n }\n })\n );\n }\n\n getArtifactDefinition() {\n return [\n {\n generatedBy: this.id,\n name: this.artifactName,\n globPatterns: this.distGlobPatterns,\n },\n ];\n }\n\n /**\n * given a source file, return its parallel in the dists. e.g. index.ts => dist/index.js\n */\n getDistPathBySrcPath(srcPath: string) {\n const fileWithJSExtIfNeeded = this.replaceFileExtToJs(srcPath);\n return path.join(this.distDir, fileWithJSExtIfNeeded);\n }\n\n /**\n * whether typescript is able to compile the given path\n */\n isFileSupported(filePath: string): boolean {\n const isJsAndCompile = !!this.options.compileJs && filePath.endsWith('.js');\n const isJsxAndCompile = !!this.options.compileJsx && filePath.endsWith('.jsx');\n return (\n (filePath.endsWith('.ts') || filePath.endsWith('.tsx') || isJsAndCompile || isJsxAndCompile) &&\n !filePath.endsWith('.d.ts')\n );\n }\n\n /**\n * we have two options here:\n * 1. pass all capsules-dir at the second parameter of createSolutionBuilder and then no\n * need to write the main tsconfig.json with all the references.\n * 2. write main tsconfig.json and pass the capsules root-dir.\n * we went with option #2 because it'll be easier for users to go to the capsule-root and run\n * `tsc --build` to debug issues.\n */\n private async runTscBuild(network: Network): Promise<ComponentResult[]> {\n const rootDir = network.capsulesRootDir;\n const capsules = network.graphCapsules;\n const capsuleDirs = capsules.getAllCapsuleDirs();\n const formatHost = {\n getCanonicalFileName: (p) => p,\n getCurrentDirectory: () => '', // it helps to get the files with absolute paths\n getNewLine: () => this.tsModule.sys.newLine,\n };\n const componentsResults: ComponentResult[] = [];\n let currentComponentResult: Partial<ComponentResult> = { errors: [] };\n const reportDiagnostic = (diagnostic: ts.Diagnostic) => {\n const errorStr = process.stdout.isTTY\n ? this.tsModule.formatDiagnosticsWithColorAndContext([diagnostic], formatHost)\n : this.tsModule.formatDiagnostic(diagnostic, formatHost);\n if (!diagnostic.file) {\n // the error is general and not related to a specific file. e.g. tsconfig is missing.\n throw new BitError(errorStr);\n }\n this.logger.consoleFailure(errorStr);\n if (!currentComponentResult.component || !currentComponentResult.errors) {\n throw new Error(`currentComponentResult is not defined yet for ${diagnostic.file}`);\n }\n currentComponentResult.errors.push(errorStr);\n };\n // this only works when `verbose` is `true` in the `ts.createSolutionBuilder` function.\n const reportSolutionBuilderStatus = (diag: ts.Diagnostic) => {\n const msg = diag.messageText as string;\n this.logger.debug(msg);\n };\n const errorCounter = (errorCount: number) => {\n this.logger.info(`total error found: ${errorCount}`);\n };\n const host = this.tsModule.createSolutionBuilderHost(\n undefined,\n undefined,\n reportDiagnostic,\n reportSolutionBuilderStatus,\n errorCounter\n );\n await this.writeProjectReferencesTsConfig(rootDir, capsuleDirs);\n const solutionBuilder = this.tsModule.createSolutionBuilder(host, [rootDir], { verbose: true });\n let nextProject;\n const longProcessLogger = this.logger.createLongProcessLogger('compile typescript components', capsules.length);\n // eslint-disable-next-line no-cond-assign\n while ((nextProject = solutionBuilder.getNextInvalidatedProject())) {\n // regex to make sure it will work correctly for both linux and windows\n // it replaces both /tsconfig.json and \\tsocnfig.json\n const capsulePath = nextProject.project.replace(/[/\\\\]tsconfig.json/, '');\n const currentComponentId = capsules.getIdByPathInCapsule(capsulePath);\n if (!currentComponentId) throw new Error(`unable to find component for ${capsulePath}`);\n longProcessLogger.logProgress(currentComponentId.toString());\n const capsule = capsules.getCapsule(currentComponentId);\n if (!capsule) throw new Error(`unable to find capsule for ${currentComponentId.toString()}`);\n currentComponentResult.component = capsule.component;\n currentComponentResult.startTime = Date.now();\n nextProject.done();\n currentComponentResult.endTime = Date.now();\n componentsResults.push({ ...currentComponentResult } as ComponentResult);\n currentComponentResult = { errors: [] };\n }\n longProcessLogger.end();\n\n return componentsResults;\n }\n\n private getFormatDiagnosticsHost(): ts.FormatDiagnosticsHost {\n return {\n getCanonicalFileName: (p) => p,\n getCurrentDirectory: this.tsModule.sys.getCurrentDirectory,\n getNewLine: () => this.tsModule.sys.newLine,\n };\n }\n\n private async writeTypes(dirs: string[]) {\n await Promise.all(\n this.options.types.map(async (typePath) => {\n const contents = await fs.readFile(typePath, 'utf8');\n const filename = path.basename(typePath);\n\n await Promise.all(\n dirs.map(async (dir) => {\n const filePath = path.join(dir, 'types', filename);\n if (!(await fs.pathExists(filePath))) {\n await fs.outputFile(filePath, contents);\n }\n })\n );\n })\n );\n }\n\n /**\n * when using project-references, typescript adds a file \"tsconfig.tsbuildinfo\" which is not\n * needed for the package.\n */\n private async writeNpmIgnore(dirs: string[]) {\n const NPM_IGNORE_FILE = '.npmignore';\n await Promise.all(\n dirs.map(async (dir) => {\n const npmIgnorePath = path.join(dir, NPM_IGNORE_FILE);\n const npmIgnoreEntriesStr = `\\n${this.distDir}/tsconfig.tsbuildinfo\\n`;\n await fs.appendFile(npmIgnorePath, npmIgnoreEntriesStr);\n })\n );\n }\n\n private async writeProjectReferencesTsConfig(rootDir: string, projects: string[]) {\n const files = [];\n const references = projects.map((project) => ({ path: project }));\n const tsconfig = { files, references };\n const tsconfigStr = this.stringifyTsconfig(tsconfig);\n await fs.writeFile(path.join(rootDir, 'tsconfig.json'), tsconfigStr);\n }\n\n private async writeTsConfig(dirs: string[]) {\n const tsconfigStr = this.stringifyTsconfig(this.options.tsconfig);\n await Promise.all(dirs.map((dir) => fs.writeFile(path.join(dir, 'tsconfig.json'), tsconfigStr)));\n }\n\n private stringifyTsconfig(tsconfig) {\n return JSON.stringify(tsconfig, undefined, 2);\n }\n\n private replaceFileExtToJs(filePath: string): string {\n if (!this.isFileSupported(filePath)) return filePath;\n const fileExtension = path.extname(filePath);\n return filePath.replace(new RegExp(`${fileExtension}$`), '.js'); // makes sure it's the last occurrence\n }\n\n version() {\n return this.tsModule.version;\n }\n}\n"]}
@@ -4,18 +4,28 @@ import { Logger, LoggerMain } from '@teambit/logger';
4
4
  import { SchemaExtractor, SchemaMain } from '@teambit/schema';
5
5
  import { PackageJsonProps } from '@teambit/pkg';
6
6
  import { TypescriptConfigMutator } from '@teambit/typescript.modules.ts-config-mutator';
7
+ import type { Workspace } from '@teambit/workspace';
8
+ import { TsserverClient, TsserverClientOpts } from '@teambit/ts-server';
7
9
  import { TypeScriptCompilerOptions } from './compiler-options';
8
10
  export declare type TsMode = 'build' | 'dev';
9
11
  export declare type TsConfigTransformContext = {};
10
12
  export declare type TsConfigTransformer = (config: TypescriptConfigMutator, context: TsConfigTransformContext) => TypescriptConfigMutator;
11
13
  export declare class TypescriptMain {
12
14
  private logger;
13
- constructor(logger: Logger);
15
+ private workspace?;
16
+ private tsServer;
17
+ constructor(logger: Logger, workspace?: Workspace | undefined);
14
18
  createCompiler(options: TypeScriptCompilerOptions, transformers?: TsConfigTransformer[], tsModule?: typeof ts): Compiler;
19
+ getTsserverClient(): TsserverClient | undefined;
20
+ initTsserverClient(projectPath: string, options?: TsserverClientOpts): Promise<TsserverClient>;
21
+ initTsserverClientFromWorkspace(options?: TsserverClientOpts): Promise<TsserverClient>;
22
+ private getAllFilesForTsserver;
23
+ private onPreWatch;
24
+ private onComponentChange;
15
25
  createSchemaExtractor(tsconfig: TsConfigSourceFile): SchemaExtractor;
16
26
  getPackageJsonProps(): PackageJsonProps;
17
27
  static runtime: import("@teambit/harmony").RuntimeDefinition;
18
28
  static dependencies: import("@teambit/harmony").Aspect[];
19
- static provider([schema, loggerExt]: [SchemaMain, LoggerMain]): Promise<TypescriptMain>;
29
+ static provider([schema, loggerExt, workspace]: [SchemaMain, LoggerMain, Workspace]): Promise<TypescriptMain>;
20
30
  }
21
31
  export declare function runTransformersWithContext(config: TypescriptConfigMutator, transformers: TsConfigTransformer[] | undefined, context: TsConfigTransformContext): TypescriptConfigMutator;
@@ -2,8 +2,12 @@
2
2
 
3
3
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
4
 
5
+ require("core-js/modules/es.array.flat.js");
6
+
5
7
  require("core-js/modules/es.array.iterator.js");
6
8
 
9
+ require("core-js/modules/es.array.unscopables.flat.js");
10
+
7
11
  require("core-js/modules/es.promise.js");
8
12
 
9
13
  Object.defineProperty(exports, "__esModule", {
@@ -72,6 +76,36 @@ function _typescriptModules() {
72
76
  return data;
73
77
  }
74
78
 
79
+ function _workspace() {
80
+ const data = _interopRequireDefault(require("@teambit/workspace"));
81
+
82
+ _workspace = function () {
83
+ return data;
84
+ };
85
+
86
+ return data;
87
+ }
88
+
89
+ function _pMapSeries() {
90
+ const data = _interopRequireDefault(require("p-map-series"));
91
+
92
+ _pMapSeries = function () {
93
+ return data;
94
+ };
95
+
96
+ return data;
97
+ }
98
+
99
+ function _tsServer() {
100
+ const data = require("@teambit/ts-server");
101
+
102
+ _tsServer = function () {
103
+ return data;
104
+ };
105
+
106
+ return data;
107
+ }
108
+
75
109
  function _typescript2() {
76
110
  const data = require("./typescript.extractor");
77
111
 
@@ -113,8 +147,16 @@ function _typescript5() {
113
147
  }
114
148
 
115
149
  class TypescriptMain {
116
- constructor(logger) {
150
+ constructor(logger, workspace) {
117
151
  this.logger = logger;
152
+ this.workspace = workspace;
153
+ (0, _defineProperty2().default)(this, "tsServer", void 0);
154
+
155
+ if (this.workspace) {
156
+ this.workspace.registerOnPreWatch(this.onPreWatch.bind(this));
157
+ this.workspace.registerOnComponentChange(this.onComponentChange.bind(this));
158
+ this.workspace.registerOnComponentAdd(this.onComponentChange.bind(this));
159
+ }
118
160
  }
119
161
  /**
120
162
  * create a new compiler.
@@ -127,6 +169,72 @@ class TypescriptMain {
127
169
  const afterMutation = runTransformersWithContext(configMutator.clone(), transformers, transformerContext);
128
170
  return new (_typescript4().TypescriptCompiler)(_typescript3().TypescriptAspect.id, this.logger, afterMutation.raw, tsModule);
129
171
  }
172
+
173
+ getTsserverClient() {
174
+ return this.tsServer;
175
+ }
176
+
177
+ async initTsserverClient(projectPath, options = {}) {
178
+ this.tsServer = new (_tsServer().TsserverClient)(projectPath, this.logger, options);
179
+ this.tsServer.init();
180
+ return this.tsServer;
181
+ }
182
+
183
+ async initTsserverClientFromWorkspace(options = {}) {
184
+ if (!this.workspace) {
185
+ throw new Error(`initTsserverClientFromWorkspace: workspace was not found`);
186
+ }
187
+
188
+ return this.initTsserverClient(this.workspace.path, options);
189
+ }
190
+
191
+ getAllFilesForTsserver(components) {
192
+ const files = components.map(c => c.filesystem.files).flat().map(f => f.path);
193
+ return files.filter(f => f.endsWith('.ts') || f.endsWith('.tsx'));
194
+ }
195
+
196
+ async onPreWatch(components, watchOpts) {
197
+ const workspace = this.workspace;
198
+
199
+ if (!workspace || !watchOpts.checkTypes) {
200
+ return;
201
+ }
202
+
203
+ await this.initTsserverClientFromWorkspace({
204
+ verbose: watchOpts.verbose
205
+ });
206
+ const supportedFiles = this.getAllFilesForTsserver(components);
207
+ this.tsServer.openMultipleFiles(supportedFiles);
208
+ const start = Date.now();
209
+ this.tsServer.getDiagnostic().then(() => {
210
+ const end = Date.now() - start;
211
+ this.logger.console(`\ncompleted preliminary type checking. took ${end / 1000} sec`);
212
+ }).catch(err => {
213
+ this.logger.error(`failed getting the diag info from ts-server`, err);
214
+ });
215
+ }
216
+
217
+ async onComponentChange(component, files) {
218
+ if (!this.tsServer) {
219
+ return {
220
+ results: 'N/A'
221
+ };
222
+ }
223
+
224
+ await (0, _pMapSeries().default)(files, file => this.tsServer.changed(file));
225
+ let results = 'succeed';
226
+ const start = Date.now();
227
+ this.tsServer.getDiagnostic().then(() => {
228
+ const end = Date.now() - start;
229
+ this.logger.console(`\ntype checking had been completed (${end / 1000} sec) for the following files:\n${files.join('\n')}`);
230
+ }).catch(err => {
231
+ results = 'failed';
232
+ this.logger.error(`failed getting the diag info from ts-server`, err);
233
+ });
234
+ return {
235
+ results
236
+ };
237
+ }
130
238
  /**
131
239
  * create an instance of a typescript semantic schema extractor.
132
240
  */
@@ -148,17 +256,18 @@ class TypescriptMain {
148
256
  };
149
257
  }
150
258
 
151
- static async provider([schema, loggerExt]) {
259
+ static async provider([schema, loggerExt, workspace]) {
260
+ schema.registerParser(new (_typescript5().TypeScriptParser)());
152
261
  const logger = loggerExt.createLogger(_typescript3().TypescriptAspect.id);
153
262
  schema.registerParser(new (_typescript5().TypeScriptParser)(logger));
154
- return new TypescriptMain(logger);
263
+ return new TypescriptMain(logger, workspace);
155
264
  }
156
265
 
157
266
  }
158
267
 
159
268
  exports.TypescriptMain = TypescriptMain;
160
269
  (0, _defineProperty2().default)(TypescriptMain, "runtime", _cli().MainRuntime);
161
- (0, _defineProperty2().default)(TypescriptMain, "dependencies", [_schema().SchemaAspect, _logger().LoggerAspect]);
270
+ (0, _defineProperty2().default)(TypescriptMain, "dependencies", [_schema().SchemaAspect, _logger().LoggerAspect, _workspace().default]);
162
271
 
163
272
  _typescript3().TypescriptAspect.addRuntime(TypescriptMain);
164
273
 
@@ -1 +1 @@
1
- {"version":3,"sources":["typescript.main.runtime.ts"],"names":["TypescriptMain","constructor","logger","createCompiler","options","transformers","tsModule","ts","configMutator","TypescriptConfigMutator","transformerContext","afterMutation","runTransformersWithContext","clone","TypescriptCompiler","TypescriptAspect","id","raw","createSchemaExtractor","tsconfig","TypeScriptExtractor","getPackageJsonProps","main","types","provider","schema","loggerExt","createLogger","registerParser","TypeScriptParser","MainRuntime","SchemaAspect","LoggerAspect","addRuntime","config","context","Array","isArray","newConfig","reduce","acc","transformer"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAaO,MAAMA,cAAN,CAAqB;AAC1BC,EAAAA,WAAW,CAASC,MAAT,EAAyB;AAAA,SAAhBA,MAAgB,GAAhBA,MAAgB;AAAE;AACtC;AACF;AACA;;;AACEC,EAAAA,cAAc,CACZC,OADY,EAEZC,YAAmC,GAAG,EAF1B,EAGZC,QAAQ,GAAGC,qBAHC,EAIF;AACV,UAAMC,aAAa,GAAG,KAAIC,4CAAJ,EAA4BL,OAA5B,CAAtB;AACA,UAAMM,kBAA4C,GAAG,EAArD;AACA,UAAMC,aAAa,GAAGC,0BAA0B,CAACJ,aAAa,CAACK,KAAd,EAAD,EAAwBR,YAAxB,EAAsCK,kBAAtC,CAAhD;AACA,WAAO,KAAII,iCAAJ,EAAuBC,gCAAiBC,EAAxC,EAA4C,KAAKd,MAAjD,EAAyDS,aAAa,CAACM,GAAvE,EAA4EX,QAA5E,CAAP;AACD;AAED;AACF;AACA;;;AACEY,EAAAA,qBAAqB,CAACC,QAAD,EAAgD;AACnE,WAAO,KAAIC,kCAAJ,EAAwBD,QAAxB,CAAP;AACD;AAED;AACF;AACA;AACA;;;AACEE,EAAAA,mBAAmB,GAAqB;AACtC,WAAO;AACLC,MAAAA,IAAI,EAAE,gBADD;AAELC,MAAAA,KAAK,EAAE;AAFF,KAAP;AAID;;AAKoB,eAARC,QAAQ,CAAC,CAACC,MAAD,EAASC,SAAT,CAAD,EAAgD;AACnE,UAAMxB,MAAM,GAAGwB,SAAS,CAACC,YAAV,CAAuBZ,gCAAiBC,EAAxC,CAAf;AACAS,IAAAA,MAAM,CAACG,cAAP,CAAsB,KAAIC,+BAAJ,EAAqB3B,MAArB,CAAtB;AAEA,WAAO,IAAIF,cAAJ,CAAmBE,MAAnB,CAAP;AACD;;AA1CyB;;;gCAAfF,c,aAkCM8B,kB;gCAlCN9B,c,kBAmCW,CAAC+B,sBAAD,EAAeC,sBAAf,C;;AAUxBjB,gCAAiBkB,UAAjB,CAA4BjC,cAA5B;;AAEO,SAASY,0BAAT,CACLsB,MADK,EAEL7B,YAAmC,GAAG,EAFjC,EAGL8B,OAHK,EAIoB;AACzB,MAAI,CAACC,KAAK,CAACC,OAAN,CAAchC,YAAd,CAAL,EAAkC,OAAO6B,MAAP;AAClC,QAAMI,SAAS,GAAGjC,YAAY,CAACkC,MAAb,CAAoB,CAACC,GAAD,EAAMC,WAAN,KAAsB;AAC1D,WAAOA,WAAW,CAACD,GAAD,EAAML,OAAN,CAAlB;AACD,GAFiB,EAEfD,MAFe,CAAlB;AAGA,SAAOI,SAAP;AACD","sourcesContent":["import ts, { TsConfigSourceFile } from 'typescript';\nimport { MainRuntime } from '@teambit/cli';\nimport { Compiler } from '@teambit/compiler';\nimport { Logger, LoggerAspect, LoggerMain } from '@teambit/logger';\nimport { SchemaAspect, SchemaExtractor, SchemaMain } from '@teambit/schema';\nimport { PackageJsonProps } from '@teambit/pkg';\nimport { TypescriptConfigMutator } from '@teambit/typescript.modules.ts-config-mutator';\n\nimport { TypeScriptExtractor } from './typescript.extractor';\nimport { TypeScriptCompilerOptions } from './compiler-options';\nimport { TypescriptAspect } from './typescript.aspect';\nimport { TypescriptCompiler } from './typescript.compiler';\nimport { TypeScriptParser } from './typescript.parser';\n\nexport type TsMode = 'build' | 'dev';\n\nexport type TsConfigTransformContext = {\n // mode: TsMode;\n};\n\nexport type TsConfigTransformer = (\n config: TypescriptConfigMutator,\n context: TsConfigTransformContext\n) => TypescriptConfigMutator;\n\nexport class TypescriptMain {\n constructor(private logger: Logger) {}\n /**\n * create a new compiler.\n */\n createCompiler(\n options: TypeScriptCompilerOptions,\n transformers: TsConfigTransformer[] = [],\n tsModule = ts\n ): Compiler {\n const configMutator = new TypescriptConfigMutator(options);\n const transformerContext: TsConfigTransformContext = {};\n const afterMutation = runTransformersWithContext(configMutator.clone(), transformers, transformerContext);\n return new TypescriptCompiler(TypescriptAspect.id, this.logger, afterMutation.raw, tsModule);\n }\n\n /**\n * create an instance of a typescript semantic schema extractor.\n */\n createSchemaExtractor(tsconfig: TsConfigSourceFile): SchemaExtractor {\n return new TypeScriptExtractor(tsconfig);\n }\n\n /**\n * add the default package json properties to the component\n * :TODO @gilad why do we need this DSL? can't I just get the args here.\n */\n getPackageJsonProps(): PackageJsonProps {\n return {\n main: 'dist/{main}.js',\n types: '{main}.ts',\n };\n }\n\n static runtime = MainRuntime;\n static dependencies = [SchemaAspect, LoggerAspect];\n\n static async provider([schema, loggerExt]: [SchemaMain, LoggerMain]) {\n const logger = loggerExt.createLogger(TypescriptAspect.id);\n schema.registerParser(new TypeScriptParser(logger));\n\n return new TypescriptMain(logger);\n }\n}\n\nTypescriptAspect.addRuntime(TypescriptMain);\n\nexport function runTransformersWithContext(\n config: TypescriptConfigMutator,\n transformers: TsConfigTransformer[] = [],\n context: TsConfigTransformContext\n): TypescriptConfigMutator {\n if (!Array.isArray(transformers)) return config;\n const newConfig = transformers.reduce((acc, transformer) => {\n return transformer(acc, context);\n }, config);\n return newConfig;\n}\n"]}
1
+ {"version":3,"sources":["typescript.main.runtime.ts"],"names":["TypescriptMain","constructor","logger","workspace","registerOnPreWatch","onPreWatch","bind","registerOnComponentChange","onComponentChange","registerOnComponentAdd","createCompiler","options","transformers","tsModule","ts","configMutator","TypescriptConfigMutator","transformerContext","afterMutation","runTransformersWithContext","clone","TypescriptCompiler","TypescriptAspect","id","raw","getTsserverClient","tsServer","initTsserverClient","projectPath","TsserverClient","init","initTsserverClientFromWorkspace","Error","path","getAllFilesForTsserver","components","files","map","c","filesystem","flat","f","filter","endsWith","watchOpts","checkTypes","verbose","supportedFiles","openMultipleFiles","start","Date","now","getDiagnostic","then","end","console","catch","err","error","component","results","file","changed","join","createSchemaExtractor","tsconfig","TypeScriptExtractor","getPackageJsonProps","main","types","provider","schema","loggerExt","registerParser","TypeScriptParser","createLogger","MainRuntime","SchemaAspect","LoggerAspect","WorkspaceAspect","addRuntime","config","context","Array","isArray","newConfig","reduce","acc","transformer"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAaO,MAAMA,cAAN,CAAqB;AAE1BC,EAAAA,WAA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sE,SAAS,CAACG,YAAV,CAAuBrD,gCAAiBC,EAAxC,CAAf;AACAgD,IAAAA,MAAM,CAACE,cAAP,CAAsB,KAAIC,+BAAJ,EAAqBxE,MAArB,CAAtB;AAEA,WAAO,IAAIF,cAAJ,CAAmBE,MAAnB,EAA2BC,SAA3B,CAAP;AACD;;AAzHyB;;;gCAAfH,c,aAgHM4E,kB;gCAhHN5E,c,kBAiHW,CAAC6E,sBAAD,EAAeC,sBAAf,EAA6BC,oBAA7B,C;;AAWxBzD,gCAAiB0D,UAAjB,CAA4BhF,cAA5B;;AAEO,SAASmB,0BAAT,CACL8D,MADK,EAELrE,YAAmC,GAAG,EAFjC,EAGLsE,OAHK,EAIoB;AACzB,MAAI,CAACC,KAAK,CAACC,OAAN,CAAcxE,YAAd,CAAL,EAAkC,OAAOqE,MAAP;AAClC,QAAMI,SAAS,GAAGzE,YAAY,CAAC0E,MAAb,CAAoB,CAACC,GAAD,EAAMC,WAAN,KAAsB;AAC1D,WAAOA,WAAW,CAACD,GAAD,EAAML,OAAN,CAAlB;AACD,GAFiB,EAEfD,MAFe,CAAlB;AAGA,SAAOI,SAAP;AACD","sourcesContent":["import ts, { TsConfigSourceFile } from 'typescript';\nimport { MainRuntime } from '@teambit/cli';\nimport { Compiler } from '@teambit/compiler';\nimport { Logger, LoggerAspect, LoggerMain } from '@teambit/logger';\nimport { SchemaAspect, SchemaExtractor, SchemaMain } from '@teambit/schema';\nimport { PackageJsonProps } from '@teambit/pkg';\nimport { TypescriptConfigMutator } from '@teambit/typescript.modules.ts-config-mutator';\nimport WorkspaceAspect from '@teambit/workspace';\nimport type { WatchOptions, Workspace } from '@teambit/workspace';\nimport pMapSeries from 'p-map-series';\nimport { TsserverClient, TsserverClientOpts } from '@teambit/ts-server';\nimport type { Component } from '@teambit/component';\nimport { TypeScriptExtractor } from './typescript.extractor';\nimport { TypeScriptCompilerOptions } from './compiler-options';\nimport { TypescriptAspect } from './typescript.aspect';\nimport { TypescriptCompiler } from './typescript.compiler';\nimport { TypeScriptParser } from './typescript.parser';\n\nexport type TsMode = 'build' | 'dev';\n\nexport type TsConfigTransformContext = {\n // mode: TsMode;\n};\n\nexport type TsConfigTransformer = (\n config: TypescriptConfigMutator,\n context: TsConfigTransformContext\n) => TypescriptConfigMutator;\n\nexport class TypescriptMain {\n private tsServer: TsserverClient;\n constructor(private logger: Logger, private workspace?: Workspace) {\n if (this.workspace) {\n this.workspace.registerOnPreWatch(this.onPreWatch.bind(this));\n this.workspace.registerOnComponentChange(this.onComponentChange.bind(this));\n this.workspace.registerOnComponentAdd(this.onComponentChange.bind(this));\n }\n }\n /**\n * create a new compiler.\n */\n createCompiler(\n options: TypeScriptCompilerOptions,\n transformers: TsConfigTransformer[] = [],\n tsModule = ts\n ): Compiler {\n const configMutator = new TypescriptConfigMutator(options);\n const transformerContext: TsConfigTransformContext = {};\n const afterMutation = runTransformersWithContext(configMutator.clone(), transformers, transformerContext);\n return new TypescriptCompiler(TypescriptAspect.id, this.logger, afterMutation.raw, tsModule);\n }\n\n getTsserverClient(): TsserverClient | undefined {\n return this.tsServer;\n }\n\n async initTsserverClient(projectPath: string, options: TsserverClientOpts = {}): Promise<TsserverClient> {\n this.tsServer = new TsserverClient(projectPath, this.logger, options);\n this.tsServer.init();\n return this.tsServer;\n }\n\n async initTsserverClientFromWorkspace(options: TsserverClientOpts = {}): Promise<TsserverClient> {\n if (!this.workspace) {\n throw new Error(`initTsserverClientFromWorkspace: workspace was not found`);\n }\n return this.initTsserverClient(this.workspace.path, options);\n }\n\n private getAllFilesForTsserver(components: Component[]): string[] {\n const files = components\n .map((c) => c.filesystem.files)\n .flat()\n .map((f) => f.path);\n return files.filter((f) => f.endsWith('.ts') || f.endsWith('.tsx'));\n }\n\n private async onPreWatch(components: Component[], watchOpts: WatchOptions) {\n const workspace = this.workspace;\n if (!workspace || !watchOpts.checkTypes) {\n return;\n }\n await this.initTsserverClientFromWorkspace({ verbose: watchOpts.verbose });\n const supportedFiles = this.getAllFilesForTsserver(components);\n this.tsServer.openMultipleFiles(supportedFiles);\n const start = Date.now();\n this.tsServer\n .getDiagnostic()\n .then(() => {\n const end = Date.now() - start;\n this.logger.console(`\\ncompleted preliminary type checking. took ${end / 1000} sec`);\n })\n .catch((err) => {\n this.logger.error(`failed getting the diag info from ts-server`, err);\n });\n }\n\n private async onComponentChange(component: Component, files: string[]) {\n if (!this.tsServer) {\n return {\n results: 'N/A',\n };\n }\n await pMapSeries(files, (file) => this.tsServer.changed(file));\n let results = 'succeed';\n const start = Date.now();\n this.tsServer\n .getDiagnostic()\n .then(() => {\n const end = Date.now() - start;\n this.logger.console(\n `\\ntype checking had been completed (${end / 1000} sec) for the following files:\\n${files.join('\\n')}`\n );\n })\n .catch((err) => {\n results = 'failed';\n this.logger.error(`failed getting the diag info from ts-server`, err);\n });\n return {\n results,\n };\n }\n\n /**\n * create an instance of a typescript semantic schema extractor.\n */\n createSchemaExtractor(tsconfig: TsConfigSourceFile): SchemaExtractor {\n return new TypeScriptExtractor(tsconfig);\n }\n\n /**\n * add the default package json properties to the component\n * :TODO @gilad why do we need this DSL? can't I just get the args here.\n */\n getPackageJsonProps(): PackageJsonProps {\n return {\n main: 'dist/{main}.js',\n types: '{main}.ts',\n };\n }\n\n static runtime = MainRuntime;\n static dependencies = [SchemaAspect, LoggerAspect, WorkspaceAspect];\n\n static async provider([schema, loggerExt, workspace]: [SchemaMain, LoggerMain, Workspace]) {\n schema.registerParser(new TypeScriptParser());\n const logger = loggerExt.createLogger(TypescriptAspect.id);\n schema.registerParser(new TypeScriptParser(logger));\n\n return new TypescriptMain(logger, workspace);\n }\n}\n\nTypescriptAspect.addRuntime(TypescriptMain);\n\nexport function runTransformersWithContext(\n config: TypescriptConfigMutator,\n transformers: TsConfigTransformer[] = [],\n context: TsConfigTransformContext\n): TypescriptConfigMutator {\n if (!Array.isArray(transformers)) return config;\n const newConfig = transformers.reduce((acc, transformer) => {\n return transformer(acc, context);\n }, config);\n return newConfig;\n}\n"]}
package/package.json CHANGED
@@ -1,30 +1,33 @@
1
1
  {
2
2
  "name": "@teambit/typescript",
3
- "version": "0.0.526",
3
+ "version": "0.0.530",
4
4
  "homepage": "https://bit.dev/teambit/typescript/typescript",
5
5
  "main": "dist/index.js",
6
6
  "componentId": {
7
7
  "scope": "teambit.typescript",
8
8
  "name": "typescript",
9
- "version": "0.0.526"
9
+ "version": "0.0.530"
10
10
  },
11
11
  "dependencies": {
12
12
  "@teambit/harmony": "0.2.11",
13
13
  "fs-extra": "10.0.0",
14
14
  "typescript": "4.4.2",
15
- "typedoc": "0.21.5",
15
+ "typedoc": "0.22.5",
16
+ "p-map-series": "2.1.0",
16
17
  "@babel/runtime": "7.12.18",
17
18
  "core-js": "^3.0.0",
18
- "@teambit/compiler": "0.0.526",
19
- "@teambit/typescript.modules.ts-config-mutator": "0.0.27",
19
+ "@teambit/compiler": "0.0.530",
20
+ "@teambit/typescript.modules.ts-config-mutator": "0.0.29",
20
21
  "@teambit/bit-error": "0.0.366",
21
- "@teambit/builder": "0.0.526",
22
- "@teambit/isolator": "0.0.526",
23
- "@teambit/logger": "0.0.452",
24
- "@teambit/component": "0.0.526",
25
- "@teambit/schema": "0.0.526",
22
+ "@teambit/builder": "0.0.530",
23
+ "@teambit/isolator": "0.0.530",
24
+ "@teambit/logger": "0.0.454",
25
+ "@teambit/component": "0.0.530",
26
+ "@teambit/schema": "0.0.530",
26
27
  "@teambit/cli": "0.0.380",
27
- "@teambit/pkg": "0.0.526"
28
+ "@teambit/pkg": "0.0.530",
29
+ "@teambit/ts-server": "0.0.1",
30
+ "@teambit/workspace": "0.0.530"
28
31
  },
29
32
  "devDependencies": {
30
33
  "chai": "4.3.0",
@@ -36,7 +39,7 @@
36
39
  "@types/react-dom": "^17.0.5",
37
40
  "@types/react": "^17.0.8",
38
41
  "@types/node": "12.20.4",
39
- "@teambit/typescript.aspect-docs.typescript": "0.0.88"
42
+ "@teambit/typescript.aspect-docs.typescript": "0.0.90"
40
43
  },
41
44
  "peerDependencies": {
42
45
  "@teambit/legacy": "1.0.76",
@@ -274,7 +274,7 @@ export class TypescriptCompiler implements Compiler {
274
274
 
275
275
  private async writeTsConfig(dirs: string[]) {
276
276
  const tsconfigStr = this.stringifyTsconfig(this.options.tsconfig);
277
- await Promise.all(dirs.map((capsuleDir) => fs.writeFile(path.join(capsuleDir, 'tsconfig.json'), tsconfigStr)));
277
+ await Promise.all(dirs.map((dir) => fs.writeFile(path.join(dir, 'tsconfig.json'), tsconfigStr)));
278
278
  }
279
279
 
280
280
  private stringifyTsconfig(tsconfig) {
@@ -5,7 +5,11 @@ import { Logger, LoggerAspect, LoggerMain } from '@teambit/logger';
5
5
  import { SchemaAspect, SchemaExtractor, SchemaMain } from '@teambit/schema';
6
6
  import { PackageJsonProps } from '@teambit/pkg';
7
7
  import { TypescriptConfigMutator } from '@teambit/typescript.modules.ts-config-mutator';
8
-
8
+ import WorkspaceAspect from '@teambit/workspace';
9
+ import type { WatchOptions, Workspace } from '@teambit/workspace';
10
+ import pMapSeries from 'p-map-series';
11
+ import { TsserverClient, TsserverClientOpts } from '@teambit/ts-server';
12
+ import type { Component } from '@teambit/component';
9
13
  import { TypeScriptExtractor } from './typescript.extractor';
10
14
  import { TypeScriptCompilerOptions } from './compiler-options';
11
15
  import { TypescriptAspect } from './typescript.aspect';
@@ -24,7 +28,14 @@ export type TsConfigTransformer = (
24
28
  ) => TypescriptConfigMutator;
25
29
 
26
30
  export class TypescriptMain {
27
- constructor(private logger: Logger) {}
31
+ private tsServer: TsserverClient;
32
+ constructor(private logger: Logger, private workspace?: Workspace) {
33
+ if (this.workspace) {
34
+ this.workspace.registerOnPreWatch(this.onPreWatch.bind(this));
35
+ this.workspace.registerOnComponentChange(this.onComponentChange.bind(this));
36
+ this.workspace.registerOnComponentAdd(this.onComponentChange.bind(this));
37
+ }
38
+ }
28
39
  /**
29
40
  * create a new compiler.
30
41
  */
@@ -39,6 +50,77 @@ export class TypescriptMain {
39
50
  return new TypescriptCompiler(TypescriptAspect.id, this.logger, afterMutation.raw, tsModule);
40
51
  }
41
52
 
53
+ getTsserverClient(): TsserverClient | undefined {
54
+ return this.tsServer;
55
+ }
56
+
57
+ async initTsserverClient(projectPath: string, options: TsserverClientOpts = {}): Promise<TsserverClient> {
58
+ this.tsServer = new TsserverClient(projectPath, this.logger, options);
59
+ this.tsServer.init();
60
+ return this.tsServer;
61
+ }
62
+
63
+ async initTsserverClientFromWorkspace(options: TsserverClientOpts = {}): Promise<TsserverClient> {
64
+ if (!this.workspace) {
65
+ throw new Error(`initTsserverClientFromWorkspace: workspace was not found`);
66
+ }
67
+ return this.initTsserverClient(this.workspace.path, options);
68
+ }
69
+
70
+ private getAllFilesForTsserver(components: Component[]): string[] {
71
+ const files = components
72
+ .map((c) => c.filesystem.files)
73
+ .flat()
74
+ .map((f) => f.path);
75
+ return files.filter((f) => f.endsWith('.ts') || f.endsWith('.tsx'));
76
+ }
77
+
78
+ private async onPreWatch(components: Component[], watchOpts: WatchOptions) {
79
+ const workspace = this.workspace;
80
+ if (!workspace || !watchOpts.checkTypes) {
81
+ return;
82
+ }
83
+ await this.initTsserverClientFromWorkspace({ verbose: watchOpts.verbose });
84
+ const supportedFiles = this.getAllFilesForTsserver(components);
85
+ this.tsServer.openMultipleFiles(supportedFiles);
86
+ const start = Date.now();
87
+ this.tsServer
88
+ .getDiagnostic()
89
+ .then(() => {
90
+ const end = Date.now() - start;
91
+ this.logger.console(`\ncompleted preliminary type checking. took ${end / 1000} sec`);
92
+ })
93
+ .catch((err) => {
94
+ this.logger.error(`failed getting the diag info from ts-server`, err);
95
+ });
96
+ }
97
+
98
+ private async onComponentChange(component: Component, files: string[]) {
99
+ if (!this.tsServer) {
100
+ return {
101
+ results: 'N/A',
102
+ };
103
+ }
104
+ await pMapSeries(files, (file) => this.tsServer.changed(file));
105
+ let results = 'succeed';
106
+ const start = Date.now();
107
+ this.tsServer
108
+ .getDiagnostic()
109
+ .then(() => {
110
+ const end = Date.now() - start;
111
+ this.logger.console(
112
+ `\ntype checking had been completed (${end / 1000} sec) for the following files:\n${files.join('\n')}`
113
+ );
114
+ })
115
+ .catch((err) => {
116
+ results = 'failed';
117
+ this.logger.error(`failed getting the diag info from ts-server`, err);
118
+ });
119
+ return {
120
+ results,
121
+ };
122
+ }
123
+
42
124
  /**
43
125
  * create an instance of a typescript semantic schema extractor.
44
126
  */
@@ -58,13 +140,14 @@ export class TypescriptMain {
58
140
  }
59
141
 
60
142
  static runtime = MainRuntime;
61
- static dependencies = [SchemaAspect, LoggerAspect];
143
+ static dependencies = [SchemaAspect, LoggerAspect, WorkspaceAspect];
62
144
 
63
- static async provider([schema, loggerExt]: [SchemaMain, LoggerMain]) {
145
+ static async provider([schema, loggerExt, workspace]: [SchemaMain, LoggerMain, Workspace]) {
146
+ schema.registerParser(new TypeScriptParser());
64
147
  const logger = loggerExt.createLogger(TypescriptAspect.id);
65
148
  schema.registerParser(new TypeScriptParser(logger));
66
149
 
67
- return new TypescriptMain(logger);
150
+ return new TypescriptMain(logger, workspace);
68
151
  }
69
152
  }
70
153