@teambit/typescript 0.0.555 → 0.0.559

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.
@@ -0,0 +1,22 @@
1
+ import { Command, CommandOptions } from '@teambit/cli';
2
+ import { Logger } from '@teambit/logger';
3
+ import { Workspace } from '@teambit/workspace';
4
+ import { TypescriptMain } from '../typescript.main.runtime';
5
+ export declare class CheckTypesCmd implements Command {
6
+ private typescript;
7
+ private workspace;
8
+ private logger;
9
+ name: string;
10
+ description: string;
11
+ alias: string;
12
+ group: string;
13
+ options: CommandOptions;
14
+ constructor(typescript: TypescriptMain, workspace: Workspace, logger: Logger);
15
+ report([userPattern]: [string], { all, strict }: {
16
+ all: boolean;
17
+ strict: boolean;
18
+ }): Promise<{
19
+ code: number;
20
+ data: string;
21
+ }>;
22
+ }
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ require("core-js/modules/es.array.iterator.js");
6
+
7
+ require("core-js/modules/es.promise.js");
8
+
9
+ Object.defineProperty(exports, "__esModule", {
10
+ value: true
11
+ });
12
+ exports.CheckTypesCmd = void 0;
13
+
14
+ function _defineProperty2() {
15
+ const data = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
16
+
17
+ _defineProperty2 = function () {
18
+ return data;
19
+ };
20
+
21
+ return data;
22
+ }
23
+
24
+ function _exceptions() {
25
+ const data = require("@teambit/legacy/dist/consumer/exceptions");
26
+
27
+ _exceptions = function () {
28
+ return data;
29
+ };
30
+
31
+ return data;
32
+ }
33
+
34
+ function _chalk() {
35
+ const data = _interopRequireDefault(require("chalk"));
36
+
37
+ _chalk = function () {
38
+ return data;
39
+ };
40
+
41
+ return data;
42
+ }
43
+
44
+ class CheckTypesCmd {
45
+ constructor(typescript, workspace, logger) {
46
+ this.typescript = typescript;
47
+ this.workspace = workspace;
48
+ this.logger = logger;
49
+ (0, _defineProperty2().default)(this, "name", 'check-types [pattern]');
50
+ (0, _defineProperty2().default)(this, "description", 'check typescript types');
51
+ (0, _defineProperty2().default)(this, "alias", '');
52
+ (0, _defineProperty2().default)(this, "group", 'development');
53
+ (0, _defineProperty2().default)(this, "options", [['a', 'all', 'build all components, not only modified and new'], ['', 'strict', 'in case issues found, exit with code 1']]);
54
+ }
55
+
56
+ async report([userPattern], {
57
+ all = false,
58
+ strict = false
59
+ }) {
60
+ if (!this.workspace) throw new (_exceptions().ConsumerNotFound)();
61
+ const components = await this.workspace.getComponentsByUserInputDefaultToChanged(all, userPattern);
62
+ this.logger.setStatusLine(`checking types for ${components.length} components`);
63
+ const files = this.typescript.getSupportedFilesForTsserver(components);
64
+ await this.typescript.initTsserverClientFromWorkspace({
65
+ printTypeErrors: true
66
+ }, files);
67
+ const tsserver = this.typescript.getTsserverClient();
68
+ if (!tsserver) throw new Error(`unable to start tsserver`);
69
+ const start = Date.now();
70
+ await tsserver.getDiagnostic(files);
71
+ const end = Date.now() - start;
72
+ const msg = `completed type checking (${end / 1000} sec)`;
73
+ tsserver.killTsServer();
74
+
75
+ if (tsserver.lastDiagnostics.length) {
76
+ return {
77
+ code: strict ? 1 : 0,
78
+ data: _chalk().default.red(`${msg}. found errors in ${tsserver.lastDiagnostics.length} files.`)
79
+ };
80
+ }
81
+
82
+ return {
83
+ code: 0,
84
+ data: _chalk().default.green(`${msg}. no errors were found.`)
85
+ };
86
+ }
87
+
88
+ }
89
+
90
+ exports.CheckTypesCmd = CheckTypesCmd;
91
+
92
+ //# sourceMappingURL=check-types.cmd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["check-types.cmd.ts"],"names":["CheckTypesCmd","constructor","typescript","workspace","logger","report","userPattern","all","strict","ConsumerNotFound","components","getComponentsByUserInputDefaultToChanged","setStatusLine","length","files","getSupportedFilesForTsserver","initTsserverClientFromWorkspace","printTypeErrors","tsserver","getTsserverClient","Error","start","Date","now","getDiagnostic","end","msg","killTsServer","lastDiagnostics","code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AAJ,CAAW,0BAAX,CAAN;AACf,UAAMC,KAAK,GAAGC,IAAI,CAACC,GAAL,EAAd;AACA,UAAML,QAAQ,CAACM,aAAT,CAAuBV,KAAvB,CAAN;AACA,UAAMW,GAAG,GAAGH,IAAI,CAACC,GAAL,KAAaF,KAAzB;AACA,UAAMK,GAAG,GAAI,4BAA2BD,GAAG,GAAG,IAAK,OAAnD;AACAP,IAAAA,QAAQ,CAACS,YAAT;;AACA,QAAIT,QAAQ,CAACU,eAAT,CAAyBf,MAA7B,EAAqC;AACnC,aAAO;AACLgB,QAAAA,IAAI,EAAErB,MAAM,GAAG,CAAH,GAAO,CADd;AAELsB,QAAAA,IAAI,EAAEC,iBAAMC,GAAN,CAAW,GAAEN,GAAI,qBAAoBR,QAAQ,CAACU,eAAT,CAAyBf,MAAO,SAArE;AAFD,OAAP;AAID;;AACD,WAAO;AACLgB,MAAAA,IAAI,EAAE,CADD;AAELC,MAAAA,IAAI,EAAEC,iBAAME,KAAN,CAAa,GAAEP,GAAI,yBAAnB;AAFD,KAAP;AAID;;AAnC2C","sourcesContent":["import { Command, CommandOptions } from '@teambit/cli';\nimport { ConsumerNotFound } from '@teambit/legacy/dist/consumer/exceptions';\nimport { Logger } from '@teambit/logger';\nimport { Workspace } from '@teambit/workspace';\nimport chalk from 'chalk';\nimport { TypescriptMain } from '../typescript.main.runtime';\n\nexport class CheckTypesCmd implements Command {\n name = 'check-types [pattern]';\n description = 'check typescript types';\n alias = '';\n group = 'development';\n options = [\n ['a', 'all', 'build all components, not only modified and new'],\n ['', 'strict', 'in case issues found, exit with code 1'],\n ] as CommandOptions;\n\n constructor(private typescript: TypescriptMain, private workspace: Workspace, private logger: Logger) {}\n\n async report([userPattern]: [string], { all = false, strict = false }: { all: boolean; strict: boolean }) {\n if (!this.workspace) throw new ConsumerNotFound();\n const components = await this.workspace.getComponentsByUserInputDefaultToChanged(all, userPattern);\n this.logger.setStatusLine(`checking types for ${components.length} components`);\n const files = this.typescript.getSupportedFilesForTsserver(components);\n await this.typescript.initTsserverClientFromWorkspace({ printTypeErrors: true }, files);\n const tsserver = this.typescript.getTsserverClient();\n if (!tsserver) throw new Error(`unable to start tsserver`);\n const start = Date.now();\n await tsserver.getDiagnostic(files);\n const end = Date.now() - start;\n const msg = `completed type checking (${end / 1000} sec)`;\n tsserver.killTsServer();\n if (tsserver.lastDiagnostics.length) {\n return {\n code: strict ? 1 : 0,\n data: chalk.red(`${msg}. found errors in ${tsserver.lastDiagnostics.length} files.`),\n };\n }\n return {\n code: 0,\n data: chalk.green(`${msg}. no errors were found.`),\n };\n }\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import ts, { TsConfigSourceFile } from 'typescript';
2
+ import { CLIMain } from '@teambit/cli';
2
3
  import { Compiler } from '@teambit/compiler';
