Skip to content

Commit 016c14d

Browse files
authored
Merge pull request microsoft#69 from Microsoft/dagaeta/external-package-loading
Adding support for external json doc loading, Changed name of Analyzer to Extractor
2 parents a920548 + 0b5e006 commit 016c14d

28 files changed

Lines changed: 357 additions & 198 deletions

‎api-extractor/src/DebugRun.ts‎

Lines changed: 33 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -3,38 +3,46 @@
33

44
import * as ts from 'typescript';
55
import * as os from 'os';
6-
import Analyzer from './Analyzer';
6+
import Extractor from './Extractor';
77
import ApiFileGenerator from './generators/ApiFileGenerator';
88
import ApiJsonGenerator from './generators/ApiJsonGenerator';
9+
import { IApiDefinitionReference } from './IApiDefinitionReference';
910

10-
const analyzer: Analyzer = new Analyzer(
11-
(message: string, fileName: string, lineNumber: number): void => {
12-
console.log(`ErrorHandler: ${message}` + os.EOL
13-
+ ` ${fileName}#${lineNumber}`);
14-
}
15-
);
16-
17-
/**
18-
* Debugging inheritdoc expression parser.
19-
* Analyzer on example2 is needed for testing the parser.
20-
*/
21-
analyzer.analyze({
22-
compilerOptions: {
23-
target: ts.ScriptTarget.ES5,
24-
module: ts.ModuleKind.CommonJS,
25-
moduleResolution: ts.ModuleResolutionKind.NodeJs,
26-
experimentalDecorators: true,
27-
jsx: ts.JsxEmit.React,
28-
rootDir: './testInputs/example2'
29-
},
30-
entryPointFile: './testInputs/example2/index.ts',
31-
otherFiles: []
11+
const compilerOptions: ts.CompilerOptions = {
12+
target: ts.ScriptTarget.ES5,
13+
module: ts.ModuleKind.CommonJS,
14+
moduleResolution: ts.ModuleResolutionKind.NodeJs,
15+
experimentalDecorators: true,
16+
jsx: ts.JsxEmit.React,
17+
rootDir: './testInputs/example2'
18+
};
19+
20+
const extractor: Extractor = new Extractor( {
21+
compilerOptions: compilerOptions,
22+
errorHandler:
23+
(message: string, fileName: string, lineNumber: number): void => {
24+
console.log(`ErrorHandler: ${message}` + os.EOL
25+
+ ` ${fileName}#${lineNumber}`);
26+
}
3227
});
3328

29+
extractor.loadExternalPackages('./testInputs/external-api-json');
30+
31+
extractor.analyze({entryPointFile: './testInputs/example2/index.ts',
32+
otherFiles: []});
33+
34+
const externalPackageApiRef: IApiDefinitionReference = {
35+
scopeName: '',
36+
packageName: 'es6-collections',
37+
exportName: '',
38+
memberName: ''
39+
};
40+
console.log(extractor.docItemLoader.getPackage(externalPackageApiRef, console.log));
41+
3442
const apiFileGenerator: ApiFileGenerator = new ApiFileGenerator();
35-
apiFileGenerator.writeApiFile('./lib/DebugRun.api.ts', analyzer);
43+
apiFileGenerator.writeApiFile('./lib/DebugRun.api.ts', extractor);
3644

3745
const apiJsonGenerator: ApiJsonGenerator = new ApiJsonGenerator();
38-
apiJsonGenerator.writeJsonFile('./lib/DebugRun.json', analyzer);
46+
apiJsonGenerator.writeJsonFile('./lib/DebugRun.json', extractor);
3947

4048
console.log('DebugRun completed.');

‎api-extractor/src/DocItemLoader.ts‎

Lines changed: 31 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,9 @@ export interface IParsedScopeName {
2929
* then use DocItemLoader.getItem to retrieve the IDocItem of a particular API item.
3030
*/
3131
export default class DocItemLoader {
32-
private cache: Map<string, IDocPackage>;
33-
private projectFolder: string; // Root directory to check for node modules
32+
private _cache: Map<string, IDocPackage>;
33+
private _projectFolder: string; // Root directory to check for node modules
34+
private _errorHandler: (message: string) => void;
3435

3536
/**
3637
* The projectFolder is the top-level folder containing package.json for a project
@@ -41,8 +42,8 @@ export default class DocItemLoader {
4142
throw new Error(`An NPM project was not found in the specified folder: ${projectFolder}`);
4243
}
4344

44-
this.projectFolder = projectFolder;
45-
this.cache = new Map<string, IDocPackage>();
45+
this._projectFolder = projectFolder;
46+
this._cache = new Map<string, IDocPackage>();
4647
}
4748

4849
/**
@@ -51,12 +52,13 @@ export default class DocItemLoader {
5152
* will attempt to the locate the associated json file to load the package and
5253
* check there. If the API item can not be found the method will return undefined.
5354
*/
54-
public getItem(apiDefinitionRef: IApiDefinitionReference): IDocItem {
55+
public getItem(apiDefinitionRef: IApiDefinitionReference, reportError: (message: string) => void): IDocItem {
5556
if (!apiDefinitionRef) {
56-
throw new Error('Expected param to DocItemLoader.getItem() to be defined');
57+
reportError('Expected reference within {@inheritdoc} tag');
58+
return undefined;
5759
}
5860
// Try to load the package given the provided packageName into the cache
59-
const docPackage: IDocPackage = this.getPackage(apiDefinitionRef);
61+
const docPackage: IDocPackage = this.getPackage(apiDefinitionRef, reportError);
6062

6163
// Check if package was not found
6264
if (!docPackage) {
@@ -90,7 +92,7 @@ export default class DocItemLoader {
9092
*
9193
* @param apiDefinitionRef - interface with propropties pertaining to the API definition reference
9294
*/
93-
public getPackage(apiDefinitionRef: IApiDefinitionReference): IDocPackage {
95+
public getPackage(apiDefinitionRef: IApiDefinitionReference, reportError: (message: string) => void): IDocPackage {
9496
let cachePackageName: string = '';
9597

9698
// We concatenate the scopeName and packageName in case there are packageName conflicts
@@ -100,23 +102,38 @@ export default class DocItemLoader {
100102
cachePackageName = apiDefinitionRef.packageName;
101103
}
102104
// Check if package exists in cache
103-
if (cachePackageName in this.cache) {
104-
return this.cache[cachePackageName];
105+
if (this._cache.has(cachePackageName)) {
106+
return this._cache.get(cachePackageName);
107+
}
108+
109+
if (!apiDefinitionRef.packageName) {
110+
// Local export resolution is currently not supported yet
111+
return;
105112
}
106113

107114
// Doesn't exist in cache, attempt to load the json file
108115
const packageJsonFilePath: string = path.join(
109-
this.projectFolder,
116+
this._projectFolder,
110117
'node_modules',
111118
apiDefinitionRef.scopeName,
112119
apiDefinitionRef.packageName,
113120
`dist/${apiDefinitionRef.packageName}.api.json`
114121
);
115122

116123
if (!fsx.existsSync(path.join(packageJsonFilePath))) {
117-
return undefined;
124+
// package not found in node_modules
125+
reportError(`@inheritdoc referenced package ("${apiDefinitionRef.packageName}") not found in node modules.`);
126+
return;
118127
}
119128

129+
return this.loadPackageIntoCache(packageJsonFilePath);
130+
}
131+
132+
/**
133+
* Loads the API documentation json file and validates that it conforms to our schema. If it does,
134+
* then the json file is saved in the cache and returned.
135+
*/
136+
public loadPackageIntoCache(packageJsonFilePath: string): IDocPackage {
120137
const apiPackage: IDocPackage = JsonFile.loadJsonFile(packageJsonFilePath) as IDocPackage;
121138

122139
// Validate that the output conforms to our JSON schema
@@ -132,8 +149,8 @@ export default class DocItemLoader {
132149
}
133150
);
134151

135-
// JSON schema has been found and validated
136-
this.cache[cachePackageName] = apiPackage;
152+
const packageName: string = path.basename(packageJsonFilePath).split('.').shift();
153+
this._cache.set(packageName, apiPackage);
137154
return apiPackage;
138155
}
139156
}

‎api-extractor/src/ExternalApiHelper.ts‎

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import * as ts from 'typescript';
22
import * as os from 'os';
33
import * as path from 'path';
44
import * as fs from 'fs';
5-
import Analyzer from './Analyzer';
5+
import Extractor from './Extractor';
66
import ApiJsonGenerator from './generators/ApiJsonGenerator';
77

88
/**
@@ -23,12 +23,22 @@ export default class ExternalApiHelper {
2323
* Ex: 'resources/external-api-json/es6-promise/index.t.ds'
2424
*/
2525
public static generateApiJson(rootDir: string, libFolder: string, externalPackageFilePath: string): void {
26-
const analyzer: Analyzer = new Analyzer(
26+
const compilerOptions: ts.CompilerOptions = {
27+
target: ts.ScriptTarget.ES5,
28+
module: ts.ModuleKind.CommonJS,
29+
moduleResolution: ts.ModuleResolutionKind.NodeJs,
30+
experimentalDecorators: true,
31+
jsx: ts.JsxEmit.React,
32+
rootDir: rootDir
33+
};
34+
const extractor: Extractor = new Extractor( {
35+
compilerOptions: compilerOptions,
36+
errorHandler:
2737
(message: string, fileName: string, lineNumber: number): void => {
2838
console.log(`TypeScript error: ${message}` + os.EOL
2939
+ ` ${fileName}#${lineNumber}`);
3040
}
31-
);
41+
});
3242

3343
let outputPath: string = path.join(rootDir, libFolder);
3444
if (!fs.existsSync(outputPath)) {
@@ -44,21 +54,13 @@ export default class ExternalApiHelper {
4454
const outputApiJsonFilePath: string = path.join(outputPath, `${path.basename(externalPackageRootDir)}.api.json`);
4555
const entryPointFile: string = path.join(rootDir, externalPackageFilePath);
4656

47-
analyzer.analyze({
48-
compilerOptions: {
49-
target: ts.ScriptTarget.ES5,
50-
module: ts.ModuleKind.CommonJS,
51-
moduleResolution: ts.ModuleResolutionKind.NodeJs,
52-
experimentalDecorators: true,
53-
jsx: ts.JsxEmit.React,
54-
rootDir: rootDir
55-
},
57+
extractor.analyze({
5658
entryPointFile: entryPointFile, // local/bundles/platform-exports.ts',
5759
otherFiles: []
5860
});
5961

6062
const apiJsonGenerator: ApiJsonGenerator = new ApiJsonGenerator();
61-
apiJsonGenerator.writeJsonFile(outputApiJsonFilePath, analyzer);
63+
apiJsonGenerator.writeJsonFile(outputApiJsonFilePath, extractor);
6264

6365
}
6466
}
Lines changed: 45 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
import * as ts from 'typescript';
2+
import * as fsx from 'fs-extra';
3+
import * as path from 'path';
24
import ApiPackage from './definitions/ApiPackage';
35
import DocItemLoader from './DocItemLoader';
46

57
export type ApiErrorHandler = (message: string, fileName: string, lineNumber: number) => void;
68

79
/**
8-
* Options for Analyzer.analyze()
9-
*/
10-
export interface IApiAnalyzerOptions {
10+
* Options for Extractor contructor.
11+
*/
12+
export interface IExtractorOptions {
1113
/**
1214
* Configuration for the TypeScript compiler. The most important options to set are:
1315
*
@@ -18,10 +20,17 @@ export interface IApiAnalyzerOptions {
1820
*/
1921
compilerOptions: ts.CompilerOptions;
2022

23+
errorHandler?: ApiErrorHandler;
24+
}
25+
26+
/**
27+
* Options for Extractor.analyze()
28+
*/
29+
export interface IExtractorAnalyzeOptions {
2130
/**
2231
* The entry point for the project. This should correspond to the "main" field
2332
* from NPM's package.json file. If it is a relative path, it will be relative to
24-
* the project folder described by IApiAnalyzerOptions.compilerOptions.
33+
* the project folder described by IExtractorAnalyzeOptions.compilerOptions.
2534
*/
2635
entryPointFile: string;
2736

@@ -39,7 +48,7 @@ export interface IApiAnalyzerOptions {
3948
* TypeScript Compiler API to analyze a project, and constructs the ApiItem
4049
* abstract syntax tree.
4150
*/
42-
export default class Analyzer {
51+
export default class Extractor {
4352
public errorHandler: ApiErrorHandler;
4453
public typeChecker: ts.TypeChecker;
4554
public package: ApiPackage;
@@ -49,25 +58,28 @@ export default class Analyzer {
4958
*/
5059
public docItemLoader: DocItemLoader;
5160

61+
private _compilerOptions: ts.CompilerOptions;
62+
5263
/**
5364
* The default implementation of ApiErrorHandler, which merely writes to console.log().
5465
*/
5566
public static defaultErrorHandler(message: string, fileName: string, lineNumber: number): void {
5667
console.log(`ERROR: [${fileName}:${lineNumber}] ${message}`);
5768
}
5869

59-
constructor(errorHandler?: ApiErrorHandler) {
60-
this.errorHandler = errorHandler || Analyzer.defaultErrorHandler;
70+
constructor(options: IExtractorOptions) {
71+
this._compilerOptions = options.compilerOptions;
72+
this.docItemLoader = new DocItemLoader(options.compilerOptions.rootDir);
73+
this.errorHandler = options.errorHandler || Extractor.defaultErrorHandler;
6174
}
6275

6376
/**
6477
* Analyzes the specified project.
6578
*/
66-
public analyze(options: IApiAnalyzerOptions): void {
67-
this.docItemLoader = new DocItemLoader(options.compilerOptions.rootDir);
79+
public analyze(options: IExtractorAnalyzeOptions): void {
6880
const rootFiles: string[] = [options.entryPointFile].concat(options.otherFiles || []);
6981

70-
const program: ts.Program = ts.createProgram(rootFiles, options.compilerOptions);
82+
const program: ts.Program = ts.createProgram(rootFiles, this._compilerOptions);
7183

7284
// This runs a full type analysis, and then augments the Abstract Syntax Tree (i.e. declarations)
7385
// with semantic information (i.e. symbols). The "diagnostics" are a subset of the everyday
@@ -93,4 +105,27 @@ export default class Analyzer {
93105
const lineNumber: number = sourceFile.getLineAndCharacterOfPosition(start).line;
94106
this.errorHandler(message, sourceFile.fileName, lineNumber);
95107
}
108+
109+
/**
110+
* Scans for external package api files and loads them into the docItemLoader member before
111+
* any API analyzation begins.
112+
*
113+
* @param externalJsonCollectionPath - an absolute path to to the folder that contains all the external
114+
* api json files.
115+
* Ex: if externalJsonPath is './resources', then in that folder
116+
* are 'es6-collections.api.json', 'es6-promise.api.json', etc.
117+
*/
118+
public loadExternalPackages(externalJsonCollectionPath: string): void {
119+
if (!externalJsonCollectionPath) {
120+
return;
121+
}
122+
123+
const files: string[] = fsx.readdirSync(externalJsonCollectionPath);
124+
files.forEach(file => {
125+
if (path.extname(file) === '.json') {
126+
const externalJsonFilePath: string = path.join(externalJsonCollectionPath, file);
127+
this.docItemLoader.loadPackageIntoCache(externalJsonFilePath);
128+
}
129+
});
130+
}
96131
}

‎api-extractor/src/TestRun.ts‎

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,26 @@
33

44
import * as ts from 'typescript';
55
import * as path from 'path';
6-
import Analyzer from './Analyzer';
6+
import Extractor from './Extractor';
77
import ApiFileGenerator from './generators/ApiFileGenerator';
88

9-
const analyzer: Analyzer = new Analyzer();
10-
119
const inputFolder: string = './testInputs/example1';
1210
const outputFile: string = './lib/example1-output.ts';
1311

14-
analyzer.analyze({
15-
compilerOptions: {
16-
target: ts.ScriptTarget.ES5,
17-
module: ts.ModuleKind.CommonJS,
18-
moduleResolution: ts.ModuleResolutionKind.NodeJs,
19-
rootDir: inputFolder
20-
},
12+
const compilerOptions: ts.CompilerOptions = {
13+
target: ts.ScriptTarget.ES5,
14+
module: ts.ModuleKind.CommonJS,
15+
moduleResolution: ts.ModuleResolutionKind.NodeJs,
16+
rootDir: inputFolder
17+
};
18+
const extractor: Extractor = new Extractor({
19+
compilerOptions: compilerOptions,
20+
errorHandler: console.log
21+
});
22+
23+
extractor.analyze({
2124
entryPointFile: path.join(inputFolder, 'index.ts')
2225
});
2326

2427
const apiFileGenerator: ApiFileGenerator = new ApiFileGenerator();
25-
apiFileGenerator.writeApiFile(outputFile, analyzer);
28+
apiFileGenerator.writeApiFile(outputFile, extractor);

‎api-extractor/src/definitions/ApiDocumentation.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -454,7 +454,7 @@ export default class ApiDocumentation {
454454
}
455455

456456
// Atempt to locate the apiDefinitionRef
457-
const inheritedDoc: IDocItem = this.docItemLoader.getItem(apiDefinitionRef);
457+
const inheritedDoc: IDocItem = this.docItemLoader.getItem(apiDefinitionRef, this.reportError);
458458

459459
// If no IDocItem found then nothing to inherit
460460
// But for the time being set the summary to a text object

‎api-extractor/src/definitions/ApiEnum.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ export default class ApiEnum extends ApiItemContainer {
1515
const memberSymbol: ts.Symbol = TypeScriptHelpers.getSymbolForDeclaration(memberDeclaration);
1616

1717
const memberOptions: IApiItemOptions = {
18-
analyzer: this.analyzer,
18+
extractor: this.extractor,
1919
declaration: memberDeclaration,
2020
declarationSymbol: memberSymbol,
2121
jsdocNode: memberDeclaration

0 commit comments

Comments
 (0)