-
Notifications
You must be signed in to change notification settings - Fork 622
/
Copy pathExtractorConfig.ts
1401 lines (1235 loc) · 52.2 KB
/
ExtractorConfig.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import * as path from 'path';
import * as resolve from 'resolve';
import lodash = require('lodash');
import {
JsonFile,
JsonSchema,
FileSystem,
PackageJsonLookup,
type INodePackageJson,
PackageName,
Text,
InternalError,
Path,
NewlineKind
} from '@rushstack/node-core-library';
import { type IRigConfig, RigConfig } from '@rushstack/rig-package';
import { EnumMemberOrder, ReleaseTag } from '@microsoft/api-extractor-model';
import { TSDocConfiguration, TSDocTagDefinition } from '@microsoft/tsdoc';
import { TSDocConfigFile } from '@microsoft/tsdoc-config';
import type {
ApiReportVariant,
IConfigApiReport,
IConfigFile,
IExtractorMessagesConfig
} from './IConfigFile';
import { PackageMetadataManager } from '../analyzer/PackageMetadataManager';
import { MessageRouter } from '../collector/MessageRouter';
import type { IApiModelGenerationOptions } from '../generators/ApiModelGenerator';
import apiExtractorSchema from '../schemas/api-extractor.schema.json';
/**
* Tokens used during variable expansion of path fields from api-extractor.json.
*/
interface IExtractorConfigTokenContext {
/**
* The `<unscopedPackageName>` token returns the project's NPM package name, without any NPM scope.
* If there is no associated package.json file, then the value is `unknown-package`.
*
* Example: `my-project`
*/
unscopedPackageName: string;
/**
* The `<packageName>` token returns the project's full NPM package name including any NPM scope.
* If there is no associated package.json file, then the value is `unknown-package`.
*
* Example: `@scope/my-project`
*/
packageName: string;
/**
* The `<projectFolder>` token returns the expanded `"projectFolder"` setting from api-extractor.json.
*/
projectFolder: string;
}
/**
* Options for {@link ExtractorConfig.tryLoadForFolder}.
*
* @public
*/
export interface IExtractorConfigLoadForFolderOptions {
/**
* The folder path to start from when searching for api-extractor.json.
*/
startingFolder: string;
/**
* An already constructed `PackageJsonLookup` cache object to use. If omitted, a temporary one will
* be constructed.
*/
packageJsonLookup?: PackageJsonLookup;
/**
* An already constructed `RigConfig` object. If omitted, then a new `RigConfig` object will be constructed.
*/
rigConfig?: IRigConfig;
}
/**
* Options for {@link ExtractorConfig.prepare}.
*
* @public
*/
export interface IExtractorConfigPrepareOptions {
/**
* A configuration object as returned by {@link ExtractorConfig.loadFile}.
*/
configObject: IConfigFile;
/**
* The absolute path of the file that the `configObject` object was loaded from. This is used for error messages
* and when probing for `tsconfig.json`.
*
* @remarks
*
* If `configObjectFullPath` and `projectFolderLookupToken` are both unspecified, then the api-extractor.json
* config file must explicitly specify a `projectFolder` setting rather than relying on the `<lookup>` token.
*/
configObjectFullPath: string | undefined;
/**
* The parsed package.json file for the working package, or undefined if API Extractor was invoked without
* a package.json file.
*
* @remarks
*
* If omitted, then the `<unscopedPackageName>` and `<packageName>` tokens will have default values.
*/
packageJson?: INodePackageJson | undefined;
/**
* The absolute path of the file that the `packageJson` object was loaded from, or undefined if API Extractor
* was invoked without a package.json file.
*
* @remarks
*
* This is used for error messages and when resolving paths found in package.json.
*
* If `packageJsonFullPath` is specified but `packageJson` is omitted, the file will be loaded automatically.
*/
packageJsonFullPath: string | undefined;
/**
* The default value for the `projectFolder` setting is the `<lookup>` token, which uses a heuristic to guess
* an appropriate project folder. Use `projectFolderLookupValue` to manually specify the `<lookup>` token value
* instead.
*
* @remarks
* If the `projectFolder` setting is explicitly specified in api-extractor.json file, it should take precedence
* over a value specified via the API. Thus the `projectFolderLookupToken` option provides a way to override
* the default value for `projectFolder` setting while still honoring a manually specified value.
*/
projectFolderLookupToken?: string;
/**
* Allow customization of the tsdoc.json config file. If omitted, this file will be loaded from its default
* location. If the file does not exist, then the standard definitions will be used from
* `@microsoft/api-extractor/extends/tsdoc-base.json`.
*/
tsdocConfigFile?: TSDocConfigFile;
/**
* When preparing the configuration object, folder and file paths referenced in the configuration are checked
* for existence, and an error is reported if they are not found. This option can be used to disable this
* check for the main entry point module. This may be useful when preparing a configuration file for an
* un-built project.
*/
ignoreMissingEntryPoint?: boolean;
}
/**
* Configuration for a single API report, including its {@link IExtractorConfigApiReport.variant}.
*
* @public
*/
export interface IExtractorConfigApiReport {
/**
* Report variant.
* Determines which API items will be included in the report output, based on their tagged release levels.
*/
variant: ApiReportVariant;
/**
* Name of the output report file.
* @remarks Relative to the configured report directory path.
*/
fileName: string;
}
/** Default {@link IConfigApiReport.reportVariants} */
const defaultApiReportVariants: readonly ApiReportVariant[] = ['complete'];
/**
* Default {@link IConfigApiReport.tagsToReport}.
*
* @remarks
* Note that this list is externally documented, and directly affects report output.
* Also note that the order of tags in this list is significant, as it determines the order of tags in the report.
* Any changes to this list should be considered breaking.
*/
const defaultTagsToReport: Readonly<Record<`@${string}`, boolean>> = {
'@sealed': true,
'@virtual': true,
'@override': true,
'@eventProperty': true,
'@deprecated': true
};
interface IExtractorConfigParameters {
projectFolder: string;
packageJson: INodePackageJson | undefined;
packageFolder: string | undefined;
mainEntryPointFilePath: string;
bundledPackages: string[];
tsconfigFilePath: string;
overrideTsconfig: {} | undefined;
skipLibCheck: boolean;
apiReportEnabled: boolean;
reportConfigs: readonly IExtractorConfigApiReport[];
reportFolder: string;
reportTempFolder: string;
apiReportIncludeForgottenExports: boolean;
tagsToReport: Readonly<Record<`@${string}`, boolean>>;
docModelGenerationOptions: IApiModelGenerationOptions | undefined;
apiJsonFilePath: string;
docModelIncludeForgottenExports: boolean;
projectFolderUrl: string | undefined;
rollupEnabled: boolean;
untrimmedFilePath: string;
alphaTrimmedFilePath: string;
betaTrimmedFilePath: string;
publicTrimmedFilePath: string;
omitTrimmingComments: boolean;
tsdocMetadataEnabled: boolean;
tsdocMetadataFilePath: string;
tsdocConfigFile: TSDocConfigFile;
tsdocConfiguration: TSDocConfiguration;
newlineKind: NewlineKind;
messages: IExtractorMessagesConfig;
testMode: boolean;
enumMemberOrder: EnumMemberOrder;
}
/**
* The `ExtractorConfig` class loads, validates, interprets, and represents the api-extractor.json config file.
* @sealed
* @public
*/
export class ExtractorConfig {
/**
* The JSON Schema for API Extractor config file (api-extractor.schema.json).
*/
public static readonly jsonSchema: JsonSchema = JsonSchema.fromLoadedObject(apiExtractorSchema);
/**
* The config file name "api-extractor.json".
*/
public static readonly FILENAME: 'api-extractor.json' = 'api-extractor.json';
/**
* The full path to `extends/tsdoc-base.json` which contains the standard TSDoc configuration
* for API Extractor.
* @internal
*/
public static readonly _tsdocBaseFilePath: string = path.resolve(
__dirname,
'../../extends/tsdoc-base.json'
);
private static readonly _defaultConfig: Partial<IConfigFile> = JsonFile.load(
path.join(__dirname, '../schemas/api-extractor-defaults.json')
);
/** Match all three flavors for type declaration files (.d.ts, .d.mts, .d.cts) */
private static readonly _declarationFileExtensionRegExp: RegExp = /\.d\.(c|m)?ts$/i;
/** {@inheritDoc IConfigFile.projectFolder} */
public readonly projectFolder: string;
/**
* The parsed package.json file for the working package, or undefined if API Extractor was invoked without
* a package.json file.
*/
public readonly packageJson: INodePackageJson | undefined;
/**
* The absolute path of the folder containing the package.json file for the working package, or undefined
* if API Extractor was invoked without a package.json file.
*/
public readonly packageFolder: string | undefined;
/** {@inheritDoc IConfigFile.mainEntryPointFilePath} */
public readonly mainEntryPointFilePath: string;
/** {@inheritDoc IConfigFile.bundledPackages} */
public readonly bundledPackages: string[];
/** {@inheritDoc IConfigCompiler.tsconfigFilePath} */
public readonly tsconfigFilePath: string;
/** {@inheritDoc IConfigCompiler.overrideTsconfig} */
public readonly overrideTsconfig: {} | undefined;
/** {@inheritDoc IConfigCompiler.skipLibCheck} */
public readonly skipLibCheck: boolean;
/** {@inheritDoc IConfigApiReport.enabled} */
public readonly apiReportEnabled: boolean;
/**
* List of configurations for report files to be generated.
* @remarks Derived from {@link IConfigApiReport.reportFileName} and {@link IConfigApiReport.reportVariants}.
*/
public readonly reportConfigs: readonly IExtractorConfigApiReport[];
/** {@inheritDoc IConfigApiReport.reportFolder} */
public readonly reportFolder: string;
/** {@inheritDoc IConfigApiReport.reportTempFolder} */
public readonly reportTempFolder: string;
/** {@inheritDoc IConfigApiReport.tagsToReport} */
public readonly tagsToReport: Readonly<Record<`@${string}`, boolean>>;
/**
* Gets the file path for the "complete" (default) report configuration, if one was specified.
* Otherwise, returns an empty string.
* @deprecated Use {@link ExtractorConfig.reportConfigs} to access all report configurations.
*/
public get reportFilePath(): string {
const completeConfig: IExtractorConfigApiReport | undefined = this._getCompleteReportConfig();
return completeConfig === undefined ? '' : path.join(this.reportFolder, completeConfig.fileName);
}
/**
* Gets the temp file path for the "complete" (default) report configuration, if one was specified.
* Otherwise, returns an empty string.
* @deprecated Use {@link ExtractorConfig.reportConfigs} to access all report configurations.
*/
public get reportTempFilePath(): string {
const completeConfig: IExtractorConfigApiReport | undefined = this._getCompleteReportConfig();
return completeConfig === undefined ? '' : path.join(this.reportTempFolder, completeConfig.fileName);
}
/** {@inheritDoc IConfigApiReport.includeForgottenExports} */
public readonly apiReportIncludeForgottenExports: boolean;
/**
* If specified, the doc model is enabled and the specified options will be used.
* @beta
*/
public readonly docModelGenerationOptions: IApiModelGenerationOptions | undefined;
/** {@inheritDoc IConfigDocModel.apiJsonFilePath} */
public readonly apiJsonFilePath: string;
/** {@inheritDoc IConfigDocModel.includeForgottenExports} */
public readonly docModelIncludeForgottenExports: boolean;
/** {@inheritDoc IConfigDocModel.projectFolderUrl} */
public readonly projectFolderUrl: string | undefined;
/** {@inheritDoc IConfigDtsRollup.enabled} */
public readonly rollupEnabled: boolean;
/** {@inheritDoc IConfigDtsRollup.untrimmedFilePath} */
public readonly untrimmedFilePath: string;
/** {@inheritDoc IConfigDtsRollup.alphaTrimmedFilePath} */
public readonly alphaTrimmedFilePath: string;
/** {@inheritDoc IConfigDtsRollup.betaTrimmedFilePath} */
public readonly betaTrimmedFilePath: string;
/** {@inheritDoc IConfigDtsRollup.publicTrimmedFilePath} */
public readonly publicTrimmedFilePath: string;
/** {@inheritDoc IConfigDtsRollup.omitTrimmingComments} */
public readonly omitTrimmingComments: boolean;
/** {@inheritDoc IConfigTsdocMetadata.enabled} */
public readonly tsdocMetadataEnabled: boolean;
/** {@inheritDoc IConfigTsdocMetadata.tsdocMetadataFilePath} */
public readonly tsdocMetadataFilePath: string;
/**
* The tsdoc.json configuration that will be used when parsing doc comments.
*/
public readonly tsdocConfigFile: TSDocConfigFile;
/**
* The `TSDocConfiguration` loaded from {@link ExtractorConfig.tsdocConfigFile}.
*/
public readonly tsdocConfiguration: TSDocConfiguration;
/**
* Specifies what type of newlines API Extractor should use when writing output files. By default, the output files
* will be written with Windows-style newlines.
*/
public readonly newlineKind: NewlineKind;
/** {@inheritDoc IConfigFile.messages} */
public readonly messages: IExtractorMessagesConfig;
/** {@inheritDoc IConfigFile.testMode} */
public readonly testMode: boolean;
/** {@inheritDoc IConfigFile.enumMemberOrder} */
public readonly enumMemberOrder: EnumMemberOrder;
private constructor({
projectFolder,
packageJson,
packageFolder,
mainEntryPointFilePath,
bundledPackages,
tsconfigFilePath,
overrideTsconfig,
skipLibCheck,
apiReportEnabled,
apiReportIncludeForgottenExports,
reportConfigs,
reportFolder,
reportTempFolder,
tagsToReport,
docModelGenerationOptions,
apiJsonFilePath,
docModelIncludeForgottenExports,
projectFolderUrl,
rollupEnabled,
untrimmedFilePath,
alphaTrimmedFilePath,
betaTrimmedFilePath,
publicTrimmedFilePath,
omitTrimmingComments,
tsdocMetadataEnabled,
tsdocMetadataFilePath,
tsdocConfigFile,
tsdocConfiguration,
newlineKind,
messages,
testMode,
enumMemberOrder
}: IExtractorConfigParameters) {
this.projectFolder = projectFolder;
this.packageJson = packageJson;
this.packageFolder = packageFolder;
this.mainEntryPointFilePath = mainEntryPointFilePath;
this.bundledPackages = bundledPackages;
this.tsconfigFilePath = tsconfigFilePath;
this.overrideTsconfig = overrideTsconfig;
this.skipLibCheck = skipLibCheck;
this.apiReportEnabled = apiReportEnabled;
this.apiReportIncludeForgottenExports = apiReportIncludeForgottenExports;
this.reportConfigs = reportConfigs;
this.reportFolder = reportFolder;
this.reportTempFolder = reportTempFolder;
this.tagsToReport = tagsToReport;
this.docModelGenerationOptions = docModelGenerationOptions;
this.apiJsonFilePath = apiJsonFilePath;
this.docModelIncludeForgottenExports = docModelIncludeForgottenExports;
this.projectFolderUrl = projectFolderUrl;
this.rollupEnabled = rollupEnabled;
this.untrimmedFilePath = untrimmedFilePath;
this.alphaTrimmedFilePath = alphaTrimmedFilePath;
this.betaTrimmedFilePath = betaTrimmedFilePath;
this.publicTrimmedFilePath = publicTrimmedFilePath;
this.omitTrimmingComments = omitTrimmingComments;
this.tsdocMetadataEnabled = tsdocMetadataEnabled;
this.tsdocMetadataFilePath = tsdocMetadataFilePath;
this.tsdocConfigFile = tsdocConfigFile;
this.tsdocConfiguration = tsdocConfiguration;
this.newlineKind = newlineKind;
this.messages = messages;
this.testMode = testMode;
this.enumMemberOrder = enumMemberOrder;
}
/**
* Returns a JSON-like string representing the `ExtractorConfig` state, which can be printed to a console
* for diagnostic purposes.
*
* @remarks
* This is used by the "--diagnostics" command-line option. The string is not intended to be deserialized;
* its format may be changed at any time.
*/
public getDiagnosticDump(): string {
// Handle the simple JSON-serializable properties using buildJsonDumpObject()
const result: object = MessageRouter.buildJsonDumpObject(this, {
keyNamesToOmit: ['tsdocConfigFile', 'tsdocConfiguration']
});
// Implement custom formatting for tsdocConfigFile and tsdocConfiguration
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(result as any).tsdocConfigFile = {
filePath: this.tsdocConfigFile.filePath,
log: this.tsdocConfigFile.log.messages.map((x) => x.toString())
};
return JSON.stringify(result, undefined, 2);
}
/**
* Returns a simplified file path for use in error messages.
* @internal
*/
public _getShortFilePath(absolutePath: string): string {
if (!path.isAbsolute(absolutePath)) {
throw new InternalError('Expected absolute path: ' + absolutePath);
}
if (Path.isUnderOrEqual(absolutePath, this.projectFolder)) {
return Path.convertToSlashes(path.relative(this.projectFolder, absolutePath));
}
return absolutePath;
}
/**
* Searches for the api-extractor.json config file associated with the specified starting folder,
* and loads the file if found. This lookup supports
* {@link https://www.npmjs.com/package/@rushstack/rig-package | rig packages}.
*
* @remarks
* The search will first look for a package.json file in a parent folder of the starting folder;
* if found, that will be used as the base folder instead of the starting folder. If the config
* file is not found in `<baseFolder>/api-extractor.json` or `<baseFolder>/config/api-extractor.json`,
* then `<baseFolder/config/rig.json` will be checked to see whether a
* {@link https://www.npmjs.com/package/@rushstack/rig-package | rig package} is referenced; if so then
* the rig's api-extractor.json file will be used instead. If a config file is found, it will be loaded
* and returned with the `IExtractorConfigPrepareOptions` object. Otherwise, `undefined` is returned
* to indicate that API Extractor does not appear to be configured for the specified folder.
*
* @returns An options object that can be passed to {@link ExtractorConfig.prepare}, or `undefined`
* if not api-extractor.json file was found.
*/
public static tryLoadForFolder(
options: IExtractorConfigLoadForFolderOptions
): IExtractorConfigPrepareOptions | undefined {
const packageJsonLookup: PackageJsonLookup = options.packageJsonLookup || new PackageJsonLookup();
const startingFolder: string = options.startingFolder;
// Figure out which project we're in and look for the config file at the project root
const packageJsonFullPath: string | undefined =
packageJsonLookup.tryGetPackageJsonFilePathFor(startingFolder);
const packageFolder: string | undefined = packageJsonFullPath
? path.dirname(packageJsonFullPath)
: undefined;
// If there is no package, then just use the starting folder
const baseFolder: string = packageFolder || startingFolder;
let projectFolderLookupToken: string | undefined = undefined;
// First try the standard "config" subfolder:
let configFilename: string = path.join(baseFolder, 'config', ExtractorConfig.FILENAME);
if (FileSystem.exists(configFilename)) {
if (FileSystem.exists(path.join(baseFolder, ExtractorConfig.FILENAME))) {
throw new Error(`Found conflicting ${ExtractorConfig.FILENAME} files in "." and "./config" folders`);
}
} else {
// Otherwise try the top-level folder
configFilename = path.join(baseFolder, ExtractorConfig.FILENAME);
if (!FileSystem.exists(configFilename)) {
// If We didn't find it in <packageFolder>/api-extractor.json or <packageFolder>/config/api-extractor.json
// then check for a rig package
if (packageFolder) {
let rigConfig: IRigConfig;
if (options.rigConfig) {
// The caller provided an already solved RigConfig. Double-check that it is for the right project.
if (!Path.isEqual(options.rigConfig.projectFolderPath, packageFolder)) {
throw new Error(
'The provided ILoadForFolderOptions.rigConfig is for the wrong project folder:\n' +
'\nExpected path: ' +
packageFolder +
'\nProvided path: ' +
options.rigConfig.projectFolderOriginalPath
);
}
rigConfig = options.rigConfig;
} else {
rigConfig = RigConfig.loadForProjectFolder({
projectFolderPath: packageFolder
});
}
if (rigConfig.rigFound) {
configFilename = path.join(rigConfig.getResolvedProfileFolder(), ExtractorConfig.FILENAME);
// If the "projectFolder" setting isn't specified in api-extractor.json, it defaults to the
// "<lookup>" token which will probe for the tsconfig.json nearest to the api-extractor.json path.
// But this won't work if api-extractor.json belongs to the rig. So instead "<lookup>" should be
// the "<packageFolder>" that referenced the rig.
projectFolderLookupToken = packageFolder;
}
}
if (!FileSystem.exists(configFilename)) {
// API Extractor does not seem to be configured for this folder
return undefined;
}
}
}
const configObjectFullPath: string = path.resolve(configFilename);
const configObject: IConfigFile = ExtractorConfig.loadFile(configObjectFullPath);
return {
configObject,
configObjectFullPath,
packageJsonFullPath,
projectFolderLookupToken
};
}
/**
* Loads the api-extractor.json config file from the specified file path, and prepares an `ExtractorConfig` object.
*
* @remarks
* Loads the api-extractor.json config file from the specified file path. If the "extends" field is present,
* the referenced file(s) will be merged. For any omitted fields, the API Extractor default values are merged.
*
* The result is prepared using `ExtractorConfig.prepare()`.
*/
public static loadFileAndPrepare(configJsonFilePath: string): ExtractorConfig {
const configObjectFullPath: string = path.resolve(configJsonFilePath);
const configObject: IConfigFile = ExtractorConfig.loadFile(configObjectFullPath);
const packageJsonLookup: PackageJsonLookup = new PackageJsonLookup();
const packageJsonFullPath: string | undefined =
packageJsonLookup.tryGetPackageJsonFilePathFor(configObjectFullPath);
const extractorConfig: ExtractorConfig = ExtractorConfig.prepare({
configObject,
configObjectFullPath,
packageJsonFullPath
});
return extractorConfig;
}
/**
* Performs only the first half of {@link ExtractorConfig.loadFileAndPrepare}, providing an opportunity to
* modify the object before it is passed to {@link ExtractorConfig.prepare}.
*
* @remarks
* Loads the api-extractor.json config file from the specified file path. If the "extends" field is present,
* the referenced file(s) will be merged. For any omitted fields, the API Extractor default values are merged.
*/
public static loadFile(jsonFilePath: string): IConfigFile {
// Set to keep track of config files which have been processed.
const visitedPaths: Set<string> = new Set<string>();
let currentConfigFilePath: string = path.resolve(jsonFilePath);
let configObject: Partial<IConfigFile> = {};
// Lodash merges array values by default, which is unintuitive for config files (and makes it impossible for derived configurations to overwrite arrays).
// For example, given a base config containing an array property with value ["foo", "bar"] and a derived config that specifies ["baz"] for that property, lodash will produce ["baz", "bar"], which is unintuitive.
// This customizer function ensures that arrays are always overwritten.
const mergeCustomizer: lodash.MergeWithCustomizer = (objValue, srcValue) => {
if (Array.isArray(srcValue)) {
return srcValue;
}
// Fall back to default merge behavior.
return undefined;
};
try {
do {
// Check if this file was already processed.
if (visitedPaths.has(currentConfigFilePath)) {
throw new Error(
`The API Extractor "extends" setting contains a cycle.` +
` This file is included twice: "${currentConfigFilePath}"`
);
}
visitedPaths.add(currentConfigFilePath);
const currentConfigFolderPath: string = path.dirname(currentConfigFilePath);
// Load the extractor config defined in extends property.
const baseConfig: IConfigFile = JsonFile.load(currentConfigFilePath);
let extendsField: string = baseConfig.extends || '';
// Delete the "extends" field so it doesn't get merged
delete baseConfig.extends;
if (extendsField) {
if (extendsField.match(/^\.\.?[\\/]/)) {
// EXAMPLE: "./subfolder/api-extractor-base.json"
extendsField = path.resolve(currentConfigFolderPath, extendsField);
} else {
// EXAMPLE: "my-package/api-extractor-base.json"
//
// Resolve "my-package" from the perspective of the current folder.
try {
extendsField = resolve.sync(extendsField, {
basedir: currentConfigFolderPath
});
} catch (e) {
throw new Error(`Error resolving NodeJS path "${extendsField}": ${(e as Error).message}`);
}
}
}
// This step has to be performed in advance, since the currentConfigFolderPath information will be lost
// after lodash.merge() is performed.
ExtractorConfig._resolveConfigFileRelativePaths(baseConfig, currentConfigFolderPath);
// Merge extractorConfig into baseConfig, mutating baseConfig
lodash.mergeWith(baseConfig, configObject, mergeCustomizer);
configObject = baseConfig;
currentConfigFilePath = extendsField;
} while (currentConfigFilePath);
} catch (e) {
throw new Error(`Error loading ${currentConfigFilePath}:\n` + (e as Error).message);
}
// Lastly, apply the defaults
configObject = lodash.mergeWith(
lodash.cloneDeep(ExtractorConfig._defaultConfig),
configObject,
mergeCustomizer
);
ExtractorConfig.jsonSchema.validateObject(configObject, jsonFilePath);
// The schema validation should ensure that this object conforms to IConfigFile
return configObject as IConfigFile;
}
private static _resolveConfigFileRelativePaths(
configFile: IConfigFile,
currentConfigFolderPath: string
): void {
if (configFile.projectFolder) {
configFile.projectFolder = ExtractorConfig._resolveConfigFileRelativePath(
'projectFolder',
configFile.projectFolder,
currentConfigFolderPath
);
}
if (configFile.mainEntryPointFilePath) {
configFile.mainEntryPointFilePath = ExtractorConfig._resolveConfigFileRelativePath(
'mainEntryPointFilePath',
configFile.mainEntryPointFilePath,
currentConfigFolderPath
);
}
if (configFile.compiler) {
if (configFile.compiler.tsconfigFilePath) {
configFile.compiler.tsconfigFilePath = ExtractorConfig._resolveConfigFileRelativePath(
'tsconfigFilePath',
configFile.compiler.tsconfigFilePath,
currentConfigFolderPath
);
}
}
if (configFile.apiReport) {
if (configFile.apiReport.reportFolder) {
configFile.apiReport.reportFolder = ExtractorConfig._resolveConfigFileRelativePath(
'reportFolder',
configFile.apiReport.reportFolder,
currentConfigFolderPath
);
}
if (configFile.apiReport.reportTempFolder) {
configFile.apiReport.reportTempFolder = ExtractorConfig._resolveConfigFileRelativePath(
'reportTempFolder',
configFile.apiReport.reportTempFolder,
currentConfigFolderPath
);
}
}
if (configFile.docModel) {
if (configFile.docModel.apiJsonFilePath) {
configFile.docModel.apiJsonFilePath = ExtractorConfig._resolveConfigFileRelativePath(
'apiJsonFilePath',
configFile.docModel.apiJsonFilePath,
currentConfigFolderPath
);
}
}
if (configFile.dtsRollup) {
if (configFile.dtsRollup.untrimmedFilePath) {
configFile.dtsRollup.untrimmedFilePath = ExtractorConfig._resolveConfigFileRelativePath(
'untrimmedFilePath',
configFile.dtsRollup.untrimmedFilePath,
currentConfigFolderPath
);
}
if (configFile.dtsRollup.alphaTrimmedFilePath) {
configFile.dtsRollup.alphaTrimmedFilePath = ExtractorConfig._resolveConfigFileRelativePath(
'alphaTrimmedFilePath',
configFile.dtsRollup.alphaTrimmedFilePath,
currentConfigFolderPath
);
}
if (configFile.dtsRollup.betaTrimmedFilePath) {
configFile.dtsRollup.betaTrimmedFilePath = ExtractorConfig._resolveConfigFileRelativePath(
'betaTrimmedFilePath',
configFile.dtsRollup.betaTrimmedFilePath,
currentConfigFolderPath
);
}
if (configFile.dtsRollup.publicTrimmedFilePath) {
configFile.dtsRollup.publicTrimmedFilePath = ExtractorConfig._resolveConfigFileRelativePath(
'publicTrimmedFilePath',
configFile.dtsRollup.publicTrimmedFilePath,
currentConfigFolderPath
);
}
}
if (configFile.tsdocMetadata) {
if (configFile.tsdocMetadata.tsdocMetadataFilePath) {
configFile.tsdocMetadata.tsdocMetadataFilePath = ExtractorConfig._resolveConfigFileRelativePath(
'tsdocMetadataFilePath',
configFile.tsdocMetadata.tsdocMetadataFilePath,
currentConfigFolderPath
);
}
}
}
private static _resolveConfigFileRelativePath(
fieldName: string,
fieldValue: string,
currentConfigFolderPath: string
): string {
if (!path.isAbsolute(fieldValue)) {
if (fieldValue.indexOf('<projectFolder>') !== 0) {
// If the path is not absolute and does not start with "<projectFolder>", then resolve it relative
// to the folder of the config file that it appears in
return path.join(currentConfigFolderPath, fieldValue);
}
}
return fieldValue;
}
/**
* Prepares an `ExtractorConfig` object using a configuration that is provided as a runtime object,
* rather than reading it from disk. This allows configurations to be constructed programmatically,
* loaded from an alternate source, and/or customized after loading.
*/
public static prepare(options: IExtractorConfigPrepareOptions): ExtractorConfig {
const filenameForErrors: string = options.configObjectFullPath || 'the configuration object';
const configObject: Partial<IConfigFile> = options.configObject;
if (configObject.extends) {
throw new Error(
'The IConfigFile.extends field must be expanded before calling ExtractorConfig.prepare()'
);
}
if (options.configObjectFullPath) {
if (!path.isAbsolute(options.configObjectFullPath)) {
throw new Error('The "configObjectFullPath" setting must be an absolute path');
}
}
ExtractorConfig.jsonSchema.validateObject(configObject, filenameForErrors);
const packageJsonFullPath: string | undefined = options.packageJsonFullPath;
let packageFolder: string | undefined = undefined;
let packageJson: INodePackageJson | undefined = undefined;
if (packageJsonFullPath) {
if (!/.json$/i.test(packageJsonFullPath)) {
// Catch common mistakes e.g. where someone passes a folder path instead of a file path
throw new Error('The "packageJsonFullPath" setting does not have a .json file extension');
}
if (!path.isAbsolute(packageJsonFullPath)) {
throw new Error('The "packageJsonFullPath" setting must be an absolute path');
}
if (options.packageJson) {
packageJson = options.packageJson;
} else {
const packageJsonLookup: PackageJsonLookup = new PackageJsonLookup();
packageJson = packageJsonLookup.loadNodePackageJson(packageJsonFullPath);
}
packageFolder = path.dirname(packageJsonFullPath);
}
// "tsdocConfigFile" and "tsdocConfiguration" are prepared outside the try-catch block,
// so that if exceptions are thrown, it will not get the "Error parsing api-extractor.json:" header
let extractorConfigParameters: Omit<IExtractorConfigParameters, 'tsdocConfigFile' | 'tsdocConfiguration'>;
try {
if (!configObject.compiler) {
// A merged configuration should have this
throw new Error('The "compiler" section is missing');
}
if (!configObject.projectFolder) {
// A merged configuration should have this
throw new Error('The "projectFolder" setting is missing');
}
let projectFolder: string;
if (configObject.projectFolder.trim() === '<lookup>') {
if (options.projectFolderLookupToken) {
// Use the manually specified "<lookup>" value
projectFolder = options.projectFolderLookupToken;
if (!FileSystem.exists(options.projectFolderLookupToken)) {
throw new Error(
'The specified "projectFolderLookupToken" path does not exist: ' +
options.projectFolderLookupToken
);
}
} else {
if (!options.configObjectFullPath) {
throw new Error(
'The "projectFolder" setting uses the "<lookup>" token, but it cannot be expanded because' +
' the "configObjectFullPath" setting was not specified'
);
}
// "The default value for `projectFolder` is the token `<lookup>`, which means the folder is determined
// by traversing parent folders, starting from the folder containing api-extractor.json, and stopping
// at the first folder that contains a tsconfig.json file. If a tsconfig.json file cannot be found in
// this way, then an error will be reported."
let currentFolder: string = path.dirname(options.configObjectFullPath);
for (;;) {
const tsconfigPath: string = path.join(currentFolder, 'tsconfig.json');
if (FileSystem.exists(tsconfigPath)) {
projectFolder = currentFolder;
break;
}
const parentFolder: string = path.dirname(currentFolder);
if (parentFolder === '' || parentFolder === currentFolder) {
throw new Error(
'The "projectFolder" setting uses the "<lookup>" token, but a tsconfig.json file cannot be' +
' found in this folder or any parent folder.'
);
}
currentFolder = parentFolder;
}
}
} else {
ExtractorConfig._rejectAnyTokensInPath(configObject.projectFolder, 'projectFolder');
if (!FileSystem.exists(configObject.projectFolder)) {
throw new Error('The specified "projectFolder" path does not exist: ' + configObject.projectFolder);
}
projectFolder = configObject.projectFolder;
}
const tokenContext: IExtractorConfigTokenContext = {
unscopedPackageName: 'unknown-package',
packageName: 'unknown-package',
projectFolder: projectFolder
};
if (packageJson) {
tokenContext.packageName = packageJson.name;
tokenContext.unscopedPackageName = PackageName.getUnscopedName(packageJson.name);
}
if (!configObject.mainEntryPointFilePath) {
// A merged configuration should have this
throw new Error('The "mainEntryPointFilePath" setting is missing');
}
const mainEntryPointFilePath: string = ExtractorConfig._resolvePathWithTokens(
'mainEntryPointFilePath',
configObject.mainEntryPointFilePath,
tokenContext
);
if (!ExtractorConfig.hasDtsFileExtension(mainEntryPointFilePath)) {
throw new Error(
'The "mainEntryPointFilePath" value is not a declaration file: ' + mainEntryPointFilePath
);
}
if (!options.ignoreMissingEntryPoint && !FileSystem.exists(mainEntryPointFilePath)) {
throw new Error('The "mainEntryPointFilePath" path does not exist: ' + mainEntryPointFilePath);
}
const bundledPackages: string[] = configObject.bundledPackages || [];
// Note: we cannot fully validate package name patterns, as the strings may contain wildcards.
// We won't know if the entries are valid until we can compare them against the package.json "dependencies" contents.
const tsconfigFilePath: string = ExtractorConfig._resolvePathWithTokens(
'tsconfigFilePath',
configObject.compiler.tsconfigFilePath,
tokenContext
);
if (configObject.compiler.overrideTsconfig === undefined) {
if (!tsconfigFilePath) {
throw new Error('Either the "tsconfigFilePath" or "overrideTsconfig" setting must be specified');
}
if (!FileSystem.exists(tsconfigFilePath)) {
throw new Error('The file referenced by "tsconfigFilePath" does not exist: ' + tsconfigFilePath);
}
}
if (configObject.apiReport?.tagsToReport) {
_validateTagsToReport(configObject.apiReport.tagsToReport);
}
const apiReportEnabled: boolean = configObject.apiReport?.enabled ?? false;
const apiReportIncludeForgottenExports: boolean =
configObject.apiReport?.includeForgottenExports ?? false;
let reportFolder: string = tokenContext.projectFolder;
let reportTempFolder: string = tokenContext.projectFolder;
const reportConfigs: IExtractorConfigApiReport[] = [];
let tagsToReport: Record<`@${string}`, boolean> = {};
if (apiReportEnabled) {
// Undefined case checked above where we assign `apiReportEnabled`
const apiReportConfig: IConfigApiReport = configObject.apiReport!;