3
4
  import { Logger, LoggerMain } from '@teambit/logger';
4
5
  import { SchemaExtractor, SchemaMain } from '@teambit/schema';
@@ -6,6 +7,7 @@ import { PackageJsonProps } from '@teambit/pkg';
6
7
  import { TypescriptConfigMutator } from '@teambit/typescript.modules.ts-config-mutator';
7
8
  import type { Workspace } from '@teambit/workspace';
8
9
  import { TsserverClient, TsserverClientOpts } from '@teambit/ts-server';
10
+ import type { Component } from '@teambit/component';
9
11
  import { TypeScriptCompilerOptions } from './compiler-options';
10
12
  export declare type TsMode = 'build' | 'dev';
11
13
  export declare type TsConfigTransformContext = {};
@@ -47,11 +49,11 @@ export declare class TypescriptMain {
47
49
  * :TODO @gilad why do we need this DSL? can't I just get the args here.
48
50
  */
49
51
  getPackageJsonProps(): PackageJsonProps;
50
- private getAllFilesForTsserver;
52
+ getSupportedFilesForTsserver(components: Component[]): string[];
51
53
  private onPreWatch;
52
54
  private onComponentChange;
53
55
  static runtime: import("@teambit/harmony").RuntimeDefinition;
54
56
  static dependencies: import("@teambit/harmony").Aspect[];
55
- static provider([schema, loggerExt, workspace]: [SchemaMain, LoggerMain, Workspace]): Promise<TypescriptMain>;
57
+ static provider([schema, loggerExt, workspace, cli]: [SchemaMain, LoggerMain, Workspace, CLIMain]): Promise<TypescriptMain>;
56
58
  }
57
59
  export declare function runTransformersWithContext(config: TypescriptConfigMutator, transformers: TsConfigTransformer[] | undefined, context: TsConfigTransformContext): TypescriptConfigMutator;
@@ -146,6 +146,16 @@ function _typescript5() {
146
146
  return data;
147
147
  }
148
148
 
149
+ function _checkTypes() {
150
+ const data = require("./cmds/check-types.cmd");
151
+
152
+ _checkTypes = function () {
153
+ return data;
154
+ };
155
+
156
+ return data;
157
+ }
158
+
149
159
  class TypescriptMain {
150
160
  constructor(logger, workspace) {
151
161
  this.logger = logger;
@@ -227,7 +237,7 @@ class TypescriptMain {
227
237
  };
228
238
  }
229
239
 
230
- getAllFilesForTsserver(components) {
240
+ getSupportedFilesForTsserver(components) {
231
241
  const files = components.map(c => c.filesystem.files).flat().map(f => f.path);
232
242
  return files.filter(f => f.endsWith('.ts') || f.endsWith('.tsx'));
233
243
  }
@@ -243,10 +253,12 @@ class TypescriptMain {
243
253
  verbose,
244
254
  checkTypes
245
255
  } = watchOpts;
246
- const files = checkTypes ? this.getAllFilesForTsserver(components) : [];
256
+ const files = checkTypes ? this.getSupportedFilesForTsserver(components) : [];
257
+ const printTypeErrors = Boolean(checkTypes);
247
258
  await this.initTsserverClientFromWorkspace({
248
259
  verbose,
249
- checkTypes
260
+ checkTypes,
261
+ printTypeErrors
250
262
  }, files);
251
263
  }
252
264
 
@@ -263,18 +275,21 @@ class TypescriptMain {
263
275
  };
264
276
  }
265
277
 
266
- static async provider([schema, loggerExt, workspace]) {
278
+ static async provider([schema, loggerExt, workspace, cli]) {
267
279
  schema.registerParser(new (_typescript5().TypeScriptParser)());
268
280
  const logger = loggerExt.createLogger(_typescript3().TypescriptAspect.id);
269
281
  schema.registerParser(new (_typescript5().TypeScriptParser)(logger));
270
- return new TypescriptMain(logger, workspace);
282
+ const typescriptMain = new TypescriptMain(logger, workspace);
283
+ const checkTypesCmd = new (_checkTypes().CheckTypesCmd)(typescriptMain, workspace, logger);
284
+ cli.register(checkTypesCmd);
285
+ return typescriptMain;
271
286
  }
272
287
 
273
288
  }
274
289
 
275
290
  exports.TypescriptMain = TypescriptMain;
276
291
  (0, _defineProperty2().default)(TypescriptMain, "runtime", _cli().MainRuntime);
277
- (0, _defineProperty2().default)(TypescriptMain, "dependencies", [_schema().SchemaAspect, _logger().LoggerAspect, _workspace().default]);
292
+ (0, _defineProperty2().default)(TypescriptMain, "dependencies", [_schema().SchemaAspect, _logger().LoggerAspect, _workspace().default, _cli().CLIAspect]);
278
293
 
279
294
  _typescript3().TypescriptAspect.addRuntime(TypescriptMain);
280
295
 
