@teambit/typescript 0.0.529 → 0.0.533

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/index.js CHANGED
@@ -3,10 +3,10 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- Object.defineProperty(exports, "TypescriptConfigMutator", {
6
+ Object.defineProperty(exports, "TypescriptAspect", {
7
7
  enumerable: true,
8
8
  get: function () {
9
- return _typescriptModules().TypescriptConfigMutator;
9
+ return _typescript2().TypescriptAspect;
10
10
  }
11
11
  });
12
12
  Object.defineProperty(exports, "TypescriptCompiler", {
@@ -15,10 +15,10 @@ Object.defineProperty(exports, "TypescriptCompiler", {
15
15
  return _typescript().TypescriptCompiler;
16
16
  }
17
17
  });
18
- Object.defineProperty(exports, "TypescriptAspect", {
18
+ Object.defineProperty(exports, "TypescriptConfigMutator", {
19
19
  enumerable: true,
20
20
  get: function () {
21
- return _typescript2().TypescriptAspect;
21
+ return _typescriptModules().TypescriptConfigMutator;
22
22
  }
23
23
  });
24
24
 
@@ -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,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,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;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;;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, files?: string[]): Promise<TsserverClient>;
21
+ initTsserverClientFromWorkspace(options?: TsserverClientOpts, files?: string[]): Promise<TsserverClient>;
15
22
  createSchemaExtractor(tsconfig: TsConfigSourceFile): SchemaExtractor;
16
23
  getPackageJsonProps(): PackageJsonProps;
24
+ private getAllFilesForTsserver;
25
+ private onPreWatch;
26
+ private onComponentChange;
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,15 +2,19 @@
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", {
10
14
  value: true
11
15
  });
12
- exports.runTransformersWithContext = runTransformersWithContext;
13
16
  exports.TypescriptMain = void 0;
17
+ exports.runTransformersWithContext = runTransformersWithContext;
14
18
 
15
19
  function _defineProperty2() {
16
20
  const data = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
@@ -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,43 @@ 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
+ * get TsserverClient instance if initiated already, otherwise, return undefined.
174
+ */
175
+
176
+
177
+ getTsserverClient() {
178
+ return this.tsServer;
179
+ }
180
+ /**
181
+ * starts a tsserver process to communicate with its API.
182
+ * @param projectPath absolute path of the project root directory
183
+ * @param options TsserverClientOpts
184
+ * @param files optionally, if check-types is enabled, provide files to open and type check.
185
+ * @returns TsserverClient
186
+ */
187
+
188
+
189
+ async initTsserverClient(projectPath, options = {}, files = []) {
190
+ this.tsServer = new (_tsServer().TsserverClient)(projectPath, this.logger, options, files);
191
+ this.tsServer.init();
192
+ return this.tsServer;
193
+ }
194
+ /**
195
+ * starts a tsserver process to communicate with its API. use only when running on the workspace.
196
+ * @param options TsserverClientOpts
197
+ * @param files optionally, if check-types is enabled, provide files to open and type check.
198
+ * @returns TsserverClient
199
+ */
200
+
201
+
202
+ async initTsserverClientFromWorkspace(options = {}, files = []) {
203
+ if (!this.workspace) {
204
+ throw new Error(`initTsserverClientFromWorkspace: workspace was not found`);
205
+ }
206
+
207
+ return this.initTsserverClient(this.workspace.path, options, files);
208
+ }
130
209
  /**
131
210
  * create an instance of a typescript semantic schema extractor.
132
211
  */
@@ -148,17 +227,54 @@ class TypescriptMain {
148
227
  };
149
228
  }
150
229
 
151
- static async provider([schema, loggerExt]) {
230
+ getAllFilesForTsserver(components) {
231
+ const files = components.map(c => c.filesystem.files).flat().map(f => f.path);
232
+ return files.filter(f => f.endsWith('.ts') || f.endsWith('.tsx'));
233
+ }
234
+
235
+ async onPreWatch(components, watchOpts) {
236
+ const workspace = this.workspace;
237
+
238
+ if (!workspace || !watchOpts.spawnTSServer) {
239
+ return;
240
+ }
241
+
242
+ const {
243
+ verbose,
244
+ checkTypes
245
+ } = watchOpts;
246
+ const files = checkTypes ? this.getAllFilesForTsserver(components) : [];
247
+ await this.initTsserverClientFromWorkspace({
248
+ verbose,
249
+ checkTypes
250
+ }, files);
251
+ }
252
+
253
+ async onComponentChange(component, files) {
254
+ if (!this.tsServer) {
255
+ return {
256
+ results: 'N/A'
257
+ };
258
+ }
259
+
260
+ await (0, _pMapSeries().default)(files, file => this.tsServer.onFileChange(file));
261
+ return {
262
+ results: 'succeed'
263
+ };
264
+ }
265
+
266
+ static async provider([schema, loggerExt, workspace]) {
267
+ schema.registerParser(new (_typescript5().TypeScriptParser)());
152
268
  const logger = loggerExt.createLogger(_typescript3().TypescriptAspect.id);
153
269
  schema.registerParser(new (_typescript5().TypeScriptParser)(logger));
154
- return new TypescriptMain(logger);
270
+ return new TypescriptMain(logger, workspace);
155
271
  }
156
272
 
157
273
  }
158
274
 
159
275
  exports.TypescriptMain = TypescriptMain;
160
276
  (0, _defineProperty2().default)(TypescriptMain, "runtime", _cli().MainRuntime);
161
- (0, _defineProperty2().default)(TypescriptMain, "dependencies", [_schema().SchemaAspect, _logger().LoggerAspect]);
277
+ (0, _defineProperty2().default)(TypescriptMain, "dependencies", [_schema().SchemaAspect, _logger().LoggerAspect, _workspace().default]);
162
278
 
163
279
  _typescript3().TypescriptAspect.addRuntime(TypescriptMain);
164
280
 
@@ -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;AA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F,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","files","TsserverClient","init","initTsserverClientFromWorkspace","Error","path","createSchemaExtractor","tsconfig","TypeScriptExtractor","getPackageJsonProps","main","types","getAllFilesForTsserver","components","map","c","filesystem","flat","f","filter","endsWith","watchOpts","spawnTSServer","verbose","checkTypes","component","results","file","onFileChange","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,WAAW,CAASC,MAAT,EAAiCC,SAAjC,EAAwD;AAAA,SAA/CD,MAA+C,GAA/CA,MAA+C;AAAA,SAAvBC,SAAuB,GAAvBA,SAAuB;AAAA;;AACjE,QAAI,KAAKA,SAAT,EAAoB;AAClB,WAAKA,SAAL,CAAeC,kBAAf,CAAkC,KAAKC,UAAL,CAAgBC,IAAhB,CAAqB,IAArB,CAAlC;AACA,WAAKH,SAAL,CAAeI,yBAAf,CAAyC,KAAKC,iBAAL,CAAuBF,IAAvB,CAA4B,IAA5B,CAAzC;AACA,WAAKH,SAAL,CAAeM,sBAAf,CAAsC,KAAKD,iBAAL,CAAuBF,IAAvB,CAA4B,IAA5B,CAAtC;AACD;AACF;AACD;AACF;AACA;;;AACEI,EAAAA,cAAc,CACZC,OADY,EAEZC,YAAmC,GAAG,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CAAC,CAACC,MAAD,EAASC,SAAT,EAAoBzD,SAApB,CAAD,EAAsE;AACzFwD,IAAAA,MAAM,CAACE,cAAP,CAAsB,KAAIC,+BAAJ,GAAtB;AACA,UAAM5D,MAAM,GAAG0D,SAAS,CAACG,YAAV,CAAuBzC,gCAAiBC,EAAxC,CAAf;AACAoC,IAAAA,MAAM,CAACE,cAAP,CAAsB,KAAIC,+BAAJ,EAAqB5D,MAArB,CAAtB;AAEA,WAAO,IAAIF,cAAJ,CAAmBE,MAAnB,EAA2BC,SAA3B,CAAP;AACD;;AAxHyB;;;gCAAfH,c,aA+GMgE,kB;gCA/GNhE,c,kBAgHW,CAACiE,sBAAD,EAAeC,sBAAf,EAA6BC,oBAA7B,C;;AAWxB7C,gCAAiB8C,UAAjB,CAA4BpE,cAA5B;;AAEO,SAASmB,0BAAT,CACLkD,MADK,EAELzD,YAAmC,GAAG,EAFjC,EAGL0D,OAHK,EAIoB;AACzB,MAAI,CAACC,KAAK,CAACC,OAAN,CAAc5D,YAAd,CAAL,EAAkC,OAAOyD,MAAP;AAClC,QAAMI,SAAS,GAAG7D,YAAY,CAAC8D,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 /**\n * get TsserverClient instance if initiated already, otherwise, return undefined.\n */\n getTsserverClient(): TsserverClient | undefined {\n return this.tsServer;\n }\n\n /**\n * starts a tsserver process to communicate with its API.\n * @param projectPath absolute path of the project root directory\n * @param options TsserverClientOpts\n * @param files optionally, if check-types is enabled, provide files to open and type check.\n * @returns TsserverClient\n */\n async initTsserverClient(\n projectPath: string,\n options: TsserverClientOpts = {},\n files: string[] = []\n ): Promise<TsserverClient> {\n this.tsServer = new TsserverClient(projectPath, this.logger, options, files);\n this.tsServer.init();\n return this.tsServer;\n }\n\n /**\n * starts a tsserver process to communicate with its API. use only when running on the workspace.\n * @param options TsserverClientOpts\n * @param files optionally, if check-types is enabled, provide files to open and type check.\n * @returns TsserverClient\n */\n async initTsserverClientFromWorkspace(\n options: TsserverClientOpts = {},\n files: string[] = []\n ): Promise<TsserverClient> {\n if (!this.workspace) {\n throw new Error(`initTsserverClientFromWorkspace: workspace was not found`);\n }\n return this.initTsserverClient(this.workspace.path, options, files);\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 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.spawnTSServer) {\n return;\n }\n const { verbose, checkTypes } = watchOpts;\n const files = checkTypes ? this.getAllFilesForTsserver(components) : [];\n await this.initTsserverClientFromWorkspace({ verbose, checkTypes }, files);\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.onFileChange(file));\n return {\n results: 'succeed',\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.529",
3
+ "version": "0.0.533",
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.529"
9
+ "version": "0.0.533"
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.529",
19
- "@teambit/typescript.modules.ts-config-mutator": "0.0.28",
19
+ "@teambit/compiler": "0.0.533",
20
+ "@teambit/typescript.modules.ts-config-mutator": "0.0.30",
20
21
  "@teambit/bit-error": "0.0.366",
21
- "@teambit/builder": "0.0.529",
22
- "@teambit/isolator": "0.0.529",
23
- "@teambit/logger": "0.0.453",
24
- "@teambit/component": "0.0.529",
25
- "@teambit/schema": "0.0.529",
22
+ "@teambit/builder": "0.0.533",
23
+ "@teambit/isolator": "0.0.533",
24
+ "@teambit/logger": "0.0.456",
25
+ "@teambit/component": "0.0.533",
26
+ "@teambit/schema": "0.0.533",
26
27
  "@teambit/cli": "0.0.380",
27
- "@teambit/pkg": "0.0.529"
28
+ "@teambit/pkg": "0.0.533",
29
+ "@teambit/ts-server": "0.0.3",
30
+ "@teambit/workspace": "0.0.533"
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.89"
42
+ "@teambit/typescript.aspect-docs.typescript": "0.0.92"
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,46 @@ export class TypescriptMain {
39
50
  return new TypescriptCompiler(TypescriptAspect.id, this.logger, afterMutation.raw, tsModule);
40
51
  }
41
52
 
53
+ /**
54
+ * get TsserverClient instance if initiated already, otherwise, return undefined.
55
+ */
56
+ getTsserverClient(): TsserverClient | undefined {
57
+ return this.tsServer;
58
+ }
59
+
60
+ /**
61
+ * starts a tsserver process to communicate with its API.
62
+ * @param projectPath absolute path of the project root directory
63
+ * @param options TsserverClientOpts
64
+ * @param files optionally, if check-types is enabled, provide files to open and type check.
65
+ * @returns TsserverClient
66
+ */
67
+ async initTsserverClient(
68
+ projectPath: string,
69
+ options: TsserverClientOpts = {},
70
+ files: string[] = []
71
+ ): Promise<TsserverClient> {
72
+ this.tsServer = new TsserverClient(projectPath, this.logger, options, files);
73
+ this.tsServer.init();
74
+ return this.tsServer;
75
+ }
76
+
77
+ /**
78
+ * starts a tsserver process to communicate with its API. use only when running on the workspace.
79
+ * @param options TsserverClientOpts
80
+ * @param files optionally, if check-types is enabled, provide files to open and type check.
81
+ * @returns TsserverClient
82
+ */
83
+ async initTsserverClientFromWorkspace(
84
+ options: TsserverClientOpts = {},
85
+ files: string[] = []
86
+ ): Promise<TsserverClient> {
87
+ if (!this.workspace) {
88
+ throw new Error(`initTsserverClientFromWorkspace: workspace was not found`);
89
+ }
90
+ return this.initTsserverClient(this.workspace.path, options, files);
91
+ }
92
+
42
93
  /**
43
94
  * create an instance of a typescript semantic schema extractor.
44
95
  */
@@ -57,14 +108,45 @@ export class TypescriptMain {
57
108
  };
58
109
  }
59
110
 
111
+ private getAllFilesForTsserver(components: Component[]): string[] {
112
+ const files = components
113
+ .map((c) => c.filesystem.files)
114
+ .flat()
115
+ .map((f) => f.path);
116
+ return files.filter((f) => f.endsWith('.ts') || f.endsWith('.tsx'));
117
+ }
118
+
119
+ private async onPreWatch(components: Component[], watchOpts: WatchOptions) {
120
+ const workspace = this.workspace;
121
+ if (!workspace || !watchOpts.spawnTSServer) {
122
+ return;
123
+ }
124
+ const { verbose, checkTypes } = watchOpts;
125
+ const files = checkTypes ? this.getAllFilesForTsserver(components) : [];
126
+ await this.initTsserverClientFromWorkspace({ verbose, checkTypes }, files);
127
+ }
128
+
129
+ private async onComponentChange(component: Component, files: string[]) {
130
+ if (!this.tsServer) {
131
+ return {
132
+ results: 'N/A',
133
+ };
134
+ }
135
+ await pMapSeries(files, (file) => this.tsServer.onFileChange(file));
136
+ return {
137
+ results: 'succeed',
138
+ };
139
+ }
140
+
60
141
  static runtime = MainRuntime;
61
- static dependencies = [SchemaAspect, LoggerAspect];
142
+ static dependencies = [SchemaAspect, LoggerAspect, WorkspaceAspect];
62
143
 
63
- static async provider([schema, loggerExt]: [SchemaMain, LoggerMain]) {
144
+ static async provider([schema, loggerExt, workspace]: [SchemaMain, LoggerMain, Workspace]) {
145
+ schema.registerParser(new TypeScriptParser());
64
146
  const logger = loggerExt.createLogger(TypescriptAspect.id);
65
147
  schema.registerParser(new TypeScriptParser(logger));
66
148
 
67
- return new TypescriptMain(logger);
149
+ return new TypescriptMain(logger, workspace);
68
150
  }
69
151
  }
70
152