@teambit/typescript 0.0.1075 → 0.0.1077

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.
@@ -1,5 +1,5 @@
1
- import * as compositions_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.typescript_typescript@0.0.1075/dist/typescript.composition.js';
2
- import * as overview_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.typescript_typescript@0.0.1075/dist/typescript.docs.mdx';
1
+ import * as compositions_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.typescript_typescript@0.0.1077/dist/typescript.composition.js';
2
+ import * as overview_0 from '/home/circleci/Library/Caches/Bit/capsules/8891be5ad3d35bfc38b9cd90c0e05b598a5a55af/teambit.typescript_typescript@0.0.1077/dist/typescript.docs.mdx';
3
3
 
4
4
  export const compositions = [compositions_0];
5
5
  export const overview = [overview_0];
@@ -0,0 +1,8 @@
1
+ import { BuildContext, BuildTask, BuiltTaskResult } from '@teambit/builder';
2
+ export declare class RemoveTypesTask implements BuildTask {
3
+ readonly aspectId: string;
4
+ readonly name = "RemoveTypesProp";
5
+ readonly description = "remove the types prop from package.json";
6
+ execute(context: BuildContext): Promise<BuiltTaskResult>;
7
+ private removeTypesFromPkgJson;
8
+ }
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ require("core-js/modules/es.array.iterator.js");
5
+ require("core-js/modules/es.promise.js");
6
+ Object.defineProperty(exports, "__esModule", {
7
+ value: true
8
+ });
9
+ exports.RemoveTypesTask = void 0;
10
+ function _defineProperty2() {
11
+ const data = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
12
+ _defineProperty2 = function () {
13
+ return data;
14
+ };
15
+ return data;
16
+ }
17
+ function _packageJsonFile() {
18
+ const data = _interopRequireDefault(require("@teambit/legacy/dist/consumer/component/package-json-file"));
19
+ _packageJsonFile = function () {
20
+ return data;
21
+ };
22
+ return data;
23
+ }
24
+ function _typescript() {
25
+ const data = require("./typescript.aspect");
26
+ _typescript = function () {
27
+ return data;
28
+ };
29
+ return data;
30
+ }
31
+ class RemoveTypesTask {
32
+ constructor() {
33
+ (0, _defineProperty2().default)(this, "aspectId", _typescript().TypescriptAspect.id);
34
+ (0, _defineProperty2().default)(this, "name", 'RemoveTypesProp');
35
+ (0, _defineProperty2().default)(this, "description", 'remove the types prop from package.json');
36
+ }
37
+ async execute(context) {
38
+ await this.removeTypesFromPkgJson(context.capsuleNetwork);
39
+ const result = {
40
+ componentsResults: []
41
+ };
42
+ return result;
43
+ }
44
+ async removeTypesFromPkgJson(capsuleNetwork) {
45
+ await Promise.all(capsuleNetwork.seedersCapsules.map(async capsule => {
46
+ const packageJson = _packageJsonFile().default.loadFromCapsuleSync(capsule.path);
47
+ // the types['index.ts'] is needed only during the build to avoid errors when tsc finds the
48
+ // same type once in the d.ts and once in the ts file.
49
+ // the reason for `packageJson.packageJsonObject.main` is that .d.ts components don't have a main file and they do need the types prop
50
+ if (packageJson.packageJsonObject.types && packageJson.packageJsonObject.main) {
51
+ delete packageJson.packageJsonObject.types;
52
+ await packageJson.write();
53
+ }
54
+ }));
55
+ }
56
+ }
57
+ exports.RemoveTypesTask = RemoveTypesTask;
58
+
59
+ //# sourceMappingURL=remove-types-task.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["RemoveTypesTask","TypescriptAspect","id","execute","context","removeTypesFromPkgJson","capsuleNetwork","result","componentsResults","Promise","all","seedersCapsules","map","capsule","packageJson","PackageJsonFile","loadFromCapsuleSync","path","packageJsonObject","types","main","write"],"sources":["remove-types-task.ts"],"sourcesContent":["import PackageJsonFile from '@teambit/legacy/dist/consumer/component/package-json-file';\nimport { Network } from '@teambit/isolator';\nimport { BuildContext, BuildTask, BuiltTaskResult } from '@teambit/builder';\nimport { TypescriptAspect } from './typescript.aspect';\n\nexport class RemoveTypesTask implements BuildTask {\n readonly aspectId = TypescriptAspect.id;\n readonly name = 'RemoveTypesProp';\n readonly description = 'remove the types prop from package.json';\n async execute(context: BuildContext): Promise<BuiltTaskResult> {\n await this.removeTypesFromPkgJson(context.capsuleNetwork);\n\n const result = {\n componentsResults: [],\n };\n\n return result;\n }\n private async removeTypesFromPkgJson(capsuleNetwork: Network) {\n await Promise.all(\n 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 // the reason for `packageJson.packageJsonObject.main` is that .d.ts components don't have a main file and they do need the types prop\n if (packageJson.packageJsonObject.types && packageJson.packageJsonObject.main) {\n delete packageJson.packageJsonObject.types;\n await packageJson.write();\n }\n })\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAGA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAEO,MAAMA,eAAe,CAAsB;EAAA;IAAA,kDAC5BC,8BAAgB,CAACC,EAAE;IAAA,8CACvB,iBAAiB;IAAA,qDACV,yCAAyC;EAAA;EAChE,MAAMC,OAAO,CAACC,OAAqB,EAA4B;IAC7D,MAAM,IAAI,CAACC,sBAAsB,CAACD,OAAO,CAACE,cAAc,CAAC;IAEzD,MAAMC,MAAM,GAAG;MACbC,iBAAiB,EAAE;IACrB,CAAC;IAED,OAAOD,MAAM;EACf;EACA,MAAcF,sBAAsB,CAACC,cAAuB,EAAE;IAC5D,MAAMG,OAAO,CAACC,GAAG,CACfJ,cAAc,CAACK,eAAe,CAACC,GAAG,CAAC,MAAOC,OAAO,IAAK;MACpD,MAAMC,WAAW,GAAGC,0BAAe,CAACC,mBAAmB,CAACH,OAAO,CAACI,IAAI,CAAC;MACrE;MACA;MACA;MACA,IAAIH,WAAW,CAACI,iBAAiB,CAACC,KAAK,IAAIL,WAAW,CAACI,iBAAiB,CAACE,IAAI,EAAE;QAC7E,OAAON,WAAW,CAACI,iBAAiB,CAACC,KAAK;QAC1C,MAAML,WAAW,CAACO,KAAK,EAAE;MAC3B;IACF,CAAC,CAAC,CACH;EACH;AACF;AAAC"}
@@ -197,10 +197,10 @@ class SchemaExtractorContext {
197
197
  */
198
198
  getLocation(node, targetSourceFile, absolutePath = false) {
199
199
  const sourceFile = targetSourceFile || node.getSourceFile();
200
+ const filePath = absolutePath ? sourceFile.fileName : this.getPathRelativeToComponent(sourceFile.fileName);
200
201
  const position = sourceFile.getLineAndCharacterOfPosition(node.getStart());
201
202
  const line = position.line + 1;
202
203
  const character = position.character + 1;
203
- const filePath = absolutePath ? sourceFile.fileName : this.getPathRelativeToComponent(sourceFile.fileName);
204
204
  return {
205
205
  filePath: (0, _utils().pathNormalizeToLinux)(filePath),
206
206
  line,
@@ -262,26 +262,24 @@ class SchemaExtractorContext {
262
262
  }
263
263
  visitTypeDefinition() {}
264
264
  findFileInComponent(filePath) {
265
- const filePathToCompare = (0, _utils().pathNormalizeToLinux)(filePath);
266
- const fileNameToCompare = (0, _path().basename)(filePathToCompare); // Get the filename from the filePath
267
-
265
+ const normalizedFilePath = (0, _utils().pathNormalizeToLinux)(filePath);
266
+ const fileNameToCompare = (0, _path().basename)(normalizedFilePath);
267
+ const pathWithoutExtension = fileNameToCompare.replace(/\.[^/.]+$/, '');
268
+ const possibleFormats = new Set(['ts', 'tsx', 'js', 'jsx']);
268
269
  const matchingFile = this.component.filesystem.files.find(file => {
269
270
  const currentFilePath = (0, _utils().pathNormalizeToLinux)(file.path);
270
- const currentFileName = (0, _path().basename)(currentFilePath); // Get the filename from the current file path
271
-
272
- // TODO: fix this line to support further extensions.
273
- if (currentFileName === fileNameToCompare || currentFilePath.includes(fileNameToCompare)) {
274
- const strings = ['ts', 'tsx', 'js', 'jsx'].map(format => {
275
- if (fileNameToCompare.endsWith(`.${format}`)) return fileNameToCompare;
276
- return `${fileNameToCompare}.${format}`;
277
- });
278
- const matchesWithExtension = !!strings.find(string => string === currentFileName);
279
- // check if it is an index file export
280
- const matchesIndexFile = !matchesWithExtension && ['ts', 'js'].some(format => {
281
- const indexFilePath = (0, _path().join)(filePathToCompare, `index.${format}`);
282
- return (0, _utils().pathNormalizeToLinux)(indexFilePath) === currentFilePath;
283
- });
284
- return matchesWithExtension || matchesIndexFile;
271
+ const currentFileName = (0, _path().basename)(currentFilePath);
272
+ const currentFileExtension = (0, _path().extname)(currentFilePath).substring(1);
273
+ const isSameBaseName = pathWithoutExtension === (0, _path().basename)(currentFileName, `.${currentFileExtension}`);
274
+ const isValidExtension = possibleFormats.has(currentFileExtension);
275
+ if (isSameBaseName && isValidExtension) {
276
+ return true;
277
+ }
278
+ if (['ts', 'js'].some(format => {
279
+ const indexFilePath = (0, _path().join)(normalizedFilePath, `index.${format}`);
280
+ return (0, _utils().pathNormalizeToLinux)(indexFilePath) === currentFilePath;
281
+ })) {
282
+ return true;
285
283
  }
286
284
  return false;
287
285
  });
@@ -1 +1 @@
1
- {"version":3,"names":["SchemaExtractorContext","mainFile","pathNormalizeToLinux","getPathRelativeToComponent","component","path","identifiers","_identifiers","internalIdentifiers","_internalIdentifiers","computed","_computed","mainFileIdentifierKey","getIdentifierKey","mainModuleIdentifiers","get","constructor","tsserver","extractor","componentDeps","formatter","Map","getComputedNodeKey","filePath","line","character","getIdentifierKeyForNode","node","getSourceFile","fileName","setComputed","location","key","set","setIdentifiers","setInternalIdentifiers","existing","uniqueIdentifiers","uniqBy","concat","k","aliasId","id","IdentifierList","computeSchema","getLocation","existingComputedSchema","computedSchema","targetSourceFile","absolutePath","sourceFile","position","getLineAndCharacterOfPosition","getStart","getLocationAsString","basePath","filesystem","files","base","relative","getSignature","getSignatureHelp","getPath","getPosition","offset","getPositionOfLineAndCharacter","getQuickInfo","err","message","Error","getQuickInfoDisplayString","quickInfo","body","displayString","typeDefinition","getTypeDefinition","visitTypeDefinition","findFileInComponent","filePathToCompare","fileNameToCompare","basename","matchingFile","find","file","currentFilePath","currentFileName","includes","strings","map","format","endsWith","matchesWithExtension","string","matchesIndexFile","some","indexFilePath","join","parsePackageNameFromPath","parts","split","length","lastPart","replace","sep","pkgParts","startsWith","pkgName","getSourceFileInsideComponent","parseSourceFile","getSourceFileFromNode","getFilePathByNode","undefined","def","getDefinition","firstDef","head","definitionInfo","definition","startPosition","start","pos","nodeAtPos","getTokenAtPosition","visitDefinition","getTypeRefForExternalNode","visit","parent","kind","SyntaxKind","Identifier","SourceFile","references","isExported","isFromComponent","getFileIdentifiers","exportDec","specifierPathStr","ExportDeclaration","moduleSpecifier","getText","specifierPath","substring","absPath","resolve","getIdentifiers","getFileExports","filter","identifier","ExportIdentifier","isExportIdentifier","getFileInternals","computeIdentifiers","headTypeDefinition","unknownExactType","typeStr","isTypeStrFromQuickInfo","InferenceTypeSchema","info","type","parseTypeFromQuickInfo","isDefInSameLocation","loc","resolveType","internalRef","getTypeRef","ts","isTypeNode","getTypeRefForExternalPath","definitionNode","definitionNodeName","definitionInternalRef","transformer","getTransformer","schemaNode","getCompIdByPkgName","dep","packageName","componentId","nodeIdentifierKey","nodeIdentifierList","mainIdentifierList","nodeIdentifier","mainIdentifier","parsedNodeIdentifier","parsedMainIdentifier","isExportedFromMain","resolveTypeRef","sourceFilePath","TypeRefSchema","isRelativeImport","compIdByPkg","compIdByPath","getComponentIDByPath","relativeDir","lastIndexOf","absFilePath","compFilePath","idKey","exportedIdentifier","i","jsDocToDocSchema","canHaveJsDoc","jsDocs","getJsDoc","jsDoc","comment","getTextOfJSDocComment","tags","pMapSeries","tag","tagParser","DocSchema"],"sources":["schema-extractor-context.ts"],"sourcesContent":["import { TsserverClient } from '@teambit/ts-server';\nimport { getTokenAtPosition, canHaveJsDoc, getJsDoc } from 'tsutils';\nimport ts, { ExportAssignment, getTextOfJSDocComment, ExportDeclaration, Node, SyntaxKind, TypeNode } from 'typescript';\nimport { head, uniqBy } from 'lodash';\n// @ts-ignore david we should figure fix this.\n// eslint-disable-next-line import/no-unresolved\nimport protocol from 'typescript/lib/protocol';\nimport { pathNormalizeToLinux } from '@teambit/legacy/dist/utils';\nimport { resolve, sep, relative, basename, join } from 'path';\nimport { Component, ComponentID } from '@teambit/component';\nimport {\n TypeRefSchema,\n SchemaNode,\n InferenceTypeSchema,\n Location,\n DocSchema,\n} from '@teambit/semantics.entities.semantic-schema';\nimport isRelativeImport from '@teambit/legacy/dist/utils/is-relative-import';\nimport { ComponentDependency } from '@teambit/dependency-resolver';\nimport { Formatter } from '@teambit/formatter';\nimport pMapSeries from 'p-map-series';\nimport { TypeScriptExtractor } from './typescript.extractor';\nimport { IdentifierList } from './identifier-list';\nimport { parseTypeFromQuickInfo } from './transformers/utils/parse-type-from-quick-info';\nimport { tagParser } from './transformers/utils/jsdoc-to-doc-schema';\nimport { Identifier } from './identifier';\nimport { ExportIdentifier } from './export-identifier';\n\nexport class SchemaExtractorContext {\n /**\n * list of all declared identifiers (exported and internal) by filename\n */\n private _identifiers = new Map<string, IdentifierList>();\n private _internalIdentifiers = new Map<string, IdentifierList>();\n\n /**\n * computed nodes by filename and (position (line:character))\n */\n private _computed = new Map<string, SchemaNode>();\n\n get mainFile() {\n return pathNormalizeToLinux(this.getPathRelativeToComponent(this.component.mainFile.path));\n }\n\n get identifiers() {\n return this._identifiers;\n }\n\n get internalIdentifiers() {\n return this._internalIdentifiers;\n }\n\n get computed() {\n return this._computed;\n }\n\n get mainFileIdentifierKey() {\n const mainFile = this.component.mainFile;\n return this.getIdentifierKey(mainFile.path);\n }\n\n get mainModuleIdentifiers() {\n return this.identifiers.get(this.mainFileIdentifierKey);\n }\n\n constructor(\n readonly tsserver: TsserverClient,\n readonly component: Component,\n readonly extractor: TypeScriptExtractor,\n readonly componentDeps: ComponentDependency[],\n readonly formatter?: Formatter\n ) {}\n\n getComputedNodeKey({ filePath, line, character }: Location) {\n return `${filePath}:${line}:${character}`;\n }\n\n getIdentifierKeyForNode(node: Node) {\n const filePath = node.getSourceFile().fileName;\n return this.getIdentifierKey(filePath);\n }\n\n getIdentifierKey(filePath: string) {\n return pathNormalizeToLinux(filePath);\n }\n\n setComputed(node: SchemaNode) {\n const { location } = node;\n const key = this.getComputedNodeKey(location);\n this.computed.set(key, node);\n }\n\n setIdentifiers(filePath: string, identifiers: IdentifierList) {\n this._identifiers.set(this.getIdentifierKey(filePath), identifiers);\n }\n\n setInternalIdentifiers(filePath: string, identifiers: IdentifierList) {\n const existing = this._internalIdentifiers.get(filePath);\n if (!existing) {\n this._internalIdentifiers.set(filePath, identifiers);\n } else {\n const uniqueIdentifiers = uniqBy(existing.identifiers.concat(identifiers.identifiers), (k) => k.aliasId || k.id);\n this._internalIdentifiers.set(filePath, new IdentifierList(uniqueIdentifiers));\n }\n }\n\n async computeSchema(node: Node) {\n const location = this.getLocation(node);\n const key = this.getComputedNodeKey(location);\n const existingComputedSchema = this.computed.get(key);\n if (existingComputedSchema) {\n return existingComputedSchema;\n }\n\n const computedSchema = await this.extractor.computeSchema(node, this);\n this.setComputed(computedSchema);\n return computedSchema;\n }\n\n /**\n * returns the location of a node in a source file.\n */\n getLocation(node: Node, targetSourceFile?: ts.SourceFile, absolutePath = false): Location {\n const sourceFile = targetSourceFile || node.getSourceFile();\n const position = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n const line = position.line + 1;\n const character = position.character + 1;\n const filePath = absolutePath ? sourceFile.fileName : this.getPathRelativeToComponent(sourceFile.fileName);\n\n return {\n filePath: pathNormalizeToLinux(filePath),\n line,\n character,\n };\n }\n\n getLocationAsString(node: Node): string {\n const location = this.getLocation(node);\n return `${node.getSourceFile().fileName}, line: ${location.line}, character: ${location.character}`;\n }\n\n getPathRelativeToComponent(filePath: string): string {\n const basePath = this.component.filesystem.files[0].base;\n return relative(basePath, filePath);\n }\n\n /**\n * returns a signature for a node.\n */\n async getSignature(node: Node) {\n return this.tsserver.getSignatureHelp(this.getPath(node), this.getLocation(node));\n }\n\n /**\n * get the position for the tsserver.\n */\n getPosition(sourceFile: ts.SourceFile, line: number, offset: number): number {\n return sourceFile.getPositionOfLineAndCharacter(line - 1, offset - 1);\n }\n\n /**\n * get the path for a source file.\n */\n getPath(node: Node) {\n const sourceFile = node.getSourceFile();\n return sourceFile.fileName;\n }\n\n async getQuickInfo(node: Node) {\n const location = this.getLocation(node);\n try {\n return await this.tsserver.getQuickInfo(this.getPath(node), location);\n } catch (err: any) {\n if (err.message === 'No content available.') {\n throw new Error(\n `unable to get quickinfo data from tsserver at ${this.getPath(node)}, Ln ${location.line}, Col ${\n location.character\n }`\n );\n }\n throw err;\n }\n }\n\n async getQuickInfoDisplayString(node: Node): Promise<string> {\n const quickInfo = await this.getQuickInfo(node);\n return quickInfo?.body?.displayString || '';\n }\n\n /**\n * returns the type definition for a type.\n */\n typeDefinition(node: Node) {\n return this.tsserver.getTypeDefinition(this.getPath(node), this.getLocation(node));\n }\n\n visitTypeDefinition() {}\n\n findFileInComponent(filePath: string) {\n const filePathToCompare = pathNormalizeToLinux(filePath);\n const fileNameToCompare = basename(filePathToCompare); // Get the filename from the filePath\n\n const matchingFile = this.component.filesystem.files.find((file) => {\n const currentFilePath = pathNormalizeToLinux(file.path);\n const currentFileName = basename(currentFilePath); // Get the filename from the current file path\n\n // TODO: fix this line to support further extensions.\n if (currentFileName === fileNameToCompare || currentFilePath.includes(fileNameToCompare)) {\n const strings = ['ts', 'tsx', 'js', 'jsx'].map((format) => {\n if (fileNameToCompare.endsWith(`.${format}`)) return fileNameToCompare;\n\n return `${fileNameToCompare}.${format}`;\n });\n\n const matchesWithExtension = !!strings.find((string) => string === currentFileName);\n // check if it is an index file export\n const matchesIndexFile =\n !matchesWithExtension &&\n ['ts', 'js'].some((format) => {\n const indexFilePath = join(filePathToCompare, `index.${format}`);\n return pathNormalizeToLinux(indexFilePath) === currentFilePath;\n });\n\n return matchesWithExtension || matchesIndexFile;\n }\n\n return false;\n });\n\n return matchingFile;\n }\n\n private parsePackageNameFromPath(path: string) {\n const parts = path.split('node_modules');\n\n if (parts.length === 1) {\n return path;\n }\n\n const lastPart = parts[parts.length - 1].replace(sep, '');\n const pkgParts = lastPart.split('/');\n if (lastPart.startsWith('@')) {\n // scoped package\n return `${pkgParts[0]}/${pkgParts[1]}`;\n }\n const pkgName = pkgParts[0];\n if (pkgName === 'typescript') {\n // it's a built-in type, such as \"string\".\n return '';\n }\n return pkgName;\n }\n\n /**\n * return the file if part of the component.\n * otherwise, a reference to the target package and the type name.\n */\n getSourceFileInsideComponent(filePath: string) {\n const file = this.findFileInComponent(filePath);\n return file && this.extractor.parseSourceFile(file);\n }\n\n async getSourceFileFromNode(node: Node) {\n const filePath = await this.getFilePathByNode(node);\n if (!filePath) {\n return undefined;\n }\n return this.getSourceFileInsideComponent(filePath);\n }\n\n async getFilePathByNode(node: Node) {\n const def = await this.tsserver.getDefinition(this.getPath(node), this.getLocation(node));\n\n const firstDef = head(def?.body);\n return firstDef?.file;\n }\n\n async definitionInfo(node: Node): Promise<protocol.DefinitionInfo | undefined> {\n const location = this.getLocation(node);\n const filePath = this.getPath(node);\n\n const def = await this.tsserver.getDefinition(filePath, location);\n\n const firstDef = head(def?.body);\n\n return firstDef;\n }\n\n /**\n * get a definition for a given node.\n */\n async definition(definition: protocol.DefinitionInfo): Promise<Node | undefined> {\n const startPosition = definition.start;\n const sourceFile = this.getSourceFileInsideComponent(definition.file);\n if (!sourceFile) {\n // it might be an external reference, cant get the node\n return undefined;\n }\n const pos = this.getPosition(sourceFile, startPosition.line, startPosition.offset);\n const nodeAtPos = getTokenAtPosition(sourceFile, pos);\n return nodeAtPos;\n }\n\n /**\n * visit a definition for node - e.g. return it's schema.\n */\n async visitDefinition(node: Node): Promise<SchemaNode | undefined> {\n const definitionInfo = await this.definitionInfo(node);\n if (!definitionInfo) {\n return undefined;\n }\n\n const definition = await this.definition(definitionInfo);\n if (!definition) {\n return this.getTypeRefForExternalNode(node);\n }\n\n return this.visit(definition.parent);\n }\n\n async visit(node: Node): Promise<SchemaNode> {\n if (node.kind === SyntaxKind.Identifier && node.parent.parent.kind !== SyntaxKind.SourceFile) {\n return this.visit(node.parent);\n }\n return this.extractor.computeSchema(node, this);\n }\n\n references() {}\n\n isExported() {}\n\n isFromComponent() {}\n\n async getFileIdentifiers(exportDec: ExportDeclaration | ExportAssignment) {\n const file = exportDec.getSourceFile().fileName;\n const specifierPathStr =\n (exportDec.kind === SyntaxKind.ExportDeclaration && exportDec.moduleSpecifier?.getText()) || '';\n const specifierPath = specifierPathStr.substring(1, specifierPathStr.length - 1);\n const absPath = resolve(file, '..', specifierPath);\n const sourceFile = this.getSourceFileInsideComponent(absPath);\n if (!sourceFile) return [];\n return this.getIdentifiers(sourceFile);\n }\n\n async getFileExports(exportDec: ExportDeclaration | ExportAssignment) {\n const identifiers = await this.getFileIdentifiers(exportDec);\n return identifiers.filter((identifier) => ExportIdentifier.isExportIdentifier(identifier));\n }\n\n async getFileInternals(exportDec: ExportDeclaration | ExportAssignment) {\n const identifiers = await this.getFileIdentifiers(exportDec);\n return identifiers.filter((identifier) => !ExportIdentifier.isExportIdentifier(identifier));\n }\n\n getIdentifiers(node: Node) {\n return this.extractor.computeIdentifiers(node, this);\n }\n\n /**\n * tsserver has two different calls: \"definition\" and \"typeDefinition\".\n * normally, we need the \"typeDefinition\" to get the type data of a node.\n * sometimes, it has no data, for example when the node is of type TypeReference, and then using \"definition\" is\n * helpful. (couldn't find a rule when to use each one. e.g. \"VariableDeclaration\" sometimes has data only in\n * \"definition\" but it's not clear when/why).\n */\n async getDefinition(node: Node) {\n const typeDefinition = await this.typeDefinition(node);\n const headTypeDefinition = head(typeDefinition?.body);\n if (headTypeDefinition) {\n return headTypeDefinition;\n }\n const definition = await this.tsserver.getDefinition(node.getSourceFile().fileName, this.getLocation(node));\n return head(definition?.body);\n }\n\n // when we can't figure out the component/package/type of this node, we'll use the typeStr as the type.\n private async unknownExactType(node: Node, location: Location, typeStr = 'any', isTypeStrFromQuickInfo = true) {\n if (isTypeStrFromQuickInfo) {\n return new InferenceTypeSchema(location, typeStr || 'any');\n }\n const info = await this.getQuickInfo(node);\n const type = parseTypeFromQuickInfo(info);\n return new InferenceTypeSchema(location, type, typeStr);\n }\n\n // the reason for this check is to avoid infinite loop when calling `this.jump` with the same file+location\n private isDefInSameLocation(node: Node, definition: protocol.FileSpanWithContext) {\n if (definition.file !== node.getSourceFile().fileName) {\n return false;\n }\n const loc = this.getLocation(node);\n\n return loc.line === definition.start.line && loc.character === definition.start.offset;\n }\n\n /**\n * resolve a type by a node and its identifier.\n */\n async resolveType(\n node: Node & { type?: TypeNode },\n typeStr: string,\n isTypeStrFromQuickInfo = true\n ): Promise<SchemaNode> {\n const location = this.getLocation(node);\n\n // check if internal ref with typeInfo\n const internalRef = await this.getTypeRef(typeStr, this.getIdentifierKeyForNode(node), location);\n\n if (internalRef) return internalRef;\n\n // if a node has \"type\" prop, it has the type data of the node. this normally happens when the code has the type\n // explicitly, e.g. `const str: string` vs implicitly `const str = 'some-string'`, which the node won't have \"type\"\n if (node.type && ts.isTypeNode(node.type)) {\n return this.computeSchema(node.type);\n }\n\n const definition = await this.getDefinition(node);\n if (!definition) {\n return this.unknownExactType(node, location, typeStr, isTypeStrFromQuickInfo);\n }\n\n const file = this.findFileInComponent(definition.file);\n\n if (!file) return this.getTypeRefForExternalPath(typeStr, definition.file, location);\n\n if (this.isDefInSameLocation(node, definition)) {\n return this.unknownExactType(node, location, typeStr, isTypeStrFromQuickInfo);\n }\n\n const definitionNode = await this.definition(definition);\n\n if (!definitionNode) {\n return this.unknownExactType(node, location, typeStr, isTypeStrFromQuickInfo);\n }\n\n const definitionNodeName = definitionNode?.getText();\n\n // check if internal ref with definition info\n const definitionInternalRef = await this.getTypeRef(\n definitionNodeName,\n this.getIdentifierKeyForNode(definitionNode),\n location\n );\n\n if (definitionInternalRef) return definitionInternalRef;\n\n const transformer = this.extractor.getTransformer(definitionNode, this);\n\n if (transformer === undefined) {\n return this.unknownExactType(node, location, typeStr, isTypeStrFromQuickInfo);\n }\n const schemaNode = await this.visit(definitionNode);\n return schemaNode || this.unknownExactType(node, location, typeStr, isTypeStrFromQuickInfo);\n }\n\n private getCompIdByPkgName(pkgName: string): ComponentID | undefined {\n return this.componentDeps.find((dep) => dep.packageName === pkgName)?.componentId;\n }\n\n async getTypeRef(typeStr: string, filePath: string, location: Location): Promise<TypeRefSchema | undefined> {\n const nodeIdentifierKey = this.getIdentifierKey(filePath);\n const mainFileIdentifierKey = this.mainFileIdentifierKey;\n\n const nodeIdentifierList = this.identifiers.get(nodeIdentifierKey);\n const mainIdentifierList = this.identifiers.get(mainFileIdentifierKey);\n\n const nodeIdentifier = new Identifier(typeStr, nodeIdentifierKey);\n const mainIdentifier = new Identifier(typeStr, mainFileIdentifierKey);\n\n const parsedNodeIdentifier = nodeIdentifierList?.find(nodeIdentifier);\n const parsedMainIdentifier = mainIdentifierList?.find(mainIdentifier);\n const isExportedFromMain = parsedMainIdentifier && ExportIdentifier.isExportIdentifier(parsedMainIdentifier);\n\n if (!parsedNodeIdentifier) return undefined;\n\n const internalRef = !isExportedFromMain;\n\n if (internalRef) {\n this.setInternalIdentifiers(filePath, new IdentifierList([parsedNodeIdentifier]));\n }\n\n return this.resolveTypeRef(parsedNodeIdentifier, location, isExportedFromMain);\n }\n\n async resolveTypeRef(\n identifier: Identifier,\n location: Location,\n isExportedFromMain?: boolean\n ): Promise<TypeRefSchema> {\n const sourceFilePath = identifier.sourceFilePath;\n\n if (!sourceFilePath || isExportedFromMain) {\n return new TypeRefSchema(\n location,\n identifier.id,\n undefined,\n undefined,\n !isExportedFromMain ? this.getPathRelativeToComponent(identifier.filePath) : undefined\n );\n }\n\n if (!isRelativeImport(sourceFilePath)) {\n const pkgName = this.parsePackageNameFromPath(sourceFilePath);\n const compIdByPkg = this.getCompIdByPkgName(pkgName);\n\n const compIdByPath = await this.extractor.getComponentIDByPath(sourceFilePath);\n\n if (compIdByPath) {\n return new TypeRefSchema(location, identifier.id, compIdByPath);\n }\n\n if (compIdByPkg) {\n return new TypeRefSchema(location, identifier.id, compIdByPkg);\n }\n\n // package without comp id\n return new TypeRefSchema(location, identifier.id, undefined, pkgName);\n }\n\n const relativeDir = identifier.filePath.substring(0, identifier.filePath.lastIndexOf('/'));\n const absFilePath = resolve(relativeDir, sourceFilePath);\n const compFilePath = this.findFileInComponent(absFilePath);\n if (!compFilePath) {\n // @todo handle this better\n throw new Error(\n `cannot find file in component \\n absolute path: ${absFilePath}\\n source file path ${sourceFilePath}\\n identifier file path ${identifier.filePath} \\n relative dir ${relativeDir}`\n );\n return new TypeRefSchema(location, identifier.id);\n }\n\n const idKey = this.getIdentifierKey(compFilePath?.path);\n\n // if re exported from a file, recurse until definition\n const exportedIdentifier = (this.identifiers.get(idKey)?.identifiers || []).find((i) => i.id === identifier.id);\n\n if (exportedIdentifier) {\n return this.resolveTypeRef(exportedIdentifier, location, isExportedFromMain);\n }\n\n return new TypeRefSchema(location, identifier.id);\n }\n\n async getTypeRefForExternalNode(node: Node): Promise<TypeRefSchema> {\n const info = await this.getQuickInfo(node);\n const typeStr = parseTypeFromQuickInfo(info);\n const location = this.getLocation(node);\n const filePath = this.getPath(node);\n return this.getTypeRefForExternalPath(typeStr, filePath, location);\n }\n\n async getTypeRefForExternalPath(typeStr: string, filePath: string, location: Location): Promise<TypeRefSchema> {\n const compIdByPath = await this.extractor.getComponentIDByPath(filePath);\n if (compIdByPath) {\n return new TypeRefSchema(location, typeStr, compIdByPath);\n }\n const pkgName = this.parsePackageNameFromPath(filePath);\n const compIdByPkg = this.getCompIdByPkgName(pkgName);\n if (compIdByPkg) {\n return new TypeRefSchema(location, typeStr, compIdByPkg);\n }\n return new TypeRefSchema(location, typeStr, undefined, pkgName);\n }\n\n async jsDocToDocSchema(node: Node): Promise<DocSchema | undefined> {\n if (!canHaveJsDoc(node)) {\n return undefined;\n }\n const jsDocs = getJsDoc(node);\n if (!jsDocs.length) {\n return undefined;\n }\n // not sure how common it is to have multiple JSDocs. never seen it before.\n // regardless, in typescript implementation of methods like `getJSDocDeprecatedTag()`, they use the first one. (`getFirstJSDocTag()`)\n const jsDoc = jsDocs[0];\n const location = this.getLocation(jsDoc);\n const comment = getTextOfJSDocComment(jsDoc.comment);\n const tags = jsDoc.tags ? await pMapSeries(jsDoc.tags, (tag) => tagParser(tag, this, this.formatter)) : undefined;\n return new DocSchema(location, jsDoc.getText(), comment, tags);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAIA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAEA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAOA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAGA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAEA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAAuD;AAAA;AAEhD,MAAMA,sBAAsB,CAAC;EAClC;AACF;AACA;;EAIE;AACF;AACA;;EAGE,IAAIC,QAAQ,GAAG;IACb,OAAO,IAAAC,6BAAoB,EAAC,IAAI,CAACC,0BAA0B,CAAC,IAAI,CAACC,SAAS,CAACH,QAAQ,CAACI,IAAI,CAAC,CAAC;EAC5F;EAEA,IAAIC,WAAW,GAAG;IAChB,OAAO,IAAI,CAACC,YAAY;EAC1B;EAEA,IAAIC,mBAAmB,GAAG;IACxB,OAAO,IAAI,CAACC,oBAAoB;EAClC;EAEA,IAAIC,QAAQ,GAAG;IACb,OAA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U,EAAkC;IACjE,IAAI,CAAC,IAAA8K,uBAAY,EAAC9K,IAAI,CAAC,EAAE;MACvB,OAAOoF,SAAS;IAClB;IACA,MAAM2F,MAAM,GAAG,IAAAC,mBAAQ,EAAChL,IAAI,CAAC;IAC7B,IAAI,CAAC+K,MAAM,CAACtG,MAAM,EAAE;MAClB,OAAOW,SAAS;IAClB;IACA;IACA;IACA,MAAM6F,KAAK,GAAGF,MAAM,CAAC,CAAC,CAAC;IACvB,MAAM3K,QAAQ,GAAG,IAAI,CAACc,WAAW,CAAC+J,KAAK,CAAC;IACxC,MAAMC,OAAO,GAAG,IAAAC,mCAAqB,EAACF,KAAK,CAACC,OAAO,CAAC;IACpD,MAAME,IAAI,GAAGH,KAAK,CAACG,IAAI,GAAG,MAAM,IAAAC,qBAAU,EAACJ,KAAK,CAACG,IAAI,EAAGE,GAAG,IAAK,IAAAC,6BAAS,EAACD,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC7L,SAAS,CAAC,CAAC,GAAG2F,SAAS;IACjH,OAAO,KAAIoG,8BAAS,EAACpL,QAAQ,EAAE6K,KAAK,CAACjE,OAAO,EAAE,EAAEkE,OAAO,EAAEE,IAAI,CAAC;EAChE;AACF;AAAC"}
1
+ {"version":3,"names":["SchemaExtractorContext","mainFile","pathNormalizeToLinux","getPathRelativeToComponent","component","path","identifiers","_identifiers","internalIdentifiers","_internalIdentifiers","computed","_computed","mainFileIdentifierKey","getIdentifierKey","mainModuleIdentifiers","get","constructor","tsserver","extractor","componentDeps","formatter","Map","getComputedNodeKey","filePath","line","character","getIdentifierKeyForNode","node","getSourceFile","fileName","setComputed","location","key","set","setIdentifiers","setInternalIdentifiers","existing","uniqueIdentifiers","uniqBy","concat","k","aliasId","id","IdentifierList","computeSchema","getLocation","existingComputedSchema","computedSchema","targetSourceFile","absolutePath","sourceFile","position","getLineAndCharacterOfPosition","getStart","getLocationAsString","basePath","filesystem","files","base","relative","getSignature","getSignatureHelp","getPath","getPosition","offset","getPositionOfLineAndCharacter","getQuickInfo","err","message","Error","getQuickInfoDisplayString","quickInfo","body","displayString","typeDefinition","getTypeDefinition","visitTypeDefinition","findFileInComponent","normalizedFilePath","fileNameToCompare","basename","pathWithoutExtension","replace","possibleFormats","Set","matchingFile","find","file","currentFilePath","currentFileName","currentFileExtension","extname","substring","isSameBaseName","isValidExtension","has","some","format","indexFilePath","join","parsePackageNameFromPath","parts","split","length","lastPart","sep","pkgParts","startsWith","pkgName","getSourceFileInsideComponent","parseSourceFile","getSourceFileFromNode","getFilePathByNode","undefined","def","getDefinition","firstDef","head","definitionInfo","definition","startPosition","start","pos","nodeAtPos","getTokenAtPosition","visitDefinition","getTypeRefForExternalNode","visit","parent","kind","SyntaxKind","Identifier","SourceFile","references","isExported","isFromComponent","getFileIdentifiers","exportDec","specifierPathStr","ExportDeclaration","moduleSpecifier","getText","specifierPath","absPath","resolve","getIdentifiers","getFileExports","filter","identifier","ExportIdentifier","isExportIdentifier","getFileInternals","computeIdentifiers","headTypeDefinition","unknownExactType","typeStr","isTypeStrFromQuickInfo","InferenceTypeSchema","info","type","parseTypeFromQuickInfo","isDefInSameLocation","loc","resolveType","internalRef","getTypeRef","ts","isTypeNode","getTypeRefForExternalPath","definitionNode","definitionNodeName","definitionInternalRef","transformer","getTransformer","schemaNode","getCompIdByPkgName","dep","packageName","componentId","nodeIdentifierKey","nodeIdentifierList","mainIdentifierList","nodeIdentifier","mainIdentifier","parsedNodeIdentifier","parsedMainIdentifier","isExportedFromMain","resolveTypeRef","sourceFilePath","TypeRefSchema","isRelativeImport","compIdByPkg","compIdByPath","getComponentIDByPath","relativeDir","lastIndexOf","absFilePath","compFilePath","idKey","exportedIdentifier","i","jsDocToDocSchema","canHaveJsDoc","jsDocs","getJsDoc","jsDoc","comment","getTextOfJSDocComment","tags","pMapSeries","tag","tagParser","DocSchema"],"sources":["schema-extractor-context.ts"],"sourcesContent":["import { TsserverClient } from '@teambit/ts-server';\nimport { getTokenAtPosition, canHaveJsDoc, getJsDoc } from 'tsutils';\nimport ts, { ExportAssignment, getTextOfJSDocComment, ExportDeclaration, Node, SyntaxKind, TypeNode } from 'typescript';\nimport { head, uniqBy } from 'lodash';\n// @ts-ignore david we should figure fix this.\n// eslint-disable-next-line import/no-unresolved\nimport protocol from 'typescript/lib/protocol';\nimport { pathNormalizeToLinux } from '@teambit/legacy/dist/utils';\nimport { resolve, sep, relative, basename, join, extname } from 'path';\nimport { Component, ComponentID } from '@teambit/component';\nimport {\n TypeRefSchema,\n SchemaNode,\n InferenceTypeSchema,\n Location,\n DocSchema,\n} from '@teambit/semantics.entities.semantic-schema';\nimport isRelativeImport from '@teambit/legacy/dist/utils/is-relative-import';\nimport { ComponentDependency } from '@teambit/dependency-resolver';\nimport { Formatter } from '@teambit/formatter';\nimport pMapSeries from 'p-map-series';\nimport { TypeScriptExtractor } from './typescript.extractor';\nimport { IdentifierList } from './identifier-list';\nimport { parseTypeFromQuickInfo } from './transformers/utils/parse-type-from-quick-info';\nimport { tagParser } from './transformers/utils/jsdoc-to-doc-schema';\nimport { Identifier } from './identifier';\nimport { ExportIdentifier } from './export-identifier';\n\nexport class SchemaExtractorContext {\n /**\n * list of all declared identifiers (exported and internal) by filename\n */\n private _identifiers = new Map<string, IdentifierList>();\n private _internalIdentifiers = new Map<string, IdentifierList>();\n\n /**\n * computed nodes by filename and (position (line:character))\n */\n private _computed = new Map<string, SchemaNode>();\n\n get mainFile() {\n return pathNormalizeToLinux(this.getPathRelativeToComponent(this.component.mainFile.path));\n }\n\n get identifiers() {\n return this._identifiers;\n }\n\n get internalIdentifiers() {\n return this._internalIdentifiers;\n }\n\n get computed() {\n return this._computed;\n }\n\n get mainFileIdentifierKey() {\n const mainFile = this.component.mainFile;\n return this.getIdentifierKey(mainFile.path);\n }\n\n get mainModuleIdentifiers() {\n return this.identifiers.get(this.mainFileIdentifierKey);\n }\n\n constructor(\n readonly tsserver: TsserverClient,\n readonly component: Component,\n readonly extractor: TypeScriptExtractor,\n readonly componentDeps: ComponentDependency[],\n readonly formatter?: Formatter\n ) {}\n\n getComputedNodeKey({ filePath, line, character }: Location) {\n return `${filePath}:${line}:${character}`;\n }\n\n getIdentifierKeyForNode(node: Node) {\n const filePath = node.getSourceFile().fileName;\n return this.getIdentifierKey(filePath);\n }\n\n getIdentifierKey(filePath: string) {\n return pathNormalizeToLinux(filePath);\n }\n\n setComputed(node: SchemaNode) {\n const { location } = node;\n const key = this.getComputedNodeKey(location);\n this.computed.set(key, node);\n }\n\n setIdentifiers(filePath: string, identifiers: IdentifierList) {\n this._identifiers.set(this.getIdentifierKey(filePath), identifiers);\n }\n\n setInternalIdentifiers(filePath: string, identifiers: IdentifierList) {\n const existing = this._internalIdentifiers.get(filePath);\n if (!existing) {\n this._internalIdentifiers.set(filePath, identifiers);\n } else {\n const uniqueIdentifiers = uniqBy(existing.identifiers.concat(identifiers.identifiers), (k) => k.aliasId || k.id);\n this._internalIdentifiers.set(filePath, new IdentifierList(uniqueIdentifiers));\n }\n }\n\n async computeSchema(node: Node) {\n const location = this.getLocation(node);\n const key = this.getComputedNodeKey(location);\n const existingComputedSchema = this.computed.get(key);\n if (existingComputedSchema) {\n return existingComputedSchema;\n }\n\n const computedSchema = await this.extractor.computeSchema(node, this);\n this.setComputed(computedSchema);\n return computedSchema;\n }\n\n /**\n * returns the location of a node in a source file.\n */\n getLocation(node: Node, targetSourceFile?: ts.SourceFile, absolutePath = false): Location {\n const sourceFile = targetSourceFile || node.getSourceFile();\n const filePath = absolutePath ? sourceFile.fileName : this.getPathRelativeToComponent(sourceFile.fileName);\n const position = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n const line = position.line + 1;\n const character = position.character + 1;\n\n return {\n filePath: pathNormalizeToLinux(filePath),\n line,\n character,\n };\n }\n\n getLocationAsString(node: Node): string {\n const location = this.getLocation(node);\n return `${node.getSourceFile().fileName}, line: ${location.line}, character: ${location.character}`;\n }\n\n getPathRelativeToComponent(filePath: string): string {\n const basePath = this.component.filesystem.files[0].base;\n return relative(basePath, filePath);\n }\n\n /**\n * returns a signature for a node.\n */\n async getSignature(node: Node) {\n return this.tsserver.getSignatureHelp(this.getPath(node), this.getLocation(node));\n }\n\n /**\n * get the position for the tsserver.\n */\n getPosition(sourceFile: ts.SourceFile, line: number, offset: number): number {\n return sourceFile.getPositionOfLineAndCharacter(line - 1, offset - 1);\n }\n\n /**\n * get the path for a source file.\n */\n getPath(node: Node) {\n const sourceFile = node.getSourceFile();\n return sourceFile.fileName;\n }\n\n async getQuickInfo(node: Node) {\n const location = this.getLocation(node);\n try {\n return await this.tsserver.getQuickInfo(this.getPath(node), location);\n } catch (err: any) {\n if (err.message === 'No content available.') {\n throw new Error(\n `unable to get quickinfo data from tsserver at ${this.getPath(node)}, Ln ${location.line}, Col ${\n location.character\n }`\n );\n }\n throw err;\n }\n }\n\n async getQuickInfoDisplayString(node: Node): Promise<string> {\n const quickInfo = await this.getQuickInfo(node);\n return quickInfo?.body?.displayString || '';\n }\n\n /**\n * returns the type definition for a type.\n */\n typeDefinition(node: Node) {\n return this.tsserver.getTypeDefinition(this.getPath(node), this.getLocation(node));\n }\n\n visitTypeDefinition() {}\n\n findFileInComponent(filePath: string) {\n const normalizedFilePath = pathNormalizeToLinux(filePath);\n const fileNameToCompare = basename(normalizedFilePath);\n const pathWithoutExtension = fileNameToCompare.replace(/\\.[^/.]+$/, '');\n const possibleFormats = new Set(['ts', 'tsx', 'js', 'jsx']);\n\n const matchingFile = this.component.filesystem.files.find((file) => {\n const currentFilePath = pathNormalizeToLinux(file.path);\n const currentFileName = basename(currentFilePath);\n const currentFileExtension = extname(currentFilePath).substring(1);\n\n const isSameBaseName = pathWithoutExtension === basename(currentFileName, `.${currentFileExtension}`);\n const isValidExtension = possibleFormats.has(currentFileExtension);\n\n if (isSameBaseName && isValidExtension) {\n return true;\n }\n\n if (\n ['ts', 'js'].some((format) => {\n const indexFilePath = join(normalizedFilePath, `index.${format}`);\n return pathNormalizeToLinux(indexFilePath) === currentFilePath;\n })\n ) {\n return true;\n }\n\n return false;\n });\n\n return matchingFile;\n }\n\n private parsePackageNameFromPath(path: string) {\n const parts = path.split('node_modules');\n\n if (parts.length === 1) {\n return path;\n }\n\n const lastPart = parts[parts.length - 1].replace(sep, '');\n const pkgParts = lastPart.split('/');\n if (lastPart.startsWith('@')) {\n // scoped package\n return `${pkgParts[0]}/${pkgParts[1]}`;\n }\n const pkgName = pkgParts[0];\n if (pkgName === 'typescript') {\n // it's a built-in type, such as \"string\".\n return '';\n }\n return pkgName;\n }\n\n /**\n * return the file if part of the component.\n * otherwise, a reference to the target package and the type name.\n */\n getSourceFileInsideComponent(filePath: string) {\n const file = this.findFileInComponent(filePath);\n return file && this.extractor.parseSourceFile(file);\n }\n\n async getSourceFileFromNode(node: Node) {\n const filePath = await this.getFilePathByNode(node);\n if (!filePath) {\n return undefined;\n }\n return this.getSourceFileInsideComponent(filePath);\n }\n\n async getFilePathByNode(node: Node) {\n const def = await this.tsserver.getDefinition(this.getPath(node), this.getLocation(node));\n\n const firstDef = head(def?.body);\n return firstDef?.file;\n }\n\n async definitionInfo(node: Node): Promise<protocol.DefinitionInfo | undefined> {\n const location = this.getLocation(node);\n const filePath = this.getPath(node);\n\n const def = await this.tsserver.getDefinition(filePath, location);\n\n const firstDef = head(def?.body);\n\n return firstDef;\n }\n\n /**\n * get a definition for a given node.\n */\n async definition(definition: protocol.DefinitionInfo): Promise<Node | undefined> {\n const startPosition = definition.start;\n const sourceFile = this.getSourceFileInsideComponent(definition.file);\n if (!sourceFile) {\n // it might be an external reference, cant get the node\n return undefined;\n }\n const pos = this.getPosition(sourceFile, startPosition.line, startPosition.offset);\n const nodeAtPos = getTokenAtPosition(sourceFile, pos);\n return nodeAtPos;\n }\n\n /**\n * visit a definition for node - e.g. return it's schema.\n */\n async visitDefinition(node: Node): Promise<SchemaNode | undefined> {\n const definitionInfo = await this.definitionInfo(node);\n if (!definitionInfo) {\n return undefined;\n }\n\n const definition = await this.definition(definitionInfo);\n if (!definition) {\n return this.getTypeRefForExternalNode(node);\n }\n\n return this.visit(definition.parent);\n }\n\n async visit(node: Node): Promise<SchemaNode> {\n if (node.kind === SyntaxKind.Identifier && node.parent.parent.kind !== SyntaxKind.SourceFile) {\n return this.visit(node.parent);\n }\n return this.extractor.computeSchema(node, this);\n }\n\n references() {}\n\n isExported() {}\n\n isFromComponent() {}\n\n async getFileIdentifiers(exportDec: ExportDeclaration | ExportAssignment) {\n const file = exportDec.getSourceFile().fileName;\n const specifierPathStr =\n (exportDec.kind === SyntaxKind.ExportDeclaration && exportDec.moduleSpecifier?.getText()) || '';\n const specifierPath = specifierPathStr.substring(1, specifierPathStr.length - 1);\n const absPath = resolve(file, '..', specifierPath);\n const sourceFile = this.getSourceFileInsideComponent(absPath);\n if (!sourceFile) return [];\n return this.getIdentifiers(sourceFile);\n }\n\n async getFileExports(exportDec: ExportDeclaration | ExportAssignment) {\n const identifiers = await this.getFileIdentifiers(exportDec);\n return identifiers.filter((identifier) => ExportIdentifier.isExportIdentifier(identifier));\n }\n\n async getFileInternals(exportDec: ExportDeclaration | ExportAssignment) {\n const identifiers = await this.getFileIdentifiers(exportDec);\n return identifiers.filter((identifier) => !ExportIdentifier.isExportIdentifier(identifier));\n }\n\n getIdentifiers(node: Node) {\n return this.extractor.computeIdentifiers(node, this);\n }\n\n /**\n * tsserver has two different calls: \"definition\" and \"typeDefinition\".\n * normally, we need the \"typeDefinition\" to get the type data of a node.\n * sometimes, it has no data, for example when the node is of type TypeReference, and then using \"definition\" is\n * helpful. (couldn't find a rule when to use each one. e.g. \"VariableDeclaration\" sometimes has data only in\n * \"definition\" but it's not clear when/why).\n */\n async getDefinition(node: Node) {\n const typeDefinition = await this.typeDefinition(node);\n const headTypeDefinition = head(typeDefinition?.body);\n if (headTypeDefinition) {\n return headTypeDefinition;\n }\n const definition = await this.tsserver.getDefinition(node.getSourceFile().fileName, this.getLocation(node));\n return head(definition?.body);\n }\n\n // when we can't figure out the component/package/type of this node, we'll use the typeStr as the type.\n private async unknownExactType(node: Node, location: Location, typeStr = 'any', isTypeStrFromQuickInfo = true) {\n if (isTypeStrFromQuickInfo) {\n return new InferenceTypeSchema(location, typeStr || 'any');\n }\n const info = await this.getQuickInfo(node);\n const type = parseTypeFromQuickInfo(info);\n return new InferenceTypeSchema(location, type, typeStr);\n }\n\n // the reason for this check is to avoid infinite loop when calling `this.jump` with the same file+location\n private isDefInSameLocation(node: Node, definition: protocol.FileSpanWithContext) {\n if (definition.file !== node.getSourceFile().fileName) {\n return false;\n }\n const loc = this.getLocation(node);\n\n return loc.line === definition.start.line && loc.character === definition.start.offset;\n }\n\n /**\n * resolve a type by a node and its identifier.\n */\n async resolveType(\n node: Node & { type?: TypeNode },\n typeStr: string,\n isTypeStrFromQuickInfo = true\n ): Promise<SchemaNode> {\n const location = this.getLocation(node);\n\n // check if internal ref with typeInfo\n const internalRef = await this.getTypeRef(typeStr, this.getIdentifierKeyForNode(node), location);\n\n if (internalRef) return internalRef;\n\n // if a node has \"type\" prop, it has the type data of the node. this normally happens when the code has the type\n // explicitly, e.g. `const str: string` vs implicitly `const str = 'some-string'`, which the node won't have \"type\"\n if (node.type && ts.isTypeNode(node.type)) {\n return this.computeSchema(node.type);\n }\n\n const definition = await this.getDefinition(node);\n if (!definition) {\n return this.unknownExactType(node, location, typeStr, isTypeStrFromQuickInfo);\n }\n\n const file = this.findFileInComponent(definition.file);\n\n if (!file) return this.getTypeRefForExternalPath(typeStr, definition.file, location);\n\n if (this.isDefInSameLocation(node, definition)) {\n return this.unknownExactType(node, location, typeStr, isTypeStrFromQuickInfo);\n }\n\n const definitionNode = await this.definition(definition);\n\n if (!definitionNode) {\n return this.unknownExactType(node, location, typeStr, isTypeStrFromQuickInfo);\n }\n\n const definitionNodeName = definitionNode?.getText();\n\n // check if internal ref with definition info\n const definitionInternalRef = await this.getTypeRef(\n definitionNodeName,\n this.getIdentifierKeyForNode(definitionNode),\n location\n );\n\n if (definitionInternalRef) return definitionInternalRef;\n\n const transformer = this.extractor.getTransformer(definitionNode, this);\n\n if (transformer === undefined) {\n return this.unknownExactType(node, location, typeStr, isTypeStrFromQuickInfo);\n }\n const schemaNode = await this.visit(definitionNode);\n return schemaNode || this.unknownExactType(node, location, typeStr, isTypeStrFromQuickInfo);\n }\n\n private getCompIdByPkgName(pkgName: string): ComponentID | undefined {\n return this.componentDeps.find((dep) => dep.packageName === pkgName)?.componentId;\n }\n\n async getTypeRef(typeStr: string, filePath: string, location: Location): Promise<TypeRefSchema | undefined> {\n const nodeIdentifierKey = this.getIdentifierKey(filePath);\n const mainFileIdentifierKey = this.mainFileIdentifierKey;\n\n const nodeIdentifierList = this.identifiers.get(nodeIdentifierKey);\n const mainIdentifierList = this.identifiers.get(mainFileIdentifierKey);\n\n const nodeIdentifier = new Identifier(typeStr, nodeIdentifierKey);\n const mainIdentifier = new Identifier(typeStr, mainFileIdentifierKey);\n\n const parsedNodeIdentifier = nodeIdentifierList?.find(nodeIdentifier);\n const parsedMainIdentifier = mainIdentifierList?.find(mainIdentifier);\n const isExportedFromMain = parsedMainIdentifier && ExportIdentifier.isExportIdentifier(parsedMainIdentifier);\n\n if (!parsedNodeIdentifier) return undefined;\n\n const internalRef = !isExportedFromMain;\n\n if (internalRef) {\n this.setInternalIdentifiers(filePath, new IdentifierList([parsedNodeIdentifier]));\n }\n\n return this.resolveTypeRef(parsedNodeIdentifier, location, isExportedFromMain);\n }\n\n async resolveTypeRef(\n identifier: Identifier,\n location: Location,\n isExportedFromMain?: boolean\n ): Promise<TypeRefSchema> {\n const sourceFilePath = identifier.sourceFilePath;\n\n if (!sourceFilePath || isExportedFromMain) {\n return new TypeRefSchema(\n location,\n identifier.id,\n undefined,\n undefined,\n !isExportedFromMain ? this.getPathRelativeToComponent(identifier.filePath) : undefined\n );\n }\n\n if (!isRelativeImport(sourceFilePath)) {\n const pkgName = this.parsePackageNameFromPath(sourceFilePath);\n const compIdByPkg = this.getCompIdByPkgName(pkgName);\n\n const compIdByPath = await this.extractor.getComponentIDByPath(sourceFilePath);\n\n if (compIdByPath) {\n return new TypeRefSchema(location, identifier.id, compIdByPath);\n }\n\n if (compIdByPkg) {\n return new TypeRefSchema(location, identifier.id, compIdByPkg);\n }\n\n // package without comp id\n return new TypeRefSchema(location, identifier.id, undefined, pkgName);\n }\n\n const relativeDir = identifier.filePath.substring(0, identifier.filePath.lastIndexOf('/'));\n const absFilePath = resolve(relativeDir, sourceFilePath);\n const compFilePath = this.findFileInComponent(absFilePath);\n if (!compFilePath) {\n // @todo handle this better\n throw new Error(\n `cannot find file in component \\n absolute path: ${absFilePath}\\n source file path ${sourceFilePath}\\n identifier file path ${identifier.filePath} \\n relative dir ${relativeDir}`\n );\n return new TypeRefSchema(location, identifier.id);\n }\n\n const idKey = this.getIdentifierKey(compFilePath?.path);\n\n // if re exported from a file, recurse until definition\n const exportedIdentifier = (this.identifiers.get(idKey)?.identifiers || []).find((i) => i.id === identifier.id);\n\n if (exportedIdentifier) {\n return this.resolveTypeRef(exportedIdentifier, location, isExportedFromMain);\n }\n\n return new TypeRefSchema(location, identifier.id);\n }\n\n async getTypeRefForExternalNode(node: Node): Promise<TypeRefSchema> {\n const info = await this.getQuickInfo(node);\n const typeStr = parseTypeFromQuickInfo(info);\n const location = this.getLocation(node);\n const filePath = this.getPath(node);\n return this.getTypeRefForExternalPath(typeStr, filePath, location);\n }\n\n async getTypeRefForExternalPath(typeStr: string, filePath: string, location: Location): Promise<TypeRefSchema> {\n const compIdByPath = await this.extractor.getComponentIDByPath(filePath);\n if (compIdByPath) {\n return new TypeRefSchema(location, typeStr, compIdByPath);\n }\n const pkgName = this.parsePackageNameFromPath(filePath);\n const compIdByPkg = this.getCompIdByPkgName(pkgName);\n if (compIdByPkg) {\n return new TypeRefSchema(location, typeStr, compIdByPkg);\n }\n return new TypeRefSchema(location, typeStr, undefined, pkgName);\n }\n\n async jsDocToDocSchema(node: Node): Promise<DocSchema | undefined> {\n if (!canHaveJsDoc(node)) {\n return undefined;\n }\n const jsDocs = getJsDoc(node);\n if (!jsDocs.length) {\n return undefined;\n }\n // not sure how common it is to have multiple JSDocs. never seen it before.\n // regardless, in typescript implementation of methods like `getJSDocDeprecatedTag()`, they use the first one. (`getFirstJSDocTag()`)\n const jsDoc = jsDocs[0];\n const location = this.getLocation(jsDoc);\n const comment = getTextOfJSDocComment(jsDoc.comment);\n const tags = jsDoc.tags ? await pMapSeries(jsDoc.tags, (tag) => tagParser(tag, this, this.formatter)) : undefined;\n return new DocSchema(location, jsDoc.getText(), comment, tags);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAIA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAEA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAOA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAGA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAEA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAAuD;AAAA;AAEhD,MAAMA,sBAAsB,CAAC;EAClC;AACF;AACA;;EAIE;AACF;AACA;;EAGE,IAAIC,QAAQ,GAAG;IACb,OAAO,IAAAC,6BAAoB,EAAC,IAAI,CAACC,0BAA0B,CAAC,IAAI,CAACC,SAAS,CAACH,QAAQ,CAACI,IAAI,CAAC,CAAC;EAC5F;EAEA,IAAIC,WAAW,GAAG;IAChB,OAAO,IAAI,CAACC,YAAY;EAC1B;EAEA,IAAIC,mBAAmB,GAAG;IACxB,OAAO,IAAI,CAACC,oBAAoB;EAClC;EA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IAAU,EAAkC;IACjE,IAAI,CAAC,IAAA+K,uBAAY,EAAC/K,IAAI,CAAC,EAAE;MACvB,OAAOsF,SAAS;IAClB;IACA,MAAM0F,MAAM,GAAG,IAAAC,mBAAQ,EAACjL,IAAI,CAAC;IAC7B,IAAI,CAACgL,MAAM,CAACpG,MAAM,EAAE;MAClB,OAAOU,SAAS;IAClB;IACA;IACA;IACA,MAAM4F,KAAK,GAAGF,MAAM,CAAC,CAAC,CAAC;IACvB,MAAM5K,QAAQ,GAAG,IAAI,CAACc,WAAW,CAACgK,KAAK,CAAC;IACxC,MAAMC,OAAO,GAAG,IAAAC,mCAAqB,EAACF,KAAK,CAACC,OAAO,CAAC;IACpD,MAAME,IAAI,GAAGH,KAAK,CAACG,IAAI,GAAG,MAAM,IAAAC,qBAAU,EAACJ,KAAK,CAACG,IAAI,EAAGE,GAAG,IAAK,IAAAC,6BAAS,EAACD,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC9L,SAAS,CAAC,CAAC,GAAG6F,SAAS;IACjH,OAAO,KAAImG,8BAAS,EAACrL,QAAQ,EAAE8K,KAAK,CAAChE,OAAO,EAAE,EAAEiE,OAAO,EAAEE,IAAI,CAAC;EAChE;AACF;AAAC"}
@@ -101,27 +101,31 @@ async function namedExport(exportClause, context) {
101
101
  return schemas;
102
102
  }
103
103
  async function exportSpecifierToSchemaNode(element, context) {
104
- const definitionInfo = await context.definitionInfo(element);
105
- if (!definitionInfo) {
106
- // happens for example when the main index.ts file exports variable from an mdx file.
107
- // tsserver is unable to get the definition node because it doesn't know to parse mdx files.
108
- return new (_semanticsEntities().UnresolvedSchema)(context.getLocation(element.name), element.name.getText());
109
- }
110
- const definitionNode = await context.definition(definitionInfo);
111
- if (!definitionNode) {
112
- return context.resolveType(element, element.name.getText(), false);
113
- }
104
+ try {
105
+ const definitionInfo = await context.definitionInfo(element);
106
+ if (!definitionInfo) {
107
+ // happens for example when the main index.ts file exports variable from an mdx file.
108
+ // tsserver is unable to get the definition node because it doesn't know to parse mdx files.
109
+ return new (_semanticsEntities().UnresolvedSchema)(context.getLocation(element.name), element.name.getText());
110
+ }
111
+ const definitionNode = await context.definition(definitionInfo);
112
+ if (!definitionNode) {
113
+ return await context.resolveType(element, element.name.getText(), false);
114
+ }
114
115
 
115
- // if it is reexported from another export
116
- if (isSameNode(element, definitionNode.parent)) {
117
- // the definition node is the same node as element.name. tsserver wasn't able to find the source for it
118
- // normally, "bit install" should fix it. another option is to open vscode and look for errors.
119
- throw new Error(`error: tsserver is unable to locate the identifier "${element.name.getText()}" at ${context.getLocationAsString(element.name)}.
116
+ // if it is reexported from another export
117
+ if (isSameNode(element, definitionNode.parent)) {
118
+ // the definition node is the same node as element.name. tsserver wasn't able to find the source for it
119
+ // normally, "bit install" should fix it. another option is to open vscode and look for errors.
120
+ throw new Error(`error: tsserver is unable to locate the identifier "${element.name.getText()}" at ${context.getLocationAsString(element.name)}.
120
121
  make sure "bit status" is clean and there are no errors about missing packages/links.
121
122
  also, make sure the tsconfig.json in the root has the "jsx" setting defined.`);
123
+ }
124
+ if (definitionNode.parent.kind === _typescript().SyntaxKind.ExportSpecifier) return exportSpecifierToSchemaNode(definitionNode.parent, context);
125
+ return await context.computeSchema(definitionNode.parent);
126
+ } catch (e) {
127
+ return new (_semanticsEntities().UnresolvedSchema)(context.getLocation(element.name), element.name.getText());
122
128
  }
123
- if (definitionNode.parent.kind === _typescript().SyntaxKind.ExportSpecifier) return exportSpecifierToSchemaNode(definitionNode.parent, context);
124
- return context.computeSchema(definitionNode.parent);
125
129
  }
126
130
  async function namespaceExport(exportClause, exportDec, context) {
127
131
  const namespace = exportClause.name.getText();
@@ -1 +1 @@
1
- {"version":3,"names":["ExportDeclarationTransformer","predicate","node","kind","SyntaxKind","ExportDeclaration","getIdentifiers","exportDec","context","rawSourceFilePath","moduleSpecifier","getText","sourceFilePath","substring","length","exportClause","ts","NamedExports","elements","map","elm","alias","propertyName","name","undefined","id","fileName","getSourceFile","ExportIdentifier","NamespaceExport","getFileExports","transform","specifier","Error","sourceFile","getSourceFileFromNode","UnImplementedSchema","getLocation","computeSchema","schemas","namedExport","ModuleSchema","namespaceExport","isSameNode","nodeA","nodeB","pos","end","Promise","all","element","exportSpecifierToSchemaNode","definitionInfo","UnresolvedSchema","definitionNode","definition","resolveType","parent","getLocationAsString","ExportSpecifier","namespace","filePath","getFilePathByNode","getSourceFileInsideComponent","getTypeRefForExternalPath","result"],"sources":["export-declaration.ts"],"sourcesContent":["import {\n SchemaNode,\n ModuleSchema,\n UnresolvedSchema,\n UnImplementedSchema,\n} from '@teambit/semantics.entities.semantic-schema';\nimport ts, {\n Node,\n SyntaxKind,\n ExportDeclaration as ExportDeclarationNode,\n NamedExports,\n NamespaceExport,\n ExportSpecifier,\n} from 'typescript';\nimport { SchemaExtractorContext } from '../schema-extractor-context';\nimport { SchemaTransformer } from '../schema-transformer';\nimport { ExportIdentifier } from '../export-identifier';\n\nexport class ExportDeclarationTransformer implements SchemaTransformer {\n predicate(node: Node) {\n return node.kind === SyntaxKind.ExportDeclaration;\n }\n\n async getIdentifiers(exportDec: ExportDeclarationNode, context: SchemaExtractorContext) {\n // e.g. `export { button1, button2 } as Composition from './button';\n const rawSourceFilePath = exportDec.moduleSpecifier?.getText();\n\n // strip off quotes ''\n const sourceFilePath = rawSourceFilePath && rawSourceFilePath.substring(1, rawSourceFilePath?.length - 1);\n\n if (exportDec.exportClause?.kind === ts.SyntaxKind.NamedExports) {\n return exportDec.exportClause.elements.map((elm) => {\n const alias = (elm.propertyName && elm.name.getText()) || undefined;\n const id = elm.propertyName?.getText() || elm.name.getText();\n const fileName = elm.getSourceFile().fileName;\n\n return new ExportIdentifier(id, fileName, alias, sourceFilePath);\n });\n }\n\n // e.g. `export * as Composition from './button';\n if (exportDec.exportClause?.kind === ts.SyntaxKind.NamespaceExport) {\n return [\n new ExportIdentifier(\n exportDec.exportClause.name.getText(),\n exportDec.getSourceFile().fileName,\n undefined,\n sourceFilePath\n ),\n ];\n }\n\n if (exportDec.moduleSpecifier) {\n return context.getFileExports(exportDec);\n }\n\n return [];\n }\n\n async transform(exportDec: ExportDeclarationNode, context: SchemaExtractorContext): Promise<SchemaNode> {\n const exportClause = exportDec.exportClause;\n\n // it's export-all, e.g. `export * from './button'`;\n if (!exportClause) {\n const specifier = exportDec.moduleSpecifier;\n if (!specifier) {\n throw new Error(`fatal: no specifier`);\n }\n const sourceFile = await context.getSourceFileFromNode(specifier);\n // export * from 'webpack', export-all from a package\n if (!sourceFile) {\n return new UnImplementedSchema(\n context.getLocation(exportDec),\n exportDec.getText(),\n SyntaxKind[SyntaxKind.ExportDeclaration]\n );\n }\n return context.computeSchema(sourceFile);\n }\n\n // e.g. `export { button1, button2 } as Composition from './button';\n if (exportClause.kind === SyntaxKind.NamedExports) {\n const schemas = await namedExport(exportClause, context);\n return new ModuleSchema(context.getLocation(exportDec), schemas, []);\n }\n // e.g. `export * as Composition from './button';\n if (exportClause.kind === SyntaxKind.NamespaceExport) {\n return namespaceExport(exportClause, exportDec, context);\n }\n\n // should never reach here. exportClause can be either NamespaceExport or NamedExports\n throw new Error(`unrecognized exportClause type`);\n }\n}\n\nfunction isSameNode(nodeA: Node, nodeB: Node): boolean {\n return nodeA.kind === nodeB.kind && nodeA.pos === nodeB.pos && nodeA.end === nodeB.end;\n}\n\nasync function namedExport(exportClause: NamedExports, context: SchemaExtractorContext): Promise<SchemaNode[]> {\n const schemas = await Promise.all(\n exportClause.elements.map(async (element) => {\n return exportSpecifierToSchemaNode(element, context);\n })\n );\n\n return schemas;\n}\n\nasync function exportSpecifierToSchemaNode(element: ExportSpecifier, context: SchemaExtractorContext) {\n const definitionInfo = await context.definitionInfo(element);\n\n if (!definitionInfo) {\n // happens for example when the main index.ts file exports variable from an mdx file.\n // tsserver is unable to get the definition node because it doesn't know to parse mdx files.\n return new UnresolvedSchema(context.getLocation(element.name), element.name.getText());\n }\n\n const definitionNode = await context.definition(definitionInfo);\n\n if (!definitionNode) {\n return context.resolveType(element, element.name.getText(), false);\n }\n\n // if it is reexported from another export\n if (isSameNode(element, definitionNode.parent)) {\n // the definition node is the same node as element.name. tsserver wasn't able to find the source for it\n // normally, \"bit install\" should fix it. another option is to open vscode and look for errors.\n throw new Error(`error: tsserver is unable to locate the identifier \"${element.name.getText()}\" at ${context.getLocationAsString(\n element.name\n )}.\nmake sure \"bit status\" is clean and there are no errors about missing packages/links.\nalso, make sure the tsconfig.json in the root has the \"jsx\" setting defined.`);\n }\n\n if (definitionNode.parent.kind === SyntaxKind.ExportSpecifier)\n return exportSpecifierToSchemaNode(definitionNode.parent as ExportSpecifier, context);\n\n return context.computeSchema(definitionNode.parent);\n}\n\nasync function namespaceExport(\n exportClause: NamespaceExport,\n exportDec: ExportDeclarationNode,\n context: SchemaExtractorContext\n) {\n const namespace = exportClause.name.getText();\n const filePath = await context.getFilePathByNode(exportClause.name);\n if (!filePath) {\n throw new Error(`unable to find the file-path for \"${namespace}\"`);\n }\n const sourceFile = context.getSourceFileInsideComponent(filePath);\n if (!sourceFile) {\n // it's a namespace from another component or an external package.\n return context.getTypeRefForExternalPath(namespace, filePath, context.getLocation(exportDec));\n }\n const result = await context.computeSchema(sourceFile);\n if (!(result instanceof ModuleSchema)) {\n throw new Error(`expect result to be instance of Module`);\n }\n result.namespace = namespace;\n return result;\n}\n"],"mappings":";;;;;;;;AAAA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAMA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAUA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAAwD;AAAA;AAEjD,MAAMA,4BAA4B,CAA8B;EACrEC,SAAS,CAACC,IAAU,EAAE;IACpB,OAAOA,IAAI,CAACC,IAAI,KAAKC,wBAAU,CAACC,iBAAiB;EACnD;EAEA,MAAMC,cAAc,CAACC,SAAgC,EAAEC,OAA+B,EAAE;IAAA;IACtF;IACA,MAAMC,iBAAiB,4BAAGF,SAAS,CAACG,eAAe,0DAAzB,sBAA2BC,OAAO,EAAE;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,OAAO,CAAC;EAEvF,OAAOA,OAAO,CAAC8B,aAAa,CAACgB,cAAc,CAACG,MAAM,CAAC;AACrD;AAEA,eAAef,eAAe,CAC5B3B,YAA6B,EAC7BR,SAAgC,EAChCC,OAA+B,EAC/B;EACA,MAAMoD,SAAS,GAAG7C,YAAY,CAACQ,IAAI,CAACZ,OAAO,EAAE;EAC7C,MAAMkD,QAAQ,GAAG,MAAMrD,OAAO,CAACsD,iBAAiB,CAAC/C,YAAY,CAACQ,IAAI,CAAC;EACnE,IAAI,CAACsC,QAAQ,EAAE;IACb,MAAM,IAAI5B,KAAK,CAAE,qCAAoC2B,SAAU,GAAE,CAAC;EACpE;EACA,MAAM1B,UAAU,GAAG1B,OAAO,CAACuD,4BAA4B,CAACF,QAAQ,CAAC;EACjE,IAAI,CAAC3B,UAAU,EAAE;IACf;IACA,OAAO1B,OAAO,CAACwD,yBAAyB,CAACJ,SAAS,EAAEC,QAAQ,EAAErD,OAAO,CAAC6B,WAAW,CAAC9B,SAAS,CAAC,CAAC;EAC/F;EACA,MAAM0D,MAAM,GAAG,MAAMzD,OAAO,CAAC8B,aAAa,CAACJ,UAAU,CAAC;EACtD,IAAI,EAAE+B,MAAM,YAAYxB,iCAAY,CAAC,EAAE;IACrC,MAAM,IAAIR,KAAK,CAAE,wCAAuC,CAAC;EAC3D;EACAgC,MAAM,CAACL,SAAS,GAAGA,SAAS;EAC5B,OAAOK,MAAM;AACf"}
1
+ {"version":3,"names":["ExportDeclarationTransformer","predicate","node","kind","SyntaxKind","ExportDeclaration","getIdentifiers","exportDec","context","rawSourceFilePath","moduleSpecifier","getText","sourceFilePath","substring","length","exportClause","ts","NamedExports","elements","map","elm","alias","propertyName","name","undefined","id","fileName","getSourceFile","ExportIdentifier","NamespaceExport","getFileExports","transform","specifier","Error","sourceFile","getSourceFileFromNode","UnImplementedSchema","getLocation","computeSchema","schemas","namedExport","ModuleSchema","namespaceExport","isSameNode","nodeA","nodeB","pos","end","Promise","all","element","exportSpecifierToSchemaNode","definitionInfo","UnresolvedSchema","definitionNode","definition","resolveType","parent","getLocationAsString","ExportSpecifier","e","namespace","filePath","getFilePathByNode","getSourceFileInsideComponent","getTypeRefForExternalPath","result"],"sources":["export-declaration.ts"],"sourcesContent":["import {\n SchemaNode,\n ModuleSchema,\n UnresolvedSchema,\n UnImplementedSchema,\n} from '@teambit/semantics.entities.semantic-schema';\nimport ts, {\n Node,\n SyntaxKind,\n ExportDeclaration as ExportDeclarationNode,\n NamedExports,\n NamespaceExport,\n ExportSpecifier,\n} from 'typescript';\nimport { SchemaExtractorContext } from '../schema-extractor-context';\nimport { SchemaTransformer } from '../schema-transformer';\nimport { ExportIdentifier } from '../export-identifier';\n\nexport class ExportDeclarationTransformer implements SchemaTransformer {\n predicate(node: Node) {\n return node.kind === SyntaxKind.ExportDeclaration;\n }\n\n async getIdentifiers(exportDec: ExportDeclarationNode, context: SchemaExtractorContext) {\n // e.g. `export { button1, button2 } as Composition from './button';\n const rawSourceFilePath = exportDec.moduleSpecifier?.getText();\n\n // strip off quotes ''\n const sourceFilePath = rawSourceFilePath && rawSourceFilePath.substring(1, rawSourceFilePath?.length - 1);\n\n if (exportDec.exportClause?.kind === ts.SyntaxKind.NamedExports) {\n return exportDec.exportClause.elements.map((elm) => {\n const alias = (elm.propertyName && elm.name.getText()) || undefined;\n const id = elm.propertyName?.getText() || elm.name.getText();\n const fileName = elm.getSourceFile().fileName;\n\n return new ExportIdentifier(id, fileName, alias, sourceFilePath);\n });\n }\n\n // e.g. `export * as Composition from './button';\n if (exportDec.exportClause?.kind === ts.SyntaxKind.NamespaceExport) {\n return [\n new ExportIdentifier(\n exportDec.exportClause.name.getText(),\n exportDec.getSourceFile().fileName,\n undefined,\n sourceFilePath\n ),\n ];\n }\n\n if (exportDec.moduleSpecifier) {\n return context.getFileExports(exportDec);\n }\n\n return [];\n }\n\n async transform(exportDec: ExportDeclarationNode, context: SchemaExtractorContext): Promise<SchemaNode> {\n const exportClause = exportDec.exportClause;\n\n // it's export-all, e.g. `export * from './button'`;\n if (!exportClause) {\n const specifier = exportDec.moduleSpecifier;\n if (!specifier) {\n throw new Error(`fatal: no specifier`);\n }\n const sourceFile = await context.getSourceFileFromNode(specifier);\n // export * from 'webpack', export-all from a package\n if (!sourceFile) {\n return new UnImplementedSchema(\n context.getLocation(exportDec),\n exportDec.getText(),\n SyntaxKind[SyntaxKind.ExportDeclaration]\n );\n }\n return context.computeSchema(sourceFile);\n }\n\n // e.g. `export { button1, button2 } as Composition from './button';\n if (exportClause.kind === SyntaxKind.NamedExports) {\n const schemas = await namedExport(exportClause, context);\n return new ModuleSchema(context.getLocation(exportDec), schemas, []);\n }\n // e.g. `export * as Composition from './button';\n if (exportClause.kind === SyntaxKind.NamespaceExport) {\n return namespaceExport(exportClause, exportDec, context);\n }\n\n // should never reach here. exportClause can be either NamespaceExport or NamedExports\n throw new Error(`unrecognized exportClause type`);\n }\n}\n\nfunction isSameNode(nodeA: Node, nodeB: Node): boolean {\n return nodeA.kind === nodeB.kind && nodeA.pos === nodeB.pos && nodeA.end === nodeB.end;\n}\n\nasync function namedExport(exportClause: NamedExports, context: SchemaExtractorContext): Promise<SchemaNode[]> {\n const schemas = await Promise.all(\n exportClause.elements.map(async (element) => {\n return exportSpecifierToSchemaNode(element, context);\n })\n );\n\n return schemas;\n}\n\nasync function exportSpecifierToSchemaNode(element: ExportSpecifier, context: SchemaExtractorContext) {\n try {\n const definitionInfo = await context.definitionInfo(element);\n if (!definitionInfo) {\n // happens for example when the main index.ts file exports variable from an mdx file.\n // tsserver is unable to get the definition node because it doesn't know to parse mdx files.\n return new UnresolvedSchema(context.getLocation(element.name), element.name.getText());\n }\n\n const definitionNode = await context.definition(definitionInfo);\n\n if (!definitionNode) {\n return await context.resolveType(element, element.name.getText(), false);\n }\n\n // if it is reexported from another export\n if (isSameNode(element, definitionNode.parent)) {\n // the definition node is the same node as element.name. tsserver wasn't able to find the source for it\n // normally, \"bit install\" should fix it. another option is to open vscode and look for errors.\n throw new Error(`error: tsserver is unable to locate the identifier \"${element.name.getText()}\" at ${context.getLocationAsString(\n element.name\n )}.\nmake sure \"bit status\" is clean and there are no errors about missing packages/links.\nalso, make sure the tsconfig.json in the root has the \"jsx\" setting defined.`);\n }\n\n if (definitionNode.parent.kind === SyntaxKind.ExportSpecifier)\n return exportSpecifierToSchemaNode(definitionNode.parent as ExportSpecifier, context);\n\n return await context.computeSchema(definitionNode.parent);\n } catch (e) {\n return new UnresolvedSchema(context.getLocation(element.name), element.name.getText());\n }\n}\n\nasync function namespaceExport(\n exportClause: NamespaceExport,\n exportDec: ExportDeclarationNode,\n context: SchemaExtractorContext\n) {\n const namespace = exportClause.name.getText();\n const filePath = await context.getFilePathByNode(exportClause.name);\n if (!filePath) {\n throw new Error(`unable to find the file-path for \"${namespace}\"`);\n }\n const sourceFile = context.getSourceFileInsideComponent(filePath);\n if (!sourceFile) {\n // it's a namespace from another component or an external package.\n return context.getTypeRefForExternalPath(namespace, filePath, context.getLocation(exportDec));\n }\n const result = await context.computeSchema(sourceFile);\n if (!(result instanceof ModuleSchema)) {\n throw new Error(`expect result to be instance of Module`);\n }\n result.namespace = namespace;\n return result;\n}\n"],"mappings":";;;;;;;;AAAA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAMA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAUA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAAwD;AAAA;AAEjD,MAAMA,4BAA4B,CAA8B;EACrEC,SAAS,CAACC,IAAU,EAAE;IACpB,OAAOA,IAAI,CAACC,IAAI,KAAKC,wBAAU,CAACC,iBAAiB;EACnD;EAEA,MAAMC,cAAc,CAACC,SAAgC,EAAEC,OAA+B,EAAE;IAAA;IACtF;IACA,MAAMC,iBAAiB,4BAAGF,SAAS,CAACG,eAAe,0DAAzB,sBAA2BC,OAAO,EAAE;;IAE9D;IACA,MAAMC,cAAc,GAAGH,iBAAiB,IAAIA,iBAAiB,CAACI,SAAS,CAAC,CAA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cAAc,CAACG,MAAM,CAAC;EAC3D,CAAC,CAAC,OAAOG,CAAC,EAAE;IACV,OAAO,KAAIP,qCAAgB,EAAC7C,OAAO,CAAC6B,WAAW,CAACa,OAAO,CAAC3B,IAAI,CAAC,EAAE2B,OAAO,CAAC3B,IAAI,CAACZ,OAAO,EAAE,CAAC;EACxF;AACF;AAEA,eAAe+B,eAAe,CAC5B3B,YAA6B,EAC7BR,SAAgC,EAChCC,OAA+B,EAC/B;EACA,MAAMqD,SAAS,GAAG9C,YAAY,CAACQ,IAAI,CAACZ,OAAO,EAAE;EAC7C,MAAMmD,QAAQ,GAAG,MAAMtD,OAAO,CAACuD,iBAAiB,CAAChD,YAAY,CAACQ,IAAI,CAAC;EACnE,IAAI,CAACuC,QAAQ,EAAE;IACb,MAAM,IAAI7B,KAAK,CAAE,qCAAoC4B,SAAU,GAAE,CAAC;EACpE;EACA,MAAM3B,UAAU,GAAG1B,OAAO,CAACwD,4BAA4B,CAACF,QAAQ,CAAC;EACjE,IAAI,CAAC5B,UAAU,EAAE;IACf;IACA,OAAO1B,OAAO,CAACyD,yBAAyB,CAACJ,SAAS,EAAEC,QAAQ,EAAEtD,OAAO,CAAC6B,WAAW,CAAC9B,SAAS,CAAC,CAAC;EAC/F;EACA,MAAM2D,MAAM,GAAG,MAAM1D,OAAO,CAAC8B,aAAa,CAACJ,UAAU,CAAC;EACtD,IAAI,EAAEgC,MAAM,YAAYzB,iCAAY,CAAC,EAAE;IACrC,MAAM,IAAIR,KAAK,CAAE,wCAAuC,CAAC;EAC3D;EACAiC,MAAM,CAACL,SAAS,GAAGA,SAAS;EAC5B,OAAOK,MAAM;AACf"}
@@ -31,7 +31,6 @@ export declare class TypescriptCompiler implements Compiler, TypescriptCompilerI
31
31
  * compile multiple components on the capsules
32
32
  */
33
33
  build(context: BuildContext): Promise<BuiltTaskResult>;
34
- postBuild(context: BuildContext): Promise<void>;
35
34
  getArtifactDefinition(): {
36
35
  generatedBy: string;
37
36
  name: string;
@@ -38,13 +38,6 @@ function _bitError() {
38
38
  };
39
39
  return data;
40
40
  }
41
- function _packageJsonFile() {
42
- const data = _interopRequireDefault(require("@teambit/legacy/dist/consumer/component/package-json-file"));
43
- _packageJsonFile = function () {
44
- return data;
45
- };
46
- return data;
47
- }
48
41
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
49
42
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2().default)(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
50
43
  class TypescriptCompiler {
@@ -142,18 +135,6 @@ class TypescriptCompiler {
142
135
  componentsResults
143
136
  };
144
137
  }
145
- async postBuild(context) {
146
- await Promise.all(context.capsuleNetwork.seedersCapsules.map(async capsule => {
147
- const packageJson = _packageJsonFile().default.loadFromCapsuleSync(capsule.path);
148
- // the types['index.ts'] is needed only during the build to avoid errors when tsc finds the
149
- // same type once in the d.ts and once in the ts file.
150
- // the reason for `packageJson.packageJsonObject.main` is that .d.ts components don't have a main file and they do need the types prop
151
- if (packageJson.packageJsonObject.types && packageJson.packageJsonObject.main) {
152
- delete packageJson.packageJsonObject.types;
153
- await packageJson.write();
154
- }
155
- }));
156
- }
157
138
  getArtifactDefinition() {
158
139
  return [{
159
140
  generatedBy: this.id,
@@ -1 +1 @@
1
- {"version":3,"names":["TypescriptCompiler","constructor","id","logger","options","tsModule","distDir","distGlobPatterns","shouldCopyNonSupportedFiles","artifactName","tsconfig","compilerOptions","outDir","generateIdeConfig","globalTypesPaths","types","displayConfig","stringifyTsconfig","getDistDir","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","main","write","generatedBy","name","globPatterns","getDistPathBySrcPath","srcPath","fileWithJSExtIfNeeded","join","isJsAndCompile","compileJs","endsWith","isJsxAndCompile","compileJsx","network","capsulesRootDir","getCapsulesToCompile","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"],"sources":["typescript.compiler.ts"],"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';\nimport { TypescriptCompilerInterface } from './typescript-compiler-interface';\n\nexport class TypescriptCompiler implements Compiler, TypescriptCompilerInterface {\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 deleteDistDir = false;\n\n generateIdeConfig() {\n return {\n tsconfig: this.options.tsconfig,\n globalTypesPaths: this.options.types,\n };\n }\n\n displayConfig() {\n return this.stringifyTsconfig(this.options.tsconfig);\n }\n\n getDistDir() {\n return this.distDir;\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 // the reason for `packageJson.packageJsonObject.main` is that .d.ts components don't have a main file and they do need the types prop\n if (packageJson.packageJsonObject.types && packageJson.packageJsonObject.main) {\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 = await network.getCapsulesToCompile();\n if (!capsules.length) {\n return [];\n }\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"],"mappings":";;;;;;;;;;;;;;;;;;;AAIA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAEA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAAwF;AAAA;AAIjF,MAAMA,kBAAkB,CAAkD;EAK/EC,WAAW,CACAC,EAAU,EACXC,MAAc,EACd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/C;EAEQ3E,kBAAkB,CAACpB,QAAgB,EAAU;IACnD,IAAI,CAAC,IAAI,CAACD,eAAe,CAACC,QAAQ,CAAC,EAAE,OAAOA,QAAQ;IACpD,MAAM2I,aAAa,GAAG1G,eAAI,CAAC2G,OAAO,CAAC5I,QAAQ,CAAC;IAC5C,OAAOA,QAAQ,CAAC0G,OAAO,CAAC,IAAImC,MAAM,CAAE,GAAEF,aAAc,GAAE,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC;EACnE;;EAEAG,OAAO,GAAG;IACR,OAAO,IAAI,CAAC/J,QAAQ,CAAC+J,OAAO;EAC9B;AACF;AAAC"}
1
+ {"version":3,"names":["TypescriptCompiler","constructor","id","logger","options","tsModule","distDir","distGlobPatterns","shouldCopyNonSupportedFiles","artifactName","tsconfig","compilerOptions","outDir","generateIdeConfig","globalTypesPaths","types","displayConfig","stringifyTsconfig","getDistDir","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","generatedBy","name","globPatterns","getDistPathBySrcPath","srcPath","fileWithJSExtIfNeeded","join","isJsAndCompile","compileJs","endsWith","isJsxAndCompile","compileJsx","network","capsulesRootDir","getCapsulesToCompile","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","Promise","all","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"],"sources":["typescript.compiler.ts"],"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 { TypeScriptCompilerOptions } from './compiler-options';\nimport { TypescriptCompilerInterface } from './typescript-compiler-interface';\n\nexport class TypescriptCompiler implements Compiler, TypescriptCompilerInterface {\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 deleteDistDir = false;\n\n generateIdeConfig() {\n return {\n tsconfig: this.options.tsconfig,\n globalTypesPaths: this.options.types,\n };\n }\n\n displayConfig() {\n return this.stringifyTsconfig(this.options.tsconfig);\n }\n\n getDistDir() {\n return this.distDir;\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 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 = await network.getCapsulesToCompile();\n if (!capsules.length) {\n return [];\n }\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"],"mappings":";;;;;;;;;;;;;;;;;;;AAIA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAEA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAA8C;AAAA;AAIvC,MAAMA,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class TypeScriptExtractor {
113
113
  async extract(component, formatter) {
114
114
  const tsserver = await this.getTsServer();
115
115
  const mainFile = component.mainFile;
116
- const compatibleExts = ['.tsx', '.ts', '.jsx', '.js'];
116
+ const compatibleExts = ['.tsx', '.ts'];
117
117
  const internalFiles = component.filesystem.files.filter(file => compatibleExts.includes(file.extname) && file.path !== mainFile.path);
118
118
  const allFiles = [mainFile, ...internalFiles];
119
119
  const context = await this.createContext(tsserver, component, formatter);
@@ -1 +1 @@
1
- {"version":3,"names":["TypeScriptExtractor","constructor","tsconfig","schemaTransformerSlot","tsMain","rootPath","depResolver","workspace","scope","aspectLoader","logger","undefined","parseSourceFile","file","sourceFile","ts","createSourceFile","path","contents","toString","ScriptTarget","Latest","extract","component","formatter","tsserver","getTsServer","mainFile","compatibleExts","internalFiles","filesystem","files","filter","includes","extname","allFiles","context","createContext","pMapSeries","ast","identifiers","computeIdentifiers","cacheKey","getIdentifierKeyForNode","setIdentifiers","IdentifierList","mainAst","moduleSchema","computeSchema","flatExportsRecursively","apiScheme","internals","computeInternalModules","location","getLocation","APISchema","id","compact","Promise","all","internalIdentifiers","entries","map","filePath","find","internalFile","fileAst","dispose","killTsServer","node","transformer","getTransformer","getIdentifiers","warn","TransformerNotFound","componentDeps","getComponentDeps","SchemaExtractorContext","deps","getDependencies","getComponentDependencies","getTsserverClient","initTsserverClient","UnImplementedSchema","getText","SyntaxKind","kind","transform","getComponentIDByPath","coreAspectIds","getCoreAspectIds","matchingCoreAspect","c","getCoreAspectPackageName","resolveComponentId","getComponentIdByPath","transformers","flatten","values","singleTransformer","predicate","from","options","getTsconfig","config","compilerOptions","getAspect","TypescriptAspect","aspectLoaderMain","AspectLoaderAspect","wsPath","createLogger","name"],"sources":["typescript.extractor.ts"],"sourcesContent":["import ts, { Node, SourceFile, SyntaxKind } from 'typescript';\nimport { getTsconfig } from 'get-tsconfig';\nimport { SchemaExtractor } from '@teambit/schema';\nimport { TsserverClient } from '@teambit/ts-server';\nimport type { Workspace } from '@teambit/workspace';\nimport { ComponentDependency, DependencyResolverMain } from '@teambit/dependency-resolver';\nimport { SchemaNode, APISchema, ModuleSchema, UnImplementedSchema } from '@teambit/semantics.entities.semantic-schema';\nimport { Component } from '@teambit/component';\nimport { AbstractVinyl } from '@teambit/legacy/dist/consumer/component/sources';\nimport { EnvContext } from '@teambit/envs';\nimport { Formatter } from '@teambit/formatter';\nimport { Logger } from '@teambit/logger';\nimport AspectLoaderAspect, { AspectLoaderMain, getCoreAspectPackageName } from '@teambit/aspect-loader';\nimport { ScopeMain } from '@teambit/scope';\nimport pMapSeries from 'p-map-series';\nimport { compact, flatten } from 'lodash';\nimport { TypescriptMain, SchemaTransformerSlot } from './typescript.main.runtime';\nimport { TransformerNotFound } from './exceptions';\nimport { SchemaExtractorContext } from './schema-extractor-context';\nimport { Identifier } from './identifier';\nimport { IdentifierList } from './identifier-list';\nimport { ExtractorOptions } from './extractor-options';\nimport { TypescriptAspect } from './typescript.aspect';\n\nexport class TypeScriptExtractor implements SchemaExtractor {\n constructor(\n private tsconfig: any,\n private schemaTransformerSlot: SchemaTransformerSlot,\n private tsMain: TypescriptMain,\n private rootPath: string,\n private depResolver: DependencyResolverMain,\n private workspace: Workspace | undefined,\n private scope: ScopeMain,\n private aspectLoader: AspectLoaderMain,\n private logger: Logger\n ) {}\n\n parseSourceFile(file: AbstractVinyl): SourceFile {\n const sourceFile = ts.createSourceFile(\n file.path,\n file.contents.toString('utf8'),\n ts.ScriptTarget.Latest,\n true\n /** don't pass the scriptKind, it'll be determined automatically by typescript by the filepath */\n );\n // leave this commented out, it's helpful when there are issues with ASTs. consider throwing in this case.\n // console.log(\"sourceFile Errors\", file.path, sourceFile.parseDiagnostics);\n return sourceFile;\n }\n\n /**\n * extract a component schema.\n */\n async extract(component: Component, formatter?: Formatter): Promise<APISchema> {\n const tsserver = await this.getTsServer();\n const mainFile = component.mainFile;\n const compatibleExts = ['.tsx', '.ts', '.jsx', '.js'];\n const internalFiles = component.filesystem.files.filter(\n (file) => compatibleExts.includes(file.extname) && file.path !== mainFile.path\n );\n const allFiles = [mainFile, ...internalFiles];\n\n const context = await this.createContext(tsserver, component, formatter);\n\n await pMapSeries(allFiles, async (file) => {\n const ast = this.parseSourceFile(file);\n const identifiers = await this.computeIdentifiers(ast, context); // compute for every file\n const cacheKey = context.getIdentifierKeyForNode(ast);\n context.setIdentifiers(cacheKey, new IdentifierList(identifiers));\n });\n\n const mainAst = this.parseSourceFile(mainFile);\n const moduleSchema = (await this.computeSchema(mainAst, context)) as ModuleSchema;\n moduleSchema.flatExportsRecursively();\n const apiScheme = moduleSchema;\n const internals = await this.computeInternalModules(context, internalFiles);\n\n const location = context.getLocation(mainAst);\n\n return new APISchema(location, apiScheme, internals, component.id);\n }\n\n async computeInternalModules(context: SchemaExtractorContext, internalFiles: AbstractVinyl[]) {\n const internals = compact(\n await Promise.all(\n [...context.internalIdentifiers.entries()].map(async ([filePath]) => {\n const file = internalFiles.find((internalFile) => internalFile.path === filePath);\n if (!file) return undefined;\n const fileAst = this.parseSourceFile(file);\n const moduleSchema = (await this.computeSchema(fileAst, context)) as ModuleSchema;\n moduleSchema.flatExportsRecursively();\n return moduleSchema;\n })\n )\n );\n return internals;\n }\n\n dispose() {\n if (!this.tsserver) return;\n this.tsserver.killTsServer();\n }\n\n async computeIdentifiers(node: Node, context: SchemaExtractorContext) {\n const transformer = this.getTransformer(node, context);\n let identifiers: Identifier[] = [];\n if (!transformer || !transformer.getIdentifiers) {\n this.logger.warn(new TransformerNotFound(node, context.component, context.getLocation(node)).toString());\n } else {\n identifiers = await transformer.getIdentifiers(node, context);\n }\n return identifiers;\n }\n\n private async createContext(\n tsserver: TsserverClient,\n component: Component,\n formatter?: Formatter\n ): Promise<SchemaExtractorContext> {\n const componentDeps = await this.getComponentDeps(component);\n return new SchemaExtractorContext(tsserver, component, this, componentDeps, formatter);\n }\n\n private async getComponentDeps(component: Component): Promise<ComponentDependency[]> {\n const deps = await this.depResolver.getDependencies(component);\n const componentDeps = deps.getComponentDependencies();\n return componentDeps;\n }\n\n private tsserver: TsserverClient | undefined = undefined;\n\n private async getTsServer() {\n if (!this.tsserver) {\n const tsserver = this.tsMain.getTsserverClient();\n if (tsserver) {\n this.tsserver = tsserver;\n return tsserver;\n }\n\n this.tsserver = await this.tsMain.initTsserverClient(this.rootPath);\n return this.tsserver;\n }\n\n return this.tsserver;\n }\n\n async computeSchema(node: Node, context: SchemaExtractorContext): Promise<SchemaNode> {\n const transformer = this.getTransformer(node, context);\n\n if (!transformer) {\n return new UnImplementedSchema(context.getLocation(node), node.getText(), SyntaxKind[node.kind]);\n }\n return transformer.transform(node, context);\n }\n\n async getComponentIDByPath(file: string) {\n const coreAspectIds = this.aspectLoader.getCoreAspectIds();\n const matchingCoreAspect = coreAspectIds.find((c) => file === getCoreAspectPackageName(c));\n\n if (matchingCoreAspect) {\n return (this.workspace || this.scope).resolveComponentId(matchingCoreAspect);\n }\n\n if (this.workspace) {\n return this.workspace.getComponentIdByPath(file);\n }\n return null;\n }\n\n /**\n * select the correct transformer for a node.\n */\n getTransformer(node: Node, context: SchemaExtractorContext) {\n const transformers = flatten(this.schemaTransformerSlot.values());\n const transformer = transformers.find((singleTransformer) => {\n return singleTransformer.predicate(node);\n });\n if (!transformer) {\n this.logger.warn(new TransformerNotFound(node, context.component, context.getLocation(node)).toString());\n return undefined;\n }\n\n return transformer;\n }\n\n static from(options: ExtractorOptions) {\n return (context: EnvContext) => {\n const tsconfig = getTsconfig(options.tsconfig)?.config || { compilerOptions: options.compilerOptions };\n const tsMain = context.getAspect<TypescriptMain>(TypescriptAspect.id);\n const aspectLoaderMain = context.getAspect<AspectLoaderMain>(AspectLoaderAspect.id);\n\n // When loading the env from a scope you don't have a workspace\n const wsPath = tsMain.workspace?.path || '';\n return new TypeScriptExtractor(\n tsconfig,\n tsMain.schemaTransformerSlot,\n tsMain,\n wsPath,\n tsMain.depResolver,\n tsMain.workspace,\n tsMain.scope,\n aspectLoaderMain,\n context.createLogger(options.name)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AI,CAACC,WAAW,EAAE;MAChB,IAAI,CAAC5D,MAAM,CAAC+D,IAAI,CAAC,KAAIC,iCAAmB,EAACL,IAAI,EAAEjC,OAAO,CAACb,SAAS,EAAEa,OAAO,CAACkB,WAAW,CAACe,IAAI,CAAC,CAAC,CAAClD,QAAQ,EAAE,CAAC;MACxG,OAAOR,SAAS;IAClB;IAEA,OAAO2D,WAAW;EACpB;EAEA,OAAO+B,IAAI,CAACC,OAAyB,EAAE;IACrC,OAAQlE,OAAmB,IAAK;MAAA;MAC9B,MAAMlC,QAAQ,GAAG,qBAAAqG,2BAAW,EAACD,OAAO,CAACpG,QAAQ,CAAC,iDAA7B,aAA+BsG,MAAM,KAAI;QAAEC,eAAe,EAAEH,OAAO,CAACG;MAAgB,CAAC;MACtG,MAAMrG,MAAM,GAAGgC,OAAO,CAACsE,SAAS,CAAiBC,+BAAgB,CAACnD,EAAE,CAAC;MACrE,MAAMoD,gBAAgB,GAAGxE,OAAO,CAACsE,SAAS,CAAmBG,uBAAkB,CAACrD,EAAE,CAAC;;MAEnF;MACA,MAAMsD,MAAM,GAAG,sBAAA1G,MAAM,CAACG,SAAS,sDAAhB,kBAAkBU,IAAI,KAAI,EAAE;MAC3C,OAAO,IAAIjB,mBAAmB,CAC5BE,QAAQ,EACRE,MAAM,CAACD,qBAAqB,EAC5BC,MAAM,EACN0G,MAAM,EACN1G,MAAM,CAACE,WAAW,EAClBF,MAAM,CAACG,SAAS,EAChBH,MAAM,CAACI,KAAK,EACZoG,gBAAgB,EAChBxE,OAAO,CAAC2E,YAAY,CAACT,OAAO,CAACU,IAAI,CAAC,CACnC;IACH,CAAC;EACH;AACF;AAAC"}
1
+ {"version":3,"names":["TypeScriptExtractor","constructor","tsconfig","schemaTransformerSlot","tsMain","rootPath","depResolver","workspace","scope","aspectLoader","logger","undefined","parseSourceFile","file","sourceFile","ts","createSourceFile","path","contents","toString","ScriptTarget","Latest","extract","component","formatter","tsserver","getTsServer","mainFile","compatibleExts","internalFiles","filesystem","files","filter","includes","extname","allFiles","context","createContext","pMapSeries","ast","identifiers","computeIdentifiers","cacheKey","getIdentifierKeyForNode","setIdentifiers","IdentifierList","mainAst","moduleSchema","computeSchema","flatExportsRecursively","apiScheme","internals","computeInternalModules","location","getLocation","APISchema","id","compact","Promise","all","internalIdentifiers","entries","map","filePath","find","internalFile","fileAst","dispose","killTsServer","node","transformer","getTransformer","getIdentifiers","warn","TransformerNotFound","componentDeps","getComponentDeps","SchemaExtractorContext","deps","getDependencies","getComponentDependencies","getTsserverClient","initTsserverClient","UnImplementedSchema","getText","SyntaxKind","kind","transform","getComponentIDByPath","coreAspectIds","getCoreAspectIds","matchingCoreAspect","c","getCoreAspectPackageName","resolveComponentId","getComponentIdByPath","transformers","flatten","values","singleTransformer","predicate","from","options","getTsconfig","config","compilerOptions","getAspect","TypescriptAspect","aspectLoaderMain","AspectLoaderAspect","wsPath","createLogger","name"],"sources":["typescript.extractor.ts"],"sourcesContent":["import ts, { Node, SourceFile, SyntaxKind } from 'typescript';\nimport { getTsconfig } from 'get-tsconfig';\nimport { SchemaExtractor } from '@teambit/schema';\nimport { TsserverClient } from '@teambit/ts-server';\nimport type { Workspace } from '@teambit/workspace';\nimport { ComponentDependency, DependencyResolverMain } from '@teambit/dependency-resolver';\nimport { SchemaNode, APISchema, ModuleSchema, UnImplementedSchema } from '@teambit/semantics.entities.semantic-schema';\nimport { Component } from '@teambit/component';\nimport { AbstractVinyl } from '@teambit/legacy/dist/consumer/component/sources';\nimport { EnvContext } from '@teambit/envs';\nimport { Formatter } from '@teambit/formatter';\nimport { Logger } from '@teambit/logger';\nimport AspectLoaderAspect, { AspectLoaderMain, getCoreAspectPackageName } from '@teambit/aspect-loader';\nimport { ScopeMain } from '@teambit/scope';\nimport pMapSeries from 'p-map-series';\nimport { compact, flatten } from 'lodash';\nimport { TypescriptMain, SchemaTransformerSlot } from './typescript.main.runtime';\nimport { TransformerNotFound } from './exceptions';\nimport { SchemaExtractorContext } from './schema-extractor-context';\nimport { Identifier } from './identifier';\nimport { IdentifierList } from './identifier-list';\nimport { ExtractorOptions } from './extractor-options';\nimport { TypescriptAspect } from './typescript.aspect';\n\nexport class TypeScriptExtractor implements SchemaExtractor {\n constructor(\n private tsconfig: any,\n private schemaTransformerSlot: SchemaTransformerSlot,\n private tsMain: TypescriptMain,\n private rootPath: string,\n private depResolver: DependencyResolverMain,\n private workspace: Workspace | undefined,\n private scope: ScopeMain,\n private aspectLoader: AspectLoaderMain,\n private logger: Logger\n ) {}\n\n parseSourceFile(file: AbstractVinyl): SourceFile {\n const sourceFile = ts.createSourceFile(\n file.path,\n file.contents.toString('utf8'),\n ts.ScriptTarget.Latest,\n true\n /** don't pass the scriptKind, it'll be determined automatically by typescript by the filepath */\n );\n // leave this commented out, it's helpful when there are issues with ASTs. consider throwing in this case.\n // console.log(\"sourceFile Errors\", file.path, sourceFile.parseDiagnostics);\n return sourceFile;\n }\n\n /**\n * extract a component schema.\n */\n async extract(component: Component, formatter?: Formatter): Promise<APISchema> {\n const tsserver = await this.getTsServer();\n const mainFile = component.mainFile;\n const compatibleExts = ['.tsx', '.ts'];\n const internalFiles = component.filesystem.files.filter(\n (file) => compatibleExts.includes(file.extname) && file.path !== mainFile.path\n );\n const allFiles = [mainFile, ...internalFiles];\n\n const context = await this.createContext(tsserver, component, formatter);\n\n await pMapSeries(allFiles, async (file) => {\n const ast = this.parseSourceFile(file);\n const identifiers = await this.computeIdentifiers(ast, context); // compute for every file\n const cacheKey = context.getIdentifierKeyForNode(ast);\n context.setIdentifiers(cacheKey, new IdentifierList(identifiers));\n });\n\n const mainAst = this.parseSourceFile(mainFile);\n const moduleSchema = (await this.computeSchema(mainAst, context)) as ModuleSchema;\n moduleSchema.flatExportsRecursively();\n const apiScheme = moduleSchema;\n const internals = await this.computeInternalModules(context, internalFiles);\n\n const location = context.getLocation(mainAst);\n\n return new APISchema(location, apiScheme, internals, component.id);\n }\n\n async computeInternalModules(context: SchemaExtractorContext, internalFiles: AbstractVinyl[]) {\n const internals = compact(\n await Promise.all(\n [...context.internalIdentifiers.entries()].map(async ([filePath]) => {\n const file = internalFiles.find((internalFile) => internalFile.path === filePath);\n if (!file) return undefined;\n const fileAst = this.parseSourceFile(file);\n const moduleSchema = (await this.computeSchema(fileAst, context)) as ModuleSchema;\n moduleSchema.flatExportsRecursively();\n return moduleSchema;\n })\n )\n );\n return internals;\n }\n\n dispose() {\n if (!this.tsserver) return;\n this.tsserver.killTsServer();\n }\n\n async computeIdentifiers(node: Node, context: SchemaExtractorContext) {\n const transformer = this.getTransformer(node, context);\n let identifiers: Identifier[] = [];\n if (!transformer || !transformer.getIdentifiers) {\n this.logger.warn(new TransformerNotFound(node, context.component, context.getLocation(node)).toString());\n } else {\n identifiers = await transformer.getIdentifiers(node, context);\n }\n return identifiers;\n }\n\n private async createContext(\n tsserver: TsserverClient,\n component: Component,\n formatter?: Formatter\n ): Promise<SchemaExtractorContext> {\n const componentDeps = await this.getComponentDeps(component);\n return new SchemaExtractorContext(tsserver, component, this, componentDeps, formatter);\n }\n\n private async getComponentDeps(component: Component): Promise<ComponentDependency[]> {\n const deps = await this.depResolver.getDependencies(component);\n const componentDeps = deps.getComponentDependencies();\n return componentDeps;\n }\n\n private tsserver: TsserverClient | undefined = undefined;\n\n private async getTsServer() {\n if (!this.tsserver) {\n const tsserver = this.tsMain.getTsserverClient();\n if (tsserver) {\n this.tsserver = tsserver;\n return tsserver;\n }\n\n this.tsserver = await this.tsMain.initTsserverClient(this.rootPath);\n return this.tsserver;\n }\n\n return this.tsserver;\n }\n\n async computeSchema(node: Node, context: SchemaExtractorContext): Promise<SchemaNode> {\n const transformer = this.getTransformer(node, context);\n\n if (!transformer) {\n return new UnImplementedSchema(context.getLocation(node), node.getText(), SyntaxKind[node.kind]);\n }\n return transformer.transform(node, context);\n }\n\n async getComponentIDByPath(file: string) {\n const coreAspectIds = this.aspectLoader.getCoreAspectIds();\n const matchingCoreAspect = coreAspectIds.find((c) => file === getCoreAspectPackageName(c));\n\n if (matchingCoreAspect) {\n return (this.workspace || this.scope).resolveComponentId(matchingCoreAspect);\n }\n\n if (this.workspace) {\n return this.workspace.getComponentIdByPath(file);\n }\n return null;\n }\n\n /**\n * select the correct transformer for a node.\n */\n getTransformer(node: Node, context: SchemaExtractorContext) {\n const transformers = flatten(this.schemaTransformerSlot.values());\n const transformer = transformers.find((singleTransformer) => {\n return singleTransformer.predicate(node);\n });\n if (!transformer) {\n this.logger.warn(new TransformerNotFound(node, context.component, context.getLocation(node)).toString());\n return undefined;\n }\n\n return transformer;\n }\n\n static from(options: ExtractorOptions) {\n return (context: EnvContext) => {\n const tsconfig = getTsconfig(options.tsconfig)?.config || { compilerOptions: options.compilerOptions };\n const tsMain = context.getAspect<TypescriptMain>(TypescriptAspect.id);\n const aspectLoaderMain = context.getAspect<AspectLoaderMain>(AspectLoaderAspect.id);\n\n // When loading the env from a scope you don't have a workspace\n const wsPath = tsMain.workspace?.path || '';\n return new TypeScriptExtractor(\n tsconfig,\n tsMain.schemaTransformerSlot,\n tsMain,\n wsPath,\n tsMain.depResolver,\n tsMain.workspace,\n tsMain.scope,\n aspectLoaderMain,\n context.createLogger(options.name)\n );\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAKA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAMA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAEA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAEA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAEA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAEA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAAuD;AAAA;AAEhD,MAAMA,mBAAmB,CAA4B;EAC1DC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BAAgB,CAACnD,EAAE,CAAC;MACrE,MAAMoD,gBAAgB,GAAGxE,OAAO,CAACsE,SAAS,CAAmBG,uBAAkB,CAACrD,EAAE,CAAC;;MAEnF;MACA,MAAMsD,MAAM,GAAG,sBAAA1G,MAAM,CAACG,SAAS,sDAAhB,kBAAkBU,IAAI,KAAI,EAAE;MAC3C,OAAO,IAAIjB,mBAAmB,CAC5BE,QAAQ,EACRE,MAAM,CAACD,qBAAqB,EAC5BC,MAAM,EACN0G,MAAM,EACN1G,MAAM,CAACE,WAAW,EAClBF,MAAM,CAACG,SAAS,EAChBH,MAAM,CAACI,KAAK,EACZoG,gBAAgB,EAChBxE,OAAO,CAAC2E,YAAY,CAACT,OAAO,CAACU,IAAI,CAAC,CACnC;IACH,CAAC;EACH;AACF;AAAC"}
@@ -13,6 +13,7 @@ import { AspectLoaderMain } from '@teambit/aspect-loader';
13
13
  import { WorkspaceConfigFilesMain } from '@teambit/workspace-config-files';
14
14
  import { WatcherMain } from '@teambit/watcher';
15
15
  import type { Component } from '@teambit/component';
16
+ import { BuilderMain } from '@teambit/builder';
16
17
  import { EnvsMain } from '@teambit/envs';
17
18
  import { ScopeMain } from '@teambit/scope';
18
19
  import { TypeScriptCompilerOptions } from './compiler-options';
@@ -114,7 +115,7 @@ export declare class TypescriptMain {
114
115
  static runtime: import("@teambit/harmony").RuntimeDefinition;
115
116
  static dependencies: import("@teambit/harmony").Aspect[];
116
117
  static slots: ((registerFn: () => string) => SlotRegistry<SchemaTransformer[]>)[];
117
- static provider([schema, loggerExt, aspectLoader, workspace, cli, depResolver, envs, watcher, workspaceConfigFiles, compiler, scope,]: [
118
+ static provider([schema, loggerExt, aspectLoader, workspace, cli, depResolver, envs, watcher, workspaceConfigFiles, compiler, scope, builder,]: [
118
119
  SchemaMain,
119
120
  LoggerMain,
120
121
  AspectLoaderMain,
@@ -125,7 +126,8 @@ export declare class TypescriptMain {
125
126
  WatcherMain,
126
127
  WorkspaceConfigFilesMain,
127
128
  CompilerMain,
128
- ScopeMain
129
+ ScopeMain,
130
+ BuilderMain
129
131
  ], config: any, [schemaTransformerSlot]: [SchemaTransformerSlot]): Promise<TypescriptMain>;
130
132
  }
131
133
  export declare function runTransformersWithContext(config: TypescriptConfigMutator, transformers: TsConfigTransformer[] | undefined, context: TsConfigTransformContext): TypescriptConfigMutator;
@@ -115,6 +115,13 @@ function _watcher() {
115
115
  };
116
116
  return data;
117
117
  }
118
+ function _builder() {
119
+ const data = require("@teambit/builder");
120
+ _builder = function () {
121
+ return data;
122
+ };
123
+ return data;
124
+ }
118
125
  function _envs() {
119
126
  const data = _interopRequireDefault(require("@teambit/envs"));
120
127
  _envs = function () {
@@ -199,6 +206,13 @@ function _tsConfigWriter() {
199
206
  };
200
207
  return data;
201
208
  }
209
+ function _removeTypesTask() {
210
+ const data = require("./remove-types-task");
211
+ _removeTypesTask = function () {
212
+ return data;
213
+ };
214
+ return data;
215
+ }
202
216
  class TypescriptMain {
203
217
  constructor(logger, schemaTransformerSlot, workspace, scope, depResolver, envs, tsConfigWriter, aspectLoader) {
204
218
  this.logger = logger;
@@ -386,7 +400,7 @@ class TypescriptMain {
386
400
  results: 'succeed'
387
401
  };
388
402
  }
389
- static async provider([schema, loggerExt, aspectLoader, workspace, cli, depResolver, envs, watcher, workspaceConfigFiles, compiler, scope], config, [schemaTransformerSlot]) {
403
+ static async provider([schema, loggerExt, aspectLoader, workspace, cli, depResolver, envs, watcher, workspaceConfigFiles, compiler, scope, builder], config, [schemaTransformerSlot]) {
390
404
  schema.registerParser(new (_typescript5().TypeScriptParser)());
391
405
  const logger = loggerExt.createLogger(_typescript3().TypescriptAspect.id);
392
406
  workspaceConfigFiles.registerConfigWriter(new (_tsConfigWriter().TypescriptConfigWriter)(compiler, logger));
@@ -399,6 +413,9 @@ class TypescriptMain {
399
413
  workspace.registerOnComponentChange(tsMain.onComponentChange.bind(tsMain));
400
414
  workspace.registerOnComponentAdd(tsMain.onComponentChange.bind(tsMain));
401
415
  }
416
+ const removeTypesTask = new (_removeTypesTask().RemoveTypesTask)();
417
+ builder.registerSnapTasks([removeTypesTask]);
418
+ builder.registerTagTasks([removeTypesTask]);
402
419
  const checkTypesCmd = new (_checkTypes().CheckTypesCmd)(tsMain, workspace, logger);
403
420
  const writeTsconfigCmd = new (_writeTsconfig().default)(tsMain);
404
421
  cli.register(checkTypesCmd, writeTsconfigCmd);
@@ -407,7 +424,7 @@ class TypescriptMain {
407
424
  }
408
425
  exports.TypescriptMain = TypescriptMain;
409
426
  (0, _defineProperty2().default)(TypescriptMain, "runtime", _cli().MainRuntime);
410
- (0, _defineProperty2().default)(TypescriptMain, "dependencies", [_schema().SchemaAspect, _logger().LoggerAspect, _aspectLoader().default, _workspace().WorkspaceAspect, _cli().CLIAspect, _dependencyResolver().DependencyResolverAspect, _envs().default, _watcher().default, _workspaceConfigFiles().default, _compiler().CompilerAspect, _scope().ScopeAspect]);
427
+ (0, _defineProperty2().default)(TypescriptMain, "dependencies", [_schema().SchemaAspect, _logger().LoggerAspect, _aspectLoader().default, _workspace().WorkspaceAspect, _cli().CLIAspect, _dependencyResolver().DependencyResolverAspect, _envs().default, _watcher().default, _workspaceConfigFiles().default, _compiler().CompilerAspect, _scope().ScopeAspect, _builder().BuilderAspect]);
411
428
  (0, _defineProperty2().default)(TypescriptMain, "slots", [_harmony().Slot.withType()]);
412
429
  _typescript3().TypescriptAspect.addRuntime(TypescriptMain);
413
430
  function runTransformersWithContext(config, transformers = [], context) {
@@ -1 +1 @@
1
- {"version":3,"names":["TypescriptMain","constructor","logger","schemaTransformerSlot","workspace","scope","depResolver","envs","tsConfigWriter","aspectLoader","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","createCjsCompiler","getCjsTransformer","createEsmCompiler","getEsmTransformer","cjsTransformer","config","setModule","esmTransformer","setTarget","tsconfig","compilerOptions","module","lib","createSchemaExtractor","TypeScriptExtractor","getCjsPackageJsonProps","main","types","getEsmPackageJsonProps","type","getSupportedFilesForTsserver","components","map","c","filesystem","flat","f","filter","endsWith","cleanTsconfigJson","list","runtime","createEnvironment","execContext","getEnvExecutionContext","results","TsconfigWriter","clean","writeTsconfigJson","cleanResults","writeResults","write","onPreWatch","watchOpts","spawnTSServer","verbose","checkTypes","printTypeErrors","Boolean","onComponentChange","component","pMapSeries","file","onFileChange","provider","schema","loggerExt","cli","watcher","workspaceConfigFiles","compiler","registerParser","TypeScriptParser","createLogger","registerConfigWriter","TypescriptConfigWriter","registerPlugins","SchemaTransformerPlugin","tsconfigWriter","tsMain","register","ExportDeclarationTransformer","ExportAssignmentTransformer","FunctionLikeTransformer","ParameterTransformer","SetAccessorTransformer","GetAccessorTransformer","IndexSignatureTransformer","PropertyDeclarationTransformer","VariableStatementTransformer","VariableDeclaration","SourceFileTransformer","TypeAliasTransformer","ClassDeclarationTransformer","InterfaceDeclarationTransformer","EnumDeclarationTransformer","BindingElementTransformer","IntersectionTypeTransformer","UnionTypeTransformer","TypeReferenceTransformer","TypeLiteralTransformer","LiteralTypeTransformer","TypeQueryTransformer","ArrayTypeTransformer","TypeOperatorTransformer","KeywordTypeTransformer","TupleTypeTransformer","ParenthesizedTypeTransformer","TypePredicateTransformer","IndexedAccessTypeTransformer","TemplateLiteralTypeSpanTransformer","TemplateLiteralTypeTransformer","ThisTypeTransformer","ConditionalTypeTransformer","NamedTupleTransformer","ConstructorTransformer","ImportDeclarationTransformer","registerOnPreWatch","bind","registerOnComponentChange","registerOnComponentAdd","checkTypesCmd","CheckTypesCmd","writeTsconfigCmd","WriteTsconfigCmd","MainRuntime","SchemaAspect","LoggerAspect","AspectLoaderAspect","WorkspaceAspect","CLIAspect","DependencyResolverAspect","EnvsAspect","WatcherAspect","WorkspaceConfigFilesAspect","CompilerAspect","ScopeAspect","Slot","withType","addRuntime","context","Array","isArray","newConfig","reduce","acc","transformer"],"sources":["typescript.main.runtime.ts"],"sourcesContent":["import ts from 'typescript';\nimport { Slot, SlotRegistry } from '@teambit/harmony';\nimport { CLIAspect, CLIMain, MainRuntime } from '@teambit/cli';\nimport { Compiler, CompilerAspect, CompilerMain } 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 { Workspace } from '@teambit/workspace';\nimport { DependencyResolverAspect, DependencyResolverMain } from '@teambit/dependency-resolver';\nimport pMapSeries from 'p-map-series';\nimport { TsserverClient, TsserverClientOpts } from '@teambit/ts-server';\nimport AspectLoaderAspect, { AspectLoaderMain } from '@teambit/aspect-loader';\nimport WorkspaceConfigFilesAspect, { WorkspaceConfigFilesMain } from '@teambit/workspace-config-files';\nimport WatcherAspect, { WatcherMain, WatchOptions } from '@teambit/watcher';\nimport type { Component } from '@teambit/component';\nimport EnvsAspect, { EnvsMain } from '@teambit/envs';\nimport { ScopeMain, ScopeAspect } from '@teambit/scope';\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 { SchemaTransformer } from './schema-transformer';\nimport { SchemaTransformerPlugin } from './schema-transformer.plugin';\nimport {\n ExportDeclarationTransformer,\n TypeAliasTransformer,\n FunctionLikeTransformer,\n SetAccessorTransformer,\n GetAccessorTransformer,\n IndexSignatureTransformer,\n PropertyDeclarationTransformer,\n ParameterTransformer,\n VariableStatementTransformer,\n VariableDeclaration,\n SourceFileTransformer,\n ClassDeclarationTransformer,\n InterfaceDeclarationTransformer,\n EnumDeclarationTransformer,\n BindingElementTransformer,\n ExportAssignmentTransformer,\n ImportDeclarationTransformer,\n IntersectionTypeTransformer,\n UnionTypeTransformer,\n TypeReferenceTransformer,\n TypeLiteralTransformer,\n LiteralTypeTransformer,\n TypeQueryTransformer,\n ArrayTypeTransformer,\n TypeOperatorTransformer,\n KeywordTypeTransformer,\n TupleTypeTransformer,\n ParenthesizedTypeTransformer,\n TypePredicateTransformer,\n IndexedAccessTypeTransformer,\n TemplateLiteralTypeSpanTransformer,\n TemplateLiteralTypeTransformer,\n ThisTypeTransformer,\n ConditionalTypeTransformer,\n NamedTupleTransformer,\n ConstructorTransformer,\n} from './transformers';\nimport { CheckTypesCmd } from './cmds/check-types.cmd';\nimport { TsconfigPathsPerEnv, TsconfigWriter } from './tsconfig-writer';\nimport WriteTsconfigCmd from './cmds/write-tsconfig.cmd';\nimport { TypescriptConfigWriter } from './ts-config-writer';\n\nexport type TsMode = 'build' | 'dev';\n\nexport type SchemaTransformerSlot = SlotRegistry<SchemaTransformer[]>;\n\nexport type TsConfigTransformContext = {\n // mode: TsMode;\n};\n\nexport type TsconfigWriterOptions = {\n clean?: boolean;\n silent?: boolean; // no prompt\n dedupe?: boolean;\n dryRun?: boolean;\n dryRunWithTsconfig?: boolean;\n};\n\nexport type TsConfigTransformer = (\n config: TypescriptConfigMutator,\n context: TsConfigTransformContext\n) => TypescriptConfigMutator;\n\nexport class TypescriptMain {\n constructor(\n private logger: Logger,\n readonly schemaTransformerSlot: SchemaTransformerSlot,\n readonly workspace: Workspace,\n readonly scope: ScopeMain,\n readonly depResolver: DependencyResolverMain,\n private envs: EnvsMain,\n private tsConfigWriter: TsconfigWriter,\n private aspectLoader: AspectLoaderMain\n ) {}\n\n private tsServer: TsserverClient;\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 await 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 a compiler instance and run the cjs transformer for it\n * @param options\n * @param transformers\n * @param tsModule\n * @returns\n */\n createCjsCompiler(options: TypeScriptCompilerOptions, transformers: TsConfigTransformer[] = [], tsModule = ts) {\n return this.createCompiler(options, [this.getCjsTransformer(), ...transformers], tsModule);\n }\n\n /**\n * Create a compiler instance and run the esm transformer for it\n * @param options\n * @param transformers\n * @param tsModule\n * @returns\n */\n createEsmCompiler(options: TypeScriptCompilerOptions, transformers: TsConfigTransformer[] = [], tsModule = ts) {\n return this.createCompiler(options, [this.getEsmTransformer(), ...transformers], tsModule);\n }\n\n /**\n * Create a transformer that change the ts module to CommonJS\n * @returns\n */\n getCjsTransformer(): TsConfigTransformer {\n const cjsTransformer = (config: TypescriptConfigMutator) => {\n config.setModule('CommonJS');\n return config;\n };\n return cjsTransformer;\n }\n\n /**\n * Create a transformer that change the ts module to ES2020\n * @returns\n */\n getEsmTransformer(): TsConfigTransformer {\n const esmTransformer = (config: TypescriptConfigMutator) => {\n config.setTarget('ES2017');\n config.raw.tsconfig.compilerOptions.module = 'es2020';\n config.raw.tsconfig.compilerOptions.lib = ['es2021', 'dom', 'ESNext.String', 'dom.Iterable'];\n return config;\n };\n return esmTransformer;\n }\n\n /**\n * create an instance of a typescript semantic schema extractor.\n */\n createSchemaExtractor(tsconfig: any, path?: string): SchemaExtractor {\n return new TypeScriptExtractor(\n tsconfig,\n this.schemaTransformerSlot,\n this,\n path || this.workspace?.path || '',\n this.depResolver,\n this.workspace,\n this.scope,\n this.aspectLoader,\n this.logger\n );\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 getCjsPackageJsonProps(): PackageJsonProps {\n return {\n main: 'dist/{main}.js',\n types: '{main}.ts',\n };\n }\n\n /**\n * add type: module to the package.json props and the default props\n * :TODO @gilad why do we need this DSL? can't I just get the args here.\n */\n getEsmPackageJsonProps(): PackageJsonProps {\n return {\n // main: 'dist-esm/{main}.js',\n main: 'dist/{main}.js',\n type: 'module',\n types: '{main}.ts',\n };\n }\n\n 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 async cleanTsconfigJson(options: TsconfigWriterOptions = {}) {\n const components = await this.workspace.list();\n const runtime = await this.envs.createEnvironment(components);\n const execContext = runtime.getEnvExecutionContext();\n\n const results = await new TsconfigWriter(this.workspace, this.logger).clean(execContext, options);\n\n return results;\n }\n\n async writeTsconfigJson(options: TsconfigWriterOptions = {}): Promise<{\n cleanResults?: string[];\n writeResults: TsconfigPathsPerEnv[];\n }> {\n const components = await this.workspace.list();\n const runtime = await this.envs.createEnvironment(components);\n const execContext = runtime.getEnvExecutionContext();\n\n let cleanResults: string[] | undefined;\n if (options.clean) {\n cleanResults = await this.tsConfigWriter.clean(execContext, options);\n }\n\n const writeResults = await this.tsConfigWriter.write(execContext, options);\n\n return { writeResults, cleanResults };\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 = [\n SchemaAspect,\n LoggerAspect,\n AspectLoaderAspect,\n WorkspaceAspect,\n CLIAspect,\n DependencyResolverAspect,\n EnvsAspect,\n WatcherAspect,\n WorkspaceConfigFilesAspect,\n CompilerAspect,\n ScopeAspect,\n ];\n static slots = [Slot.withType<SchemaTransformer[]>()];\n\n static async provider(\n [\n schema,\n loggerExt,\n aspectLoader,\n workspace,\n cli,\n depResolver,\n envs,\n watcher,\n workspaceConfigFiles,\n compiler,\n scope,\n ]: [\n SchemaMain,\n LoggerMain,\n AspectLoaderMain,\n Workspace,\n CLIMain,\n DependencyResolverMain,\n EnvsMain,\n WatcherMain,\n WorkspaceConfigFilesMain,\n CompilerMain,\n ScopeMain\n ],\n config,\n [schemaTransformerSlot]: [SchemaTransformerSlot]\n ) {\n schema.registerParser(new TypeScriptParser());\n const logger = loggerExt.createLogger(TypescriptAspect.id);\n workspaceConfigFiles.registerConfigWriter(new TypescriptConfigWriter(compiler, logger));\n\n aspectLoader.registerPlugins([new SchemaTransformerPlugin(schemaTransformerSlot)]);\n const tsconfigWriter = new TsconfigWriter(workspace, logger);\n const tsMain = new TypescriptMain(\n logger,\n schemaTransformerSlot,\n workspace,\n scope,\n depResolver,\n envs,\n tsconfigWriter,\n aspectLoader\n );\n schemaTransformerSlot.register([\n new ExportDeclarationTransformer(),\n new ExportAssignmentTransformer(),\n new FunctionLikeTransformer(),\n new ParameterTransformer(),\n new SetAccessorTransformer(),\n new GetAccessorTransformer(),\n new IndexSignatureTransformer(),\n new PropertyDeclarationTransformer(),\n new VariableStatementTransformer(),\n new VariableDeclaration(),\n new SourceFileTransformer(),\n new TypeAliasTransformer(),\n new ClassDeclarationTransformer(),\n new InterfaceDeclarationTransformer(),\n new EnumDeclarationTransformer(),\n new BindingElementTransformer(),\n new IntersectionTypeTransformer(),\n new UnionTypeTransformer(),\n new TypeReferenceTransformer(),\n new TypeLiteralTransformer(),\n new LiteralTypeTransformer(),\n new TypeQueryTransformer(),\n new ArrayTypeTransformer(),\n new TypeOperatorTransformer(),\n new KeywordTypeTransformer(),\n new TupleTypeTransformer(),\n new ParenthesizedTypeTransformer(),\n new TypePredicateTransformer(),\n new IndexedAccessTypeTransformer(),\n new TemplateLiteralTypeSpanTransformer(),\n new TemplateLiteralTypeTransformer(),\n new ThisTypeTransformer(),\n new ConditionalTypeTransformer(),\n new NamedTupleTransformer(),\n new ConstructorTransformer(),\n new ImportDeclarationTransformer(),\n ]);\n\n if (workspace) {\n watcher.registerOnPreWatch(tsMain.onPreWatch.bind(tsMain));\n workspace.registerOnComponentChange(tsMain.onComponentChange.bind(tsMain));\n workspace.registerOnComponentAdd(tsMain.onComponentChange.bind(tsMain));\n }\n\n const checkTypesCmd = new CheckTypesCmd(tsMain, workspace, logger);\n const writeTsconfigCmd = new WriteTsconfigCmd(tsMain);\n cli.register(checkTypesCmd, writeTsconfigCmd);\n\n return tsMain;\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\nexport default TypescriptMain;\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAEA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAEA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAEA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAEA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAEA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAsCA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAuBO,MAAMA,cAAc,CAAC;EAC1BC,WAAW,CACDC,MAAc,EACbC,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AE7H,MAAM,CAAC;EACV,OAAOgI,SAAS;AAClB;AAAC,eAEcxK,cAAc;AAAA"}
1
+ {"version":3,"names":["TypescriptMain","constructor","logger","schemaTransformerSlot","workspace","scope","depResolver","envs","tsConfigWriter","aspectLoader","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","createCjsCompiler","getCjsTransformer","createEsmCompiler","getEsmTransformer","cjsTransformer","config","setModule","esmTransformer","setTarget","tsconfig","compilerOptions","module","lib","createSchemaExtractor","TypeScriptExtractor","getCjsPackageJsonProps","main","types","getEsmPackageJsonProps","type","getSupportedFilesForTsserver","components","map","c","filesystem","flat","f","filter","endsWith","cleanTsconfigJson","list","runtime","createEnvironment","execContext","getEnvExecutionContext","results","TsconfigWriter","clean","writeTsconfigJson","cleanResults","writeResults","write","onPreWatch","watchOpts","spawnTSServer","verbose","checkTypes","printTypeErrors","Boolean","onComponentChange","component","pMapSeries","file","onFileChange","provider","schema","loggerExt","cli","watcher","workspaceConfigFiles","compiler","builder","registerParser","TypeScriptParser","createLogger","registerConfigWriter","TypescriptConfigWriter","registerPlugins","SchemaTransformerPlugin","tsconfigWriter","tsMain","register","ExportDeclarationTransformer","ExportAssignmentTransformer","FunctionLikeTransformer","ParameterTransformer","SetAccessorTransformer","GetAccessorTransformer","IndexSignatureTransformer","PropertyDeclarationTransformer","VariableStatementTransformer","VariableDeclaration","SourceFileTransformer","TypeAliasTransformer","ClassDeclarationTransformer","InterfaceDeclarationTransformer","EnumDeclarationTransformer","BindingElementTransformer","IntersectionTypeTransformer","UnionTypeTransformer","TypeReferenceTransformer","TypeLiteralTransformer","LiteralTypeTransformer","TypeQueryTransformer","ArrayTypeTransformer","TypeOperatorTransformer","KeywordTypeTransformer","TupleTypeTransformer","ParenthesizedTypeTransformer","TypePredicateTransformer","IndexedAccessTypeTransformer","TemplateLiteralTypeSpanTransformer","TemplateLiteralTypeTransformer","ThisTypeTransformer","ConditionalTypeTransformer","NamedTupleTransformer","ConstructorTransformer","ImportDeclarationTransformer","registerOnPreWatch","bind","registerOnComponentChange","registerOnComponentAdd","removeTypesTask","RemoveTypesTask","registerSnapTasks","registerTagTasks","checkTypesCmd","CheckTypesCmd","writeTsconfigCmd","WriteTsconfigCmd","MainRuntime","SchemaAspect","LoggerAspect","AspectLoaderAspect","WorkspaceAspect","CLIAspect","DependencyResolverAspect","EnvsAspect","WatcherAspect","WorkspaceConfigFilesAspect","CompilerAspect","ScopeAspect","BuilderAspect","Slot","withType","addRuntime","context","Array","isArray","newConfig","reduce","acc","transformer"],"sources":["typescript.main.runtime.ts"],"sourcesContent":["import ts from 'typescript';\nimport { Slot, SlotRegistry } from '@teambit/harmony';\nimport { CLIAspect, CLIMain, MainRuntime } from '@teambit/cli';\nimport { Compiler, CompilerAspect, CompilerMain } 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 { Workspace } from '@teambit/workspace';\nimport { DependencyResolverAspect, DependencyResolverMain } from '@teambit/dependency-resolver';\nimport pMapSeries from 'p-map-series';\nimport { TsserverClient, TsserverClientOpts } from '@teambit/ts-server';\nimport AspectLoaderAspect, { AspectLoaderMain } from '@teambit/aspect-loader';\nimport WorkspaceConfigFilesAspect, { WorkspaceConfigFilesMain } from '@teambit/workspace-config-files';\nimport WatcherAspect, { WatcherMain, WatchOptions } from '@teambit/watcher';\nimport type { Component } from '@teambit/component';\nimport { BuilderAspect, BuilderMain } from '@teambit/builder';\nimport EnvsAspect, { EnvsMain } from '@teambit/envs';\nimport { ScopeMain, ScopeAspect } from '@teambit/scope';\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 { SchemaTransformer } from './schema-transformer';\nimport { SchemaTransformerPlugin } from './schema-transformer.plugin';\nimport {\n ExportDeclarationTransformer,\n TypeAliasTransformer,\n FunctionLikeTransformer,\n SetAccessorTransformer,\n GetAccessorTransformer,\n IndexSignatureTransformer,\n PropertyDeclarationTransformer,\n ParameterTransformer,\n VariableStatementTransformer,\n VariableDeclaration,\n SourceFileTransformer,\n ClassDeclarationTransformer,\n InterfaceDeclarationTransformer,\n EnumDeclarationTransformer,\n BindingElementTransformer,\n ExportAssignmentTransformer,\n ImportDeclarationTransformer,\n IntersectionTypeTransformer,\n UnionTypeTransformer,\n TypeReferenceTransformer,\n TypeLiteralTransformer,\n LiteralTypeTransformer,\n TypeQueryTransformer,\n ArrayTypeTransformer,\n TypeOperatorTransformer,\n KeywordTypeTransformer,\n TupleTypeTransformer,\n ParenthesizedTypeTransformer,\n TypePredicateTransformer,\n IndexedAccessTypeTransformer,\n TemplateLiteralTypeSpanTransformer,\n TemplateLiteralTypeTransformer,\n ThisTypeTransformer,\n ConditionalTypeTransformer,\n NamedTupleTransformer,\n ConstructorTransformer,\n} from './transformers';\nimport { CheckTypesCmd } from './cmds/check-types.cmd';\nimport { TsconfigPathsPerEnv, TsconfigWriter } from './tsconfig-writer';\nimport WriteTsconfigCmd from './cmds/write-tsconfig.cmd';\nimport { TypescriptConfigWriter } from './ts-config-writer';\nimport { RemoveTypesTask } from './remove-types-task';\n\nexport type TsMode = 'build' | 'dev';\n\nexport type SchemaTransformerSlot = SlotRegistry<SchemaTransformer[]>;\n\nexport type TsConfigTransformContext = {\n // mode: TsMode;\n};\n\nexport type TsconfigWriterOptions = {\n clean?: boolean;\n silent?: boolean; // no prompt\n dedupe?: boolean;\n dryRun?: boolean;\n dryRunWithTsconfig?: boolean;\n};\n\nexport type TsConfigTransformer = (\n config: TypescriptConfigMutator,\n context: TsConfigTransformContext\n) => TypescriptConfigMutator;\n\nexport class TypescriptMain {\n constructor(\n private logger: Logger,\n readonly schemaTransformerSlot: SchemaTransformerSlot,\n readonly workspace: Workspace,\n readonly scope: ScopeMain,\n readonly depResolver: DependencyResolverMain,\n private envs: EnvsMain,\n private tsConfigWriter: TsconfigWriter,\n private aspectLoader: AspectLoaderMain\n ) {}\n\n private tsServer: TsserverClient;\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 await 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 a compiler instance and run the cjs transformer for it\n * @param options\n * @param transformers\n * @param tsModule\n * @returns\n */\n createCjsCompiler(options: TypeScriptCompilerOptions, transformers: TsConfigTransformer[] = [], tsModule = ts) {\n return this.createCompiler(options, [this.getCjsTransformer(), ...transformers], tsModule);\n }\n\n /**\n * Create a compiler instance and run the esm transformer for it\n * @param options\n * @param transformers\n * @param tsModule\n * @returns\n */\n createEsmCompiler(options: TypeScriptCompilerOptions, transformers: TsConfigTransformer[] = [], tsModule = ts) {\n return this.createCompiler(options, [this.getEsmTransformer(), ...transformers], tsModule);\n }\n\n /**\n * Create a transformer that change the ts module to CommonJS\n * @returns\n */\n getCjsTransformer(): TsConfigTransformer {\n const cjsTransformer = (config: TypescriptConfigMutator) => {\n config.setModule('CommonJS');\n return config;\n };\n return cjsTransformer;\n }\n\n /**\n * Create a transformer that change the ts module to ES2020\n * @returns\n */\n getEsmTransformer(): TsConfigTransformer {\n const esmTransformer = (config: TypescriptConfigMutator) => {\n config.setTarget('ES2017');\n config.raw.tsconfig.compilerOptions.module = 'es2020';\n config.raw.tsconfig.compilerOptions.lib = ['es2021', 'dom', 'ESNext.String', 'dom.Iterable'];\n return config;\n };\n return esmTransformer;\n }\n\n /**\n * create an instance of a typescript semantic schema extractor.\n */\n createSchemaExtractor(tsconfig: any, path?: string): SchemaExtractor {\n return new TypeScriptExtractor(\n tsconfig,\n this.schemaTransformerSlot,\n this,\n path || this.workspace?.path || '',\n this.depResolver,\n this.workspace,\n this.scope,\n this.aspectLoader,\n this.logger\n );\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 getCjsPackageJsonProps(): PackageJsonProps {\n return {\n main: 'dist/{main}.js',\n types: '{main}.ts',\n };\n }\n\n /**\n * add type: module to the package.json props and the default props\n * :TODO @gilad why do we need this DSL? can't I just get the args here.\n */\n getEsmPackageJsonProps(): PackageJsonProps {\n return {\n // main: 'dist-esm/{main}.js',\n main: 'dist/{main}.js',\n type: 'module',\n types: '{main}.ts',\n };\n }\n\n 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 async cleanTsconfigJson(options: TsconfigWriterOptions = {}) {\n const components = await this.workspace.list();\n const runtime = await this.envs.createEnvironment(components);\n const execContext = runtime.getEnvExecutionContext();\n\n const results = await new TsconfigWriter(this.workspace, this.logger).clean(execContext, options);\n\n return results;\n }\n\n async writeTsconfigJson(options: TsconfigWriterOptions = {}): Promise<{\n cleanResults?: string[];\n writeResults: TsconfigPathsPerEnv[];\n }> {\n const components = await this.workspace.list();\n const runtime = await this.envs.createEnvironment(components);\n const execContext = runtime.getEnvExecutionContext();\n\n let cleanResults: string[] | undefined;\n if (options.clean) {\n cleanResults = await this.tsConfigWriter.clean(execContext, options);\n }\n\n const writeResults = await this.tsConfigWriter.write(execContext, options);\n\n return { writeResults, cleanResults };\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 = [\n SchemaAspect,\n LoggerAspect,\n AspectLoaderAspect,\n WorkspaceAspect,\n CLIAspect,\n DependencyResolverAspect,\n EnvsAspect,\n WatcherAspect,\n WorkspaceConfigFilesAspect,\n CompilerAspect,\n ScopeAspect,\n BuilderAspect,\n ];\n static slots = [Slot.withType<SchemaTransformer[]>()];\n\n static async provider(\n [\n schema,\n loggerExt,\n aspectLoader,\n workspace,\n cli,\n depResolver,\n envs,\n watcher,\n workspaceConfigFiles,\n compiler,\n scope,\n builder,\n ]: [\n SchemaMain,\n LoggerMain,\n AspectLoaderMain,\n Workspace,\n CLIMain,\n DependencyResolverMain,\n EnvsMain,\n WatcherMain,\n WorkspaceConfigFilesMain,\n CompilerMain,\n ScopeMain,\n BuilderMain\n ],\n config,\n [schemaTransformerSlot]: [SchemaTransformerSlot]\n ) {\n schema.registerParser(new TypeScriptParser());\n const logger = loggerExt.createLogger(TypescriptAspect.id);\n workspaceConfigFiles.registerConfigWriter(new TypescriptConfigWriter(compiler, logger));\n\n aspectLoader.registerPlugins([new SchemaTransformerPlugin(schemaTransformerSlot)]);\n const tsconfigWriter = new TsconfigWriter(workspace, logger);\n const tsMain = new TypescriptMain(\n logger,\n schemaTransformerSlot,\n workspace,\n scope,\n depResolver,\n envs,\n tsconfigWriter,\n aspectLoader\n );\n schemaTransformerSlot.register([\n new ExportDeclarationTransformer(),\n new ExportAssignmentTransformer(),\n new FunctionLikeTransformer(),\n new ParameterTransformer(),\n new SetAccessorTransformer(),\n new GetAccessorTransformer(),\n new IndexSignatureTransformer(),\n new PropertyDeclarationTransformer(),\n new VariableStatementTransformer(),\n new VariableDeclaration(),\n new SourceFileTransformer(),\n new TypeAliasTransformer(),\n new ClassDeclarationTransformer(),\n new InterfaceDeclarationTransformer(),\n new EnumDeclarationTransformer(),\n new BindingElementTransformer(),\n new IntersectionTypeTransformer(),\n new UnionTypeTransformer(),\n new TypeReferenceTransformer(),\n new TypeLiteralTransformer(),\n new LiteralTypeTransformer(),\n new TypeQueryTransformer(),\n new ArrayTypeTransformer(),\n new TypeOperatorTransformer(),\n new KeywordTypeTransformer(),\n new TupleTypeTransformer(),\n new ParenthesizedTypeTransformer(),\n new TypePredicateTransformer(),\n new IndexedAccessTypeTransformer(),\n new TemplateLiteralTypeSpanTransformer(),\n new TemplateLiteralTypeTransformer(),\n new ThisTypeTransformer(),\n new ConditionalTypeTransformer(),\n new NamedTupleTransformer(),\n new ConstructorTransformer(),\n new ImportDeclarationTransformer(),\n ]);\n\n if (workspace) {\n watcher.registerOnPreWatch(tsMain.onPreWatch.bind(tsMain));\n workspace.registerOnComponentChange(tsMain.onComponentChange.bind(tsMain));\n workspace.registerOnComponentAdd(tsMain.onComponentChange.bind(tsMain));\n }\n\n const removeTypesTask = new RemoveTypesTask();\n builder.registerSnapTasks([removeTypesTask]);\n builder.registerTagTasks([removeTypesTask]);\n\n const checkTypesCmd = new CheckTypesCmd(tsMain, workspace, logger);\n const writeTsconfigCmd = new WriteTsconfigCmd(tsMain);\n cli.register(checkTypesCmd, writeTsconfigCmd);\n\n return tsMain;\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\nexport default TypescriptMain;\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAEA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AAEA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA;EAAA;EAAA;AAAA;AACA;EAAA;EAAA;IAAA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AM,EAAErG,SAAS,EAAEF,MAAM,CAAC;IAClE,MAAMuJ,gBAAgB,GAAG,KAAIC,wBAAgB,EAACjD,MAAM,CAAC;IACrDb,GAAG,CAACc,QAAQ,CAAC6C,aAAa,EAAEE,gBAAgB,CAAC;IAE7C,OAAOhD,MAAM;EACf;AACF;AAAC;AAAA,gCA9UYzG,cAAc,aAuNR2J,kBAAW;AAAA,gCAvNjB3J,cAAc,kBAwNH,CACpB4J,sBAAY,EACZC,sBAAY,EACZC,uBAAkB,EAClBC,4BAAe,EACfC,gBAAS,EACTC,8CAAwB,EACxBC,eAAU,EACVC,kBAAa,EACbC,+BAA0B,EAC1BC,0BAAc,EACdC,oBAAW,EACXC,wBAAa,CACd;AAAA,gCArOUvK,cAAc,WAsOV,CAACwK,eAAI,CAACC,QAAQ,EAAuB,CAAC;AA0GvDnJ,+BAAgB,CAACoJ,UAAU,CAAC1K,cAAc,CAAC;AAEpC,SAASmB,0BAA0B,CACxCqB,MAA+B,EAC/B5B,YAAmC,GAAG,EAAE,EACxC+J,OAAiC,EACR;EACzB,IAAI,CAACC,KAAK,CAACC,OAAO,CAACjK,YAAY,CAAC,EAAE,OAAO4B,MAAM;EAC/C,MAAMsI,SAAS,GAAGlK,YAAY,CAACmK,MAAM,CAAC,CAACC,GAAG,EAAEC,WAAW,KAAK;IAC1D,OAAOA,WAAW,CAACD,GAAG,EAAEL,OAAO,CAAC;EAClC,CAAC,EAAEnI,MAAM,CAAC;EACV,OAAOsI,SAAS;AAClB;AAAC,eAEc9K,cAAc;AAAA"}
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@teambit/typescript",
3
- "version": "0.0.1075",
3
+ "version": "0.0.1077",
4
4
  "homepage": "https://bit.cloud/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.1075"
9
+ "version": "0.0.1077"
10
10
  },
11
11
  "dependencies": {
12
12
  "get-tsconfig": "4.2.0",
@@ -21,26 +21,26 @@
21
21
  "core-js": "^3.0.0",
22
22
  "@babel/runtime": "7.20.0",
23
23
  "@teambit/harmony": "0.4.6",
24
- "@teambit/compiler": "0.0.1075",
24
+ "@teambit/compiler": "0.0.1077",
25
25
  "@teambit/typescript.modules.ts-config-mutator": "0.0.76",
26
- "@teambit/component": "0.0.1075",
27
- "@teambit/dependency-resolver": "0.0.1075",
28
- "@teambit/formatter": "0.0.626",
26
+ "@teambit/builder": "0.0.1077",
27
+ "@teambit/isolator": "0.0.1077",
28
+ "@teambit/component": "0.0.1077",
29
+ "@teambit/dependency-resolver": "0.0.1077",
30
+ "@teambit/formatter": "0.0.628",
29
31
  "@teambit/semantics.entities.semantic-schema": "0.0.53",
30
- "@teambit/ts-server": "0.0.46",
31
- "@teambit/aspect-loader": "0.0.1075",
32
- "@teambit/envs": "0.0.1075",
33
- "@teambit/logger": "0.0.817",
34
- "@teambit/workspace-config-files": "0.0.55",
35
- "@teambit/workspace": "0.0.1075",
32
+ "@teambit/ts-server": "0.0.47",
33
+ "@teambit/aspect-loader": "0.0.1077",
34
+ "@teambit/envs": "0.0.1077",
35
+ "@teambit/logger": "0.0.818",
36
+ "@teambit/workspace-config-files": "0.0.57",
37
+ "@teambit/workspace": "0.0.1077",
36
38
  "@teambit/bit-error": "0.0.402",
37
- "@teambit/builder": "0.0.1075",
38
- "@teambit/isolator": "0.0.1075",
39
- "@teambit/schema": "0.0.1075",
40
- "@teambit/scope": "0.0.1075",
41
- "@teambit/cli": "0.0.724",
42
- "@teambit/pkg": "0.0.1075",
43
- "@teambit/watcher": "0.0.87"
39
+ "@teambit/schema": "0.0.1077",
40
+ "@teambit/scope": "0.0.1077",
41
+ "@teambit/cli": "0.0.725",
42
+ "@teambit/pkg": "0.0.1077",
43
+ "@teambit/watcher": "0.0.89"
44
44
  },
45
45
  "devDependencies": {
46
46
  "@types/lodash": "4.14.165",
@@ -56,7 +56,7 @@
56
56
  "@teambit/typescript.aspect-docs.typescript": "0.0.153"
57
57
  },
58
58
  "peerDependencies": {
59
- "@teambit/legacy": "1.0.504",
59
+ "@teambit/legacy": "1.0.505",
60
60
  "react": "^16.8.0 || ^17.0.0",
61
61
  "react-dom": "^16.8.0 || ^17.0.0"
62
62
  },
@@ -108,35 +108,38 @@ async function namedExport(exportClause: NamedExports, context: SchemaExtractorC
108
108
  }
109
109
 
110
110
  async function exportSpecifierToSchemaNode(element: ExportSpecifier, context: SchemaExtractorContext) {
111
- const definitionInfo = await context.definitionInfo(element);
112
-
113
- if (!definitionInfo) {
114
- // happens for example when the main index.ts file exports variable from an mdx file.
115
- // tsserver is unable to get the definition node because it doesn't know to parse mdx files.
116
- return new UnresolvedSchema(context.getLocation(element.name), element.name.getText());
117
- }
111
+ try {
112
+ const definitionInfo = await context.definitionInfo(element);
113
+ if (!definitionInfo) {
114
+ // happens for example when the main index.ts file exports variable from an mdx file.
115
+ // tsserver is unable to get the definition node because it doesn't know to parse mdx files.
116
+ return new UnresolvedSchema(context.getLocation(element.name), element.name.getText());
117
+ }
118
118
 
119
- const definitionNode = await context.definition(definitionInfo);
119
+ const definitionNode = await context.definition(definitionInfo);
120
120
 
121
- if (!definitionNode) {
122
- return context.resolveType(element, element.name.getText(), false);
123
- }
121
+ if (!definitionNode) {
122
+ return await context.resolveType(element, element.name.getText(), false);
123
+ }
124
124
 
125
- // if it is reexported from another export
126
- if (isSameNode(element, definitionNode.parent)) {
127
- // the definition node is the same node as element.name. tsserver wasn't able to find the source for it
128
- // normally, "bit install" should fix it. another option is to open vscode and look for errors.
129
- throw new Error(`error: tsserver is unable to locate the identifier "${element.name.getText()}" at ${context.getLocationAsString(
130
- element.name
131
- )}.
125
+ // if it is reexported from another export
126
+ if (isSameNode(element, definitionNode.parent)) {
127
+ // the definition node is the same node as element.name. tsserver wasn't able to find the source for it
128
+ // normally, "bit install" should fix it. another option is to open vscode and look for errors.
129
+ throw new Error(`error: tsserver is unable to locate the identifier "${element.name.getText()}" at ${context.getLocationAsString(
130
+ element.name
131
+ )}.
132
132
  make sure "bit status" is clean and there are no errors about missing packages/links.
133
133
  also, make sure the tsconfig.json in the root has the "jsx" setting defined.`);
134
- }
134
+ }
135
135
 
136
- if (definitionNode.parent.kind === SyntaxKind.ExportSpecifier)
137
- return exportSpecifierToSchemaNode(definitionNode.parent as ExportSpecifier, context);
136
+ if (definitionNode.parent.kind === SyntaxKind.ExportSpecifier)
137
+ return exportSpecifierToSchemaNode(definitionNode.parent as ExportSpecifier, context);
138
138
 
139
- return context.computeSchema(definitionNode.parent);
139
+ return await context.computeSchema(definitionNode.parent);
140
+ } catch (e) {
141
+ return new UnresolvedSchema(context.getLocation(element.name), element.name.getText());
142
+ }
140
143
  }
141
144
 
142
145
  async function namespaceExport(