@@ -1 +1 @@
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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BAgHW,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"]}
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","getSupportedFilesForTsserver","components","map","c","filesystem","flat","f","filter","endsWith","watchOpts","spawnTSServer","verbose","checkTypes","printTypeErrors","Boolean","component","results","file","onFileChange","provider","schema","loggerExt","cli","registerParser","TypeScriptParser","createLogger","typescriptMain","checkTypesCmd","CheckTypesCmd","register","MainRuntime","SchemaAspect","LoggerAspect","WorkspaceAspect","CLIAspect","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;;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;AAC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Y,CAACsE,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 { CLIAspect, CLIMain, 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';\nimport { CheckTypesCmd } from './cmds/check-types.cmd';\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 public getSupportedFilesForTsserver(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.getSupportedFilesForTsserver(components) : [];\n const printTypeErrors = Boolean(checkTypes);\n await this.initTsserverClientFromWorkspace({ verbose, checkTypes, printTypeErrors }, 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, CLIAspect];\n\n static async provider([schema, loggerExt, workspace, cli]: [SchemaMain, LoggerMain, Workspace, CLIMain]) {\n schema.registerParser(new TypeScriptParser());\n const logger = loggerExt.createLogger(TypescriptAspect.id);\n schema.registerParser(new TypeScriptParser(logger));\n const typescriptMain = new TypescriptMain(logger, workspace);\n const checkTypesCmd = new CheckTypesCmd(typescriptMain, workspace, logger);\n cli.register(checkTypesCmd);\n\n return typescriptMain;\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,12 +1,12 @@
1
1
  {
2
2
  "name": "@teambit/typescript",
3
- "version": "0.0.555",
3
+ "version": "0.0.559",
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.555"
9
+ "version": "0.0.559"
10
10
  },
11
11
  "dependencies": {
12
12
  "@teambit/harmony": "0.2.11",
@@ -14,20 +14,21 @@
14
14
  "typescript": "4.4.2",
15
15
  "typedoc": "0.22.5",
16
16
  "p-map-series": "2.1.0",
17
+ "chalk": "2.4.2",
17
18
  "@babel/runtime": "7.12.18",
18
19
  "core-js": "^3.0.0",
19
- "@teambit/compiler": "0.0.555",
20
- "@teambit/typescript.modules.ts-config-mutator": "0.0.43",
21
- "@teambit/bit-error": "0.0.372",
22
- "@teambit/builder": "0.0.555",
23
- "@teambit/isolator": "0.0.555",
24
- "@teambit/logger": "0.0.471",
25
- "@teambit/component": "0.0.555",
26
- "@teambit/schema": "0.0.555",
27
- "@teambit/cli": "0.0.386",
28
- "@teambit/pkg": "0.0.555",
29
- "@teambit/ts-server": "0.0.9",
30
- "@teambit/workspace": "0.0.555"
20
+ "@teambit/compiler": "0.0.559",
21
+ "@teambit/typescript.modules.ts-config-mutator": "0.0.46",
22
+ "@teambit/bit-error": "0.0.375",
23
+ "@teambit/builder": "0.0.559",
24
+ "@teambit/isolator": "0.0.559",
25
+ "@teambit/logger": "0.0.474",
26
+ "@teambit/component": "0.0.559",
27
+ "@teambit/schema": "0.0.559",
28
+ "@teambit/cli": "0.0.389",
29
+ "@teambit/pkg": "0.0.559",
30
+ "@teambit/ts-server": "0.0.12",
31
+ "@teambit/workspace": "0.0.559"
31
32
  },
32
33
  "devDependencies": {
33
34
  "chai": "4.3.0",
@@ -39,10 +40,10 @@
39
40
  "@types/jest": "^26.0.0",
40
41
  "@types/react-dom": "^17.0.5",
41
42
  "@types/node": "12.20.4",
42
- "@teambit/typescript.aspect-docs.typescript": "0.0.105"
43
+ "@teambit/typescript.aspect-docs.typescript": "0.0.108"
43
44
  },
44
45
  "peerDependencies": {
45
- "@teambit/legacy": "1.0.172",
46
+ "@teambit/legacy": "1.0.175",
46
47
  "react-dom": "^16.8.0 || ^17.0.0",
47
48
  "react": "^16.8.0 || ^17.0.0"
48
49
  },
@@ -70,12 +71,27 @@
70
71
  "react": "-"
71
72
  },
72
73
  "peerDependencies": {
73
- "@teambit/legacy": "1.0.172",
74
+ "@teambit/legacy": "1.0.175",
74
75
  "react-dom": "^16.8.0 || ^17.0.0",
75
76
  "react": "^16.8.0 || ^17.0.0"
76
77
  }
77
78
  }
78
79
  },
80
+ "files": [
81
+ "dist",
82
+ "!dist/tsconfig.tsbuildinfo",
83
+ "**/*.md",
84
+ "**/*.mdx",
85
+ "**/*.js",
86
+ "**/*.json",
87
+ "**/*.sass",
88
+ "**/*.scss",
89
+ "**/*.less",
90
+ "**/*.css",
91
+ "**/*.css",
92
+ "**/*.jpeg",
93
+ "**/*.gif"
94
+ ],
79
95
  "private": false,
80
96
  "engines": {
81
97
  "node": ">=12.22.0"
package/tsconfig.json CHANGED
@@ -15,9 +15,9 @@
15
15
  "skipLibCheck": true,
16
16
  "moduleResolution": "node",
17
17
  "esModuleInterop": true,
18
- "outDir": "dist",
19
18
  "composite": true,
20
19
  "emitDeclarationOnly": true,
20
+ "outDir": "dist",
21
21
  "experimentalDecorators": true,
22
22
  "emitDecoratorMetadata": true,
23
23
  "allowSyntheticDefaultImports": true,
package/cmds/init.cmd.ts DELETED
File without changes
@@ -1,27 +0,0 @@
1
- import type { CompilerOptions } from '@teambit/compiler';
2
-
3
- export type TypeScriptCompilerOptions = {
4
- /**
5
- * tsconfig to use during compilation.
6
- */
7
- tsconfig: Record<string, any>;
8
-
9
- /**
10
- * path for .d.ts files to include during build.
11
- */
12
- types: string[];
13
-
14
- /**
15
- * Run the compiler for .js files. this will only affect whether to run the compiler on the files
16
- * or not. It won't change the tsconfig to support or not support js files.
17
- */
18
- compileJs?: boolean;
19
-
20
- /**
21
- * Run the compiler for .js files. this will only affect whether to run the compiler on the files
22
- * or not. It won't change the tsconfig to support or not support jsx files.
23
- */
24
- compileJsx?: boolean;
25
- } & Partial<CompilerOptions>;
26
-
27
- export type TsCompilerOptionsWithoutTsConfig = Omit<TypeScriptCompilerOptions, 'tsconfig'>;
package/index.ts DELETED
@@ -1,5 +0,0 @@
1
- export { TypescriptConfigMutator } from '@teambit/typescript.modules.ts-config-mutator';
2
- export { TypescriptCompiler } from './typescript.compiler';
3
- export type { TypescriptMain, TsConfigTransformer } from './typescript.main.runtime';
4
- export type { TypeScriptCompilerOptions, TsCompilerOptionsWithoutTsConfig } from './compiler-options';
5
- export { TypescriptAspect } from './typescript.aspect';
package/types/asset.d.ts DELETED
@@ -1,29 +0,0 @@
1
- declare module '*.png' {
2
- const value: any;
3
- export = value;
4
- }
5
- declare module '*.svg' {
6
- import type { FunctionComponent, SVGProps } from 'react';
7
-
8
- export const ReactComponent: FunctionComponent<SVGProps<SVGSVGElement> & { title?: string }>;
9
- const src: string;
10
- export default src;
11
- }
12
-
13
- // @TODO Gilad
14
- declare module '*.jpg' {
15
- const value: any;
16
- export = value;
17
- }
18
- declare module '*.jpeg' {
19
- const value: any;
20
- export = value;
21
- }
22
- declare module '*.gif' {
23
- const value: any;
24
- export = value;
25
- }
26
- declare module '*.bmp' {
27
- const value: any;
28
- export = value;
29
- }
package/types/style.d.ts DELETED
@@ -1,42 +0,0 @@
1
- declare module '*.module.css' {
2
- const classes: { readonly [key: string]: string };
3
- export default classes;
4
- }
5
- declare module '*.module.scss' {
6
- const classes: { readonly [key: string]: string };
7
- export default classes;
8
- }
9
- declare module '*.module.sass' {
10
- const classes: { readonly [key: string]: string };
11
- export default classes;
12
- }
13
-
14
- declare module '*.module.less' {
15
- const classes: { readonly [key: string]: string };
16
- export default classes;
17
- }
18
-
19
- declare module '*.less' {
20
- const classes: { readonly [key: string]: string };
21
- export default classes;
22
- }
23
-
24
- declare module '*.css' {
25
- const classes: { readonly [key: string]: string };
26
- export default classes;
27
- }
28
-
29
- declare module '*.sass' {
30
- const classes: { readonly [key: string]: string };
31
- export default classes;
32
- }
33
-
34
- declare module '*.scss' {
35
- const classes: { readonly [key: string]: string };
36
- export default classes;
37
- }
38
-
39
- declare module '*.mdx' {
40
- const component: any;
41
- export default component;
42
- }
@@ -1,5 +0,0 @@
1
- import { Aspect } from '@teambit/harmony';
2
-
3
- export const TypescriptAspect = Aspect.create({
4
- id: 'teambit.typescript/typescript',
5
- });
@@ -1,63 +0,0 @@
1
- import { Logger } from '@teambit/logger';
2
- import ts from 'typescript';
3
- import { expect } from 'chai';
4
- import path from 'path';
5
- import { TypescriptAspect } from './typescript.aspect';
6
-
7
- import { TypescriptCompiler } from './typescript.compiler';
8
- import type { TsCompilerOptionsWithoutTsConfig } from './compiler-options';
9
-
10
- const defaultOpts = {
11
- tsconfig: {},
12
- types: [],
13
- };
14
-
15
- describe('TypescriptCompiler', () => {
16
- describe('getDistPathBySrcPath', () => {
17
- it('should replace the extension with .js and prepend the dist dir', () => {
18
- const tsCompiler = getTsCompiler();
19
- expect(tsCompiler.getDistPathBySrcPath('index.ts')).to.equal(path.join('dist', 'index.js'));
20
- expect(tsCompiler.getDistPathBySrcPath('index.tsx')).to.equal(path.join('dist', 'index.js'));
21
- });
22
- it('should not replace the extension if the file is not supported', () => {
23
- const tsCompiler = getTsCompiler();
24
- expect(tsCompiler.getDistPathBySrcPath('style.css')).to.equal(path.join('dist', 'style.css'));
25
- expect(tsCompiler.getDistPathBySrcPath('index.d.ts')).to.equal(path.join('dist', 'index.d.ts'));
26
- });
27
- });
28
- describe('isFileSupported', () => {
29
- it('should support .ts files', () => {
30
- const tsCompiler = getTsCompiler();
31
- expect(tsCompiler.isFileSupported('index.ts')).to.be.true;
32
- });
33
- it('should support .tsx files', () => {
34
- const tsCompiler = getTsCompiler();
35
- expect(tsCompiler.isFileSupported('index.tsx')).to.be.true;
36
- });
37
- it('should not support .jsx files by default', () => {
38
- const tsCompiler = getTsCompiler();
39
- expect(tsCompiler.isFileSupported('index.jsx')).to.be.false;
40
- });
41
- it('should not support .js files by default', () => {
42
- const tsCompiler = getTsCompiler();
43
- expect(tsCompiler.isFileSupported('index.js')).to.be.false;
44
- });
45
- it('should support .jsx files when passing compileJsx', () => {
46
- const tsCompiler = getTsCompiler({ compileJsx: true, ...defaultOpts });
47
- expect(tsCompiler.isFileSupported('index.jsx')).to.be.true;
48
- });
49
- it('should support .js files when passing compileJs', () => {
50
- const tsCompiler = getTsCompiler({ compileJs: true, ...defaultOpts });
51
- expect(tsCompiler.isFileSupported('index.js')).to.be.true;
52
- });
53
- it('should not support .d.ts files', () => {
54
- const tsCompiler = getTsCompiler();
55
- expect(tsCompiler.isFileSupported('index.d.ts')).to.be.false;
56
- });
57
- });
58
- });
59
-
60
- function getTsCompiler(opts: TsCompilerOptionsWithoutTsConfig = defaultOpts) {
61
- const finalOpts = Object.assign({}, defaultOpts, opts);
62
- return new TypescriptCompiler(TypescriptAspect.id, new Logger('test'), finalOpts, ts);
63
- }
@@ -1,293 +0,0 @@
1
- import { BuildContext, BuiltTaskResult, ComponentResult } from '@teambit/builder';
2
- import { Compiler, TranspileFileParams, TranspileFileOutput } from '@teambit/compiler';
3
- import { Network } from '@teambit/isolator';
4
- import { Logger } from '@teambit/logger';
5
- import fs from 'fs-extra';
6
- import path from 'path';
7
- import ts from 'typescript';
8
- import { BitError } from '@teambit/bit-error';
9
- import PackageJsonFile from '@teambit/legacy/dist/consumer/component/package-json-file';
10
- import { TypeScriptCompilerOptions } from './compiler-options';
11
-
12
- export class TypescriptCompiler implements Compiler {
13
- distDir: string;
14
- distGlobPatterns: string[];
15
- shouldCopyNonSupportedFiles: boolean;
16
- artifactName: string;
17
- constructor(
18
- readonly id: string,
19
- private logger: Logger,
20
- private options: TypeScriptCompilerOptions,
21
- private tsModule: typeof ts
22
- ) {
23
- this.distDir = options.distDir || 'dist';
24
- this.distGlobPatterns = options.distGlobPatterns || [`${this.distDir}/**`, `!${this.distDir}/tsconfig.tsbuildinfo`];
25
- this.shouldCopyNonSupportedFiles =
26
- typeof options.shouldCopyNonSupportedFiles === 'boolean' ? options.shouldCopyNonSupportedFiles : true;
27
- this.artifactName = options.artifactName || 'dist';
28
- this.options.tsconfig ||= {};
29
- this.options.tsconfig.compilerOptions ||= {};
30
- // mutate the outDir, otherwise, on capsules, the dists might be written to a different directory and make confusion
31
- this.options.tsconfig.compilerOptions.outDir = this.distDir;
32
- }
33
-
34
- displayName = 'TypeScript';
35
-
36
- displayConfig() {
37
- return this.stringifyTsconfig(this.options.tsconfig);
38
- }
39
-
40
- /**
41
- * compile one file on the workspace
42
- */
43
- transpileFile(fileContent: string, options: TranspileFileParams): TranspileFileOutput {
44
- if (!this.isFileSupported(options.filePath)) {
45
- return null; // file is not supported
46
- }
47
- const compilerOptionsFromTsconfig = this.tsModule.convertCompilerOptionsFromJson(
48
- this.options.tsconfig.compilerOptions,
49
- '.'
50
- );
51
- if (compilerOptionsFromTsconfig.errors.length) {
52
- // :TODO @david replace to a more concrete error type and put in 'exceptions' directory here.
53
- const formattedErrors = this.tsModule.formatDiagnosticsWithColorAndContext(
54
- compilerOptionsFromTsconfig.errors,
55
- this.getFormatDiagnosticsHost()
56
- );
57
- throw new Error(`failed parsing the tsconfig.json.\n${formattedErrors}`);
58
- }
59
-
60
- const compilerOptions = compilerOptionsFromTsconfig.options;
61
- compilerOptions.sourceRoot = options.componentDir;
62
- compilerOptions.rootDir = '.';
63
- const result = this.tsModule.transpileModule(fileContent, {
64
- compilerOptions,
65
- fileName: options.filePath,
66
- reportDiagnostics: true,
67
- });
68
-
69
- if (result.diagnostics && result.diagnostics.length) {
70
- const formatHost = this.getFormatDiagnosticsHost();
71
- const error = this.tsModule.formatDiagnosticsWithColorAndContext(result.diagnostics, formatHost);
72
-
73
- // :TODO @david please replace to a more concrete error type and put in 'exceptions' directory here.
74
- throw new Error(error);
75
- }
76
-
77
- const outputPath = this.replaceFileExtToJs(options.filePath);
78
- const outputFiles = [{ outputText: result.outputText, outputPath }];
79
- if (result.sourceMapText) {
80
- outputFiles.push({
81
- outputText: result.sourceMapText,
82
- outputPath: `${outputPath}.map`,
83
- });
84
- }
85
- return outputFiles;
86
- }
87
-
88
- async preBuild(context: BuildContext) {
89
- const capsules = context.capsuleNetwork.seedersCapsules;
90
- const capsuleDirs = capsules.map((capsule) => capsule.path);
91
- await this.writeTsConfig(capsuleDirs);
92
- await this.writeTypes(capsuleDirs);
93
- await this.writeNpmIgnore(capsuleDirs);
94
- }
95
-
96
- /**
97
- * compile multiple components on the capsules
98
- */
99
- async build(context: BuildContext): Promise<BuiltTaskResult> {
100
- const componentsResults = await this.runTscBuild(context.capsuleNetwork);
101
-
102
- return {
103
- artifacts: this.getArtifactDefinition(),
104
- componentsResults,
105
- };
106
- }
107
-
108
- async postBuild(context: BuildContext) {
109
- await Promise.all(
110
- context.capsuleNetwork.seedersCapsules.map(async (capsule) => {
111
- const packageJson = PackageJsonFile.loadFromCapsuleSync(capsule.path);
112
- // the types['index.ts'] is needed only during the build to avoid errors when tsc finds the
113
- // same type once in the d.ts and once in the ts file.
114
- if (packageJson.packageJsonObject.types) {
115
- delete packageJson.packageJsonObject.types;
116
- await packageJson.write();
117
- }
118
- })
119
- );
120
- }
121
-
122
- getArtifactDefinition() {
123
- return [
124
- {
125
- generatedBy: this.id,
126
- name: this.artifactName,
127
- globPatterns: this.distGlobPatterns,
128
- },
129
- ];
130
- }
131
-
132
- /**
133
- * given a source file, return its parallel in the dists. e.g. index.ts => dist/index.js
134
- */
135
- getDistPathBySrcPath(srcPath: string) {
136
- const fileWithJSExtIfNeeded = this.replaceFileExtToJs(srcPath);
137
- return path.join(this.distDir, fileWithJSExtIfNeeded);
138
- }
139
-
140
- /**
141
- * whether typescript is able to compile the given path
142
- */
143
- isFileSupported(filePath: string): boolean {
144
- const isJsAndCompile = !!this.options.compileJs && filePath.endsWith('.js');
145
- const isJsxAndCompile = !!this.options.compileJsx && filePath.endsWith('.jsx');
146
- return (
147
- (filePath.endsWith('.ts') || filePath.endsWith('.tsx') || isJsAndCompile || isJsxAndCompile) &&
148
- !filePath.endsWith('.d.ts')
149
- );
150
- }
151
-
152
- /**
153
- * we have two options here:
154
- * 1. pass all capsules-dir at the second parameter of createSolutionBuilder and then no
155
- * need to write the main tsconfig.json with all the references.
156
- * 2. write main tsconfig.json and pass the capsules root-dir.
157
- * we went with option #2 because it'll be easier for users to go to the capsule-root and run
158
- * `tsc --build` to debug issues.
159
- */
160
- private async runTscBuild(network: Network): Promise<ComponentResult[]> {
161
- const rootDir = network.capsulesRootDir;
162
- const capsules = network.graphCapsules;
163
- const capsuleDirs = capsules.getAllCapsuleDirs();
164
- const formatHost = {
165
- getCanonicalFileName: (p) => p,
166
- getCurrentDirectory: () => '', // it helps to get the files with absolute paths
167
- getNewLine: () => this.tsModule.sys.newLine,
168
- };
169
- const componentsResults: ComponentResult[] = [];
170
- let currentComponentResult: Partial<ComponentResult> = { errors: [] };
171
- const reportDiagnostic = (diagnostic: ts.Diagnostic) => {
172
- const errorStr = process.stdout.isTTY
173
- ? this.tsModule.formatDiagnosticsWithColorAndContext([diagnostic], formatHost)
174
- : this.tsModule.formatDiagnostic(diagnostic, formatHost);
175
- if (!diagnostic.file) {
176
- // the error is general and not related to a specific file. e.g. tsconfig is missing.
177
- throw new BitError(errorStr);
178
- }
179
- this.logger.consoleFailure(errorStr);
180
- if (!currentComponentResult.component || !currentComponentResult.errors) {
181
- throw new Error(`currentComponentResult is not defined yet for ${diagnostic.file}`);
182
- }
183
- currentComponentResult.errors.push(errorStr);
184
- };
185
- // this only works when `verbose` is `true` in the `ts.createSolutionBuilder` function.
186
- const reportSolutionBuilderStatus = (diag: ts.Diagnostic) => {
187
- const msg = diag.messageText as string;
188
- this.logger.debug(msg);
189
- };
190
- const errorCounter = (errorCount: number) => {
191
- this.logger.info(`total error found: ${errorCount}`);
192
- };
193
- const host = this.tsModule.createSolutionBuilderHost(
194
- undefined,
195
- undefined,
196
- reportDiagnostic,
197
- reportSolutionBuilderStatus,
198
- errorCounter
199
- );
200
- await this.writeProjectReferencesTsConfig(rootDir, capsuleDirs);
201
- const solutionBuilder = this.tsModule.createSolutionBuilder(host, [rootDir], { verbose: true });
202
- let nextProject;
203
- const longProcessLogger = this.logger.createLongProcessLogger('compile typescript components', capsules.length);
204
- // eslint-disable-next-line no-cond-assign
205
- while ((nextProject = solutionBuilder.getNextInvalidatedProject())) {
206
- // regex to make sure it will work correctly for both linux and windows
207
- // it replaces both /tsconfig.json and \tsocnfig.json
208
- const capsulePath = nextProject.project.replace(/[/\\]tsconfig.json/, '');
209
- const currentComponentId = capsules.getIdByPathInCapsule(capsulePath);
210
- if (!currentComponentId) throw new Error(`unable to find component for ${capsulePath}`);
211
- longProcessLogger.logProgress(currentComponentId.toString());
212
- const capsule = capsules.getCapsule(currentComponentId);
213
- if (!capsule) throw new Error(`unable to find capsule for ${currentComponentId.toString()}`);
214
- currentComponentResult.component = capsule.component;
215
- currentComponentResult.startTime = Date.now();
216
- nextProject.done();
217
- currentComponentResult.endTime = Date.now();
218
- componentsResults.push({ ...currentComponentResult } as ComponentResult);
219
- currentComponentResult = { errors: [] };
220
- }
221
- longProcessLogger.end();
222
-
223
- return componentsResults;
224
- }
225
-
226
- private getFormatDiagnosticsHost(): ts.FormatDiagnosticsHost {
227
- return {
228
- getCanonicalFileName: (p) => p,
229
- getCurrentDirectory: this.tsModule.sys.getCurrentDirectory,
230
- getNewLine: () => this.tsModule.sys.newLine,
231
- };
232
- }
233
-
234
- private async writeTypes(dirs: string[]) {
235
- await Promise.all(
236
- this.options.types.map(async (typePath) => {
237
- const contents = await fs.readFile(typePath, 'utf8');
238
- const filename = path.basename(typePath);
239
-
240
- await Promise.all(
241
- dirs.map(async (dir) => {
242
- const filePath = path.join(dir, 'types', filename);
243
- if (!(await fs.pathExists(filePath))) {
244
- await fs.outputFile(filePath, contents);
245
- }
246
- })
247
- );
248
- })
249
- );
250
- }
251
-
252
- /**
253
- * when using project-references, typescript adds a file "tsconfig.tsbuildinfo" which is not
254
- * needed for the package.
255
- */
256
- private async writeNpmIgnore(dirs: string[]) {
257
- const NPM_IGNORE_FILE = '.npmignore';
258
- await Promise.all(
259
- dirs.map(async (dir) => {
260
- const npmIgnorePath = path.join(dir, NPM_IGNORE_FILE);
261
- const npmIgnoreEntriesStr = `\n${this.distDir}/tsconfig.tsbuildinfo\n`;
262
- await fs.appendFile(npmIgnorePath, npmIgnoreEntriesStr);
263
- })
264
- );
265
- }
266
-
267
- private async writeProjectReferencesTsConfig(rootDir: string, projects: string[]) {
268
- const files = [];
269
- const references = projects.map((project) => ({ path: project }));
270
- const tsconfig = { files, references };
271
- const tsconfigStr = this.stringifyTsconfig(tsconfig);
272
- await fs.writeFile(path.join(rootDir, 'tsconfig.json'), tsconfigStr);
273
- }
274
-
275
- private async writeTsConfig(dirs: string[]) {
276
- const tsconfigStr = this.stringifyTsconfig(this.options.tsconfig);
277
- await Promise.all(dirs.map((dir) => fs.writeFile(path.join(dir, 'tsconfig.json'), tsconfigStr)));
278
- }
279
-
280
- private stringifyTsconfig(tsconfig) {
281
- return JSON.stringify(tsconfig, undefined, 2);
282
- }
283
-
284
- private replaceFileExtToJs(filePath: string): string {
285
- if (!this.isFileSupported(filePath)) return filePath;
286
- const fileExtension = path.extname(filePath);
287
- return filePath.replace(new RegExp(`${fileExtension}$`), '.js'); // makes sure it's the last occurrence
288
- }
289
-
290
- version() {
291
- return this.tsModule.version;
292
- }
293
- }
@@ -1,7 +0,0 @@
1
- import React from 'react';
2
-
3
- export const Logo = () => (
4
- <div style={{ height: '100%', display: 'flex', justifyContent: 'center' }}>
5
- <img style={{ width: 70 }} src="https://static.bit.dev/brands/logo-typescript.svg" />
6
- </div>
7
- );
@@ -1,33 +0,0 @@
1
- // import { tmpdir } from 'os';
2
- import { TsConfigSourceFile } from 'typescript';
3
- // import { resolve, join } from 'path';
4
- import { Module, SchemaExtractor } from '@teambit/schema';
5
- import { Component } from '@teambit/component';
6
- import { Application } from 'typedoc';
7
-
8
- export class TypeScriptExtractor implements SchemaExtractor {
9
- constructor(private tsconfig: TsConfigSourceFile) {}
10
-
11
- async extract(component: Component) {
12
- // const tsconfig = this.tsconfig;
13
- const paths = component.state.filesystem.files.map((file) => file.path).filter((path) => path.endsWith('index.ts'));
14
- // const paths = ['/Users/ranmizrahi/Bit/bit/scopes/workspace/workspace/index.ts'];
15
- const app = new Application();
16
- app.bootstrap({
17
- // typedoc options here
18
- entryPoints: paths,
19
- });
20
- const project = app.convert();
21
- // typedocApp.options.setValues({
22
- // inputFiles: paths,
23
- // allowJs: true,
24
- // lib: ['lib.es2015.d.ts', 'lib.es2019.d.ts', 'lib.es6.d.ts', 'lib.dom.d.ts', 'lib.dom.iterable.d.ts'],
25
- // jsx: 2,
26
- // noEmit: true,
27
- // exclude: ['node_modules', '*.scss'],
28
- // esModuleInterop: true,
29
- // });
30
- if (!project) throw new Error('typedoc failed generating docs');
31
- return app.serializer.projectToObject(project) as any as Module;
32
- }
33
- }
@@ -1,165 +0,0 @@
1
- import ts, { TsConfigSourceFile } from 'typescript';
2
- import { MainRuntime } from '@teambit/cli';
3
- import { Compiler } from '@teambit/compiler';
4
- import { Logger, LoggerAspect, LoggerMain } from '@teambit/logger';
5
- import { SchemaAspect, SchemaExtractor, SchemaMain } from '@teambit/schema';
6
- import { PackageJsonProps } from '@teambit/pkg';
7
- import { TypescriptConfigMutator } from '@teambit/typescript.modules.ts-config-mutator';
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';
13
- import { TypeScriptExtractor } from './typescript.extractor';
14
- import { TypeScriptCompilerOptions } from './compiler-options';
15
- import { TypescriptAspect } from './typescript.aspect';
16
- import { TypescriptCompiler } from './typescript.compiler';
17
- import { TypeScriptParser } from './typescript.parser';
18
-
19
- export type TsMode = 'build' | 'dev';
20
-
21
- export type TsConfigTransformContext = {
22
- // mode: TsMode;
23
- };
24
-
25
- export type TsConfigTransformer = (
26
- config: TypescriptConfigMutator,
27
- context: TsConfigTransformContext
28
- ) => TypescriptConfigMutator;
29
-
30
- export class TypescriptMain {
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
- }
39
- /**
40
- * create a new compiler.
41
- */
42
- createCompiler(
43
- options: TypeScriptCompilerOptions,
44
- transformers: TsConfigTransformer[] = [],
45
- tsModule = ts
46
- ): Compiler {
47
- const configMutator = new TypescriptConfigMutator(options);
48
- const transformerContext: TsConfigTransformContext = {};
49
- const afterMutation = runTransformersWithContext(configMutator.clone(), transformers, transformerContext);
50
- return new TypescriptCompiler(TypescriptAspect.id, this.logger, afterMutation.raw, tsModule);
51
- }
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
-
93
- /**
94
- * create an instance of a typescript semantic schema extractor.
95
- */
96
- createSchemaExtractor(tsconfig: TsConfigSourceFile): SchemaExtractor {
97
- return new TypeScriptExtractor(tsconfig);
98
- }
99
-
100
- /**
101
- * add the default package json properties to the component
102
- * :TODO @gilad why do we need this DSL? can't I just get the args here.
103
- */
104
- getPackageJsonProps(): PackageJsonProps {
105
- return {
106
- main: 'dist/{main}.js',
107
- types: '{main}.ts',
108
- };
109
- }
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
-
141
- static runtime = MainRuntime;
142
- static dependencies = [SchemaAspect, LoggerAspect, WorkspaceAspect];
143
-
144
- static async provider([schema, loggerExt, workspace]: [SchemaMain, LoggerMain, Workspace]) {
145
- schema.registerParser(new TypeScriptParser());
146
- const logger = loggerExt.createLogger(TypescriptAspect.id);
147
- schema.registerParser(new TypeScriptParser(logger));
148
-
149
- return new TypescriptMain(logger, workspace);
150
- }
151
- }
152
-
153
- TypescriptAspect.addRuntime(TypescriptMain);
154
-
155
- export function runTransformersWithContext(
156
- config: TypescriptConfigMutator,
157
- transformers: TsConfigTransformer[] = [],
158
- context: TsConfigTransformContext
159
- ): TypescriptConfigMutator {
160
- if (!Array.isArray(transformers)) return config;
161
- const newConfig = transformers.reduce((acc, transformer) => {
162
- return transformer(acc, context);
163
- }, config);
164
- return newConfig;
165
- }
@@ -1,129 +0,0 @@
1
- import ts from 'typescript';
2
- import { expect } from 'chai';
3
-
4
- import { TypeScriptParser } from './typescript.parser';
5
-
6
- describe('TypescriptParser', () => {
7
- describe('getExports', () => {
8
- const exampleArrowFunction = `
9
- export const arrow = () => { return 3; }
10
- arrow.textProperty = "propertyValue";
11
- `;
12
-
13
- const exampleFunction = `
14
- export function func() { return 3; }
15
- func.textProperty = "propertyValue";
16
- `;
17
-
18
- const exampleClass = `
19
- export class classy{ render() { return 3; } }
20
- classy.textProperty = "propertyValue";
21
- `;
22
-
23
- it('should parse arrowFunctions', () => {
24
- const ast = ts.createSourceFile('example.tsx', exampleArrowFunction, ts.ScriptTarget.Latest);
25
- const exports = new TypeScriptParser().getExports(ast);
26
-
27
- const exportArrow = exports.find((x) => x.identifier === 'arrow');
28
-
29
- expect(exportArrow).to.exist;
30
- });
31
-
32
- it('should parse function exports', () => {
33
- const ast = ts.createSourceFile('example.tsx', exampleFunction, ts.ScriptTarget.Latest);
34
- const exports = new TypeScriptParser().getExports(ast);
35
-
36
- const exportFunction = exports.find((x) => x.identifier === 'func');
37
-
38
- expect(exportFunction).to.exist;
39
- });
40
-
41
- it('should parse classes', () => {
42
- const ast = ts.createSourceFile('example.tsx', exampleClass, ts.ScriptTarget.Latest);
43
- const exports = new TypeScriptParser().getExports(ast);
44
-
45
- const exportClass = exports.find((x) => x.identifier === 'classy');
46
-
47
- expect(exportClass).to.exist;
48
- });
49
-
50
- describe('staticProperties', () => {
51
- it('should include staticProperties, when on arrowFunctions', () => {
52
- const ast = ts.createSourceFile('example.tsx', exampleArrowFunction, ts.ScriptTarget.Latest);
53
- const exports = new TypeScriptParser().getExports(ast);
54
-
55
- const exportArrow = exports.find((x) => x.identifier === 'arrow');
56
-
57
- expect(exportArrow?.staticProperties?.get('textProperty')).to.equal('propertyValue');
58
- });
59
-
60
- it('should include staticProperties, when on regular functions', () => {
61
- const ast = ts.createSourceFile('example.tsx', exampleFunction, ts.ScriptTarget.Latest);
62
- const exports = new TypeScriptParser().getExports(ast);
63
-
64
- const exportClass = exports.find((x) => x.identifier === 'func');
65
-
66
- expect(exportClass?.staticProperties?.get('textProperty')).to.equal('propertyValue');
67
- });
68
-
69
- it('should include staticProperties, when on classes', () => {
70
- const ast = ts.createSourceFile('example.tsx', exampleClass, ts.ScriptTarget.Latest);
71
- const exports = new TypeScriptParser().getExports(ast);
72
-
73
- const exportClass = exports.find((x) => x.identifier === 'classy');
74
-
75
- expect(exportClass?.staticProperties?.get('textProperty')).to.equal('propertyValue');
76
- });
77
- });
78
- });
79
-
80
- describe('collectStaticProperties', () => {
81
- const exampleFile = `
82
- export const hello = () => { return 3; }
83
-
84
- hello.text = "is";
85
- hello.count = 3;
86
- hello.nullish = null;
87
- hello.undef = undefined;
88
- hello.disable = false;
89
- hello.enable = true;
90
- hello.complextLiteral = \`what \${hello.text} it?\`;
91
- hello.nonAssignedProperty += 'value';
92
- `;
93
-
94
- it('should parse all primitive values', () => {
95
- const ast = ts.createSourceFile('example.tsx', exampleFile, ts.ScriptTarget.Latest);
96
- const staticProperties = new TypeScriptParser().parseStaticProperties(ast);
97
-
98
- expect(staticProperties).to.exist;
99
-
100
- const exportHello = staticProperties.get('hello');
101
- expect(exportHello).to.exist;
102
-
103
- expect(exportHello?.get('text')).to.equal('is');
104
- expect(exportHello?.get('count')).to.equal(3);
105
- expect(exportHello?.get('nullish')).to.equal(null);
106
- expect(exportHello?.get('undef')).to.equal(undefined);
107
- expect(exportHello?.get('disable')).to.equal(false);
108
- expect(exportHello?.get('enable')).to.equal(true);
109
-
110
- expect(exportHello?.has('complextLiteral')).to.be.false;
111
- });
112
-
113
- it('should skip non primitive values', () => {
114
- const ast = ts.createSourceFile('example.tsx', exampleFile, ts.ScriptTarget.Latest);
115
- const staticProperties = new TypeScriptParser().parseStaticProperties(ast);
116
- const exportHello = staticProperties.get('hello');
117
-
118
- expect(exportHello?.has('complextLiteral')).to.be.false;
119
- });
120
-
121
- it('should skip non assignment statements', () => {
122
- const ast = ts.createSourceFile('example.tsx', exampleFile, ts.ScriptTarget.Latest);
123
- const staticProperties = new TypeScriptParser().parseStaticProperties(ast);
124
- const exportHello = staticProperties.get('hello');
125
-
126
- expect(exportHello?.has('nonAssignedProperty')).to.be.false;
127
- });
128
- });
129
- });
@@ -1,102 +0,0 @@
1
- import { Export, Module, Parser, StaticProperties } from '@teambit/schema';
2
- import { Logger } from '@teambit/logger';
3
- import { readFileSync } from 'fs-extra';
4
- import ts, {
5
- isClassDeclaration,
6
- isFunctionDeclaration,
7
- isVariableStatement,
8
- SourceFile,
9
- VariableStatement,
10
- } from 'typescript';
11
-
12
- export class TypeScriptParser implements Parser {
13
- public extension = /^.*\.(js|jsx|ts|tsx)$/;
14
-
15
- getExports(sourceFile: SourceFile): Export[] {
16
- const staticProperties = this.parseStaticProperties(sourceFile);
17
-
18
- const exports = sourceFile.statements.filter((statement) => {
19
- if (!statement.modifiers) return false;
20
- return statement.modifiers.find((modifier) => {
21
- return modifier.kind === ts.SyntaxKind.ExportKeyword;
22
- });
23
- });
24
-
25
- const exportModels = exports.map((statement) => {
26
- // todo refactor to a registry of variable statements.
27
- if (isVariableStatement(statement)) {
28
- const child = (statement as VariableStatement).declarationList.declarations[0];
29
- const name = (child as any).name.text;
30
- return new Export(name, staticProperties.get(name));
31
- }
32
-
33
- if (isFunctionDeclaration(statement)) {
34
- if (!statement.name) return undefined;
35
- const name = statement.name.text;
36
- return new Export(name, staticProperties.get(name));
37
- }
38
-
39
- if (isClassDeclaration(statement)) {
40
- if (!statement.name) return undefined;
41
- const name = statement.name.text;
42
- return new Export(name, staticProperties.get(name));
43
- }
44
-
45
- return undefined;
46
- });
47
- const withoutEmpty = exportModels.filter((exportModel) => exportModel !== undefined);
48
- // @ts-ignore
49
- return withoutEmpty;
50
- }
51
-
52
- parseModule(modulePath: string) {
53
- const ast = ts.createSourceFile(modulePath, readFileSync(modulePath, 'utf8'), ts.ScriptTarget.Latest);
54
-
55
- const moduleExports = this.getExports(ast);
56
-
57
- return new Module(moduleExports);
58
- }
59
-
60
- parseStaticProperties(sourceFile: SourceFile) {
61
- // TODO - should we also parse staticProperties inside classes / objects?
62
-
63
- const exportStaticProperties = new Map<string, StaticProperties>();
64
-
65
- sourceFile.statements.forEach((statement) => {
66
- try {
67
- if (!ts.isExpressionStatement(statement)) return;
68
- if (!ts.isBinaryExpression(statement.expression)) return;
69
- if (statement.expression.operatorToken.kind !== ts.SyntaxKind.EqualsToken) return;
70
- if (!ts.isPropertyAccessExpression(statement.expression.left)) return;
71
- if (!ts.isIdentifier(statement.expression.left.expression)) return;
72
-
73
- const targetName = statement.expression.left.expression.text;
74
- const propertyName = statement.expression.left.name.text;
75
-
76
- if (!exportStaticProperties.has(targetName)) exportStaticProperties.set(targetName, new Map());
77
-
78
- const existingProperties = exportStaticProperties.get(targetName);
79
-
80
- if (ts.isStringLiteral(statement.expression.right)) {
81
- existingProperties?.set(propertyName, statement.expression.right.text);
82
- } else if (ts.isNumericLiteral(statement.expression.right)) {
83
- existingProperties?.set(propertyName, +statement.expression.right.text);
84
- } else if (statement.expression.right.kind === ts.SyntaxKind.UndefinedKeyword) {
85
- existingProperties?.set(propertyName, undefined);
86
- } else if (statement.expression.right.kind === ts.SyntaxKind.NullKeyword) {
87
- existingProperties?.set(propertyName, null);
88
- } else if (statement.expression.right.kind === ts.SyntaxKind.TrueKeyword) {
89
- existingProperties?.set(propertyName, true);
90
- } else if (statement.expression.right.kind === ts.SyntaxKind.FalseKeyword) {
91
- existingProperties?.set(propertyName, false);
92
- }
93
- } catch (err) {
94
- this.logger?.error('failed parsing static properties', err);
95
- }
96
- });
97
-
98
- return exportStaticProperties;
99
- }
100
-
101
- constructor(private logger?: Logger | undefined) {}
102
- }