mirror of
https://github.com/microsoft/TypeScript.git
synced 2025-11-18 17:21:48 +00:00
Merge pull request #22167 from Microsoft/requireJson
Resolve the modue names with "modulename.json" to json files when doing node module resolution
This commit is contained in:
@@ -281,6 +281,10 @@ namespace ts {
|
||||
return InternalSymbolName.Index;
|
||||
case SyntaxKind.ExportDeclaration:
|
||||
return InternalSymbolName.ExportStar;
|
||||
case SyntaxKind.SourceFile:
|
||||
// json file should behave as
|
||||
// module.exports = ...
|
||||
return InternalSymbolName.ExportEquals;
|
||||
case SyntaxKind.BinaryExpression:
|
||||
if (getSpecialPropertyAssignmentKind(node as BinaryExpression) === SpecialPropertyAssignmentKind.ModuleExports) {
|
||||
// module.exports = ...
|
||||
@@ -2234,6 +2238,13 @@ namespace ts {
|
||||
if (isExternalModule(file)) {
|
||||
bindSourceFileAsExternalModule();
|
||||
}
|
||||
else if (isJsonSourceFile(file)) {
|
||||
bindSourceFileAsExternalModule();
|
||||
// Create symbol equivalent for the module.exports = {}
|
||||
const originalSymbol = file.symbol;
|
||||
declareSymbol(file.symbol.exports, file.symbol, file, SymbolFlags.Property, SymbolFlags.All);
|
||||
file.symbol = originalSymbol;
|
||||
}
|
||||
}
|
||||
|
||||
function bindSourceFileAsExternalModule() {
|
||||
|
||||
@@ -2207,7 +2207,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
// May be an untyped module. If so, ignore resolutionDiagnostic.
|
||||
if (resolvedModule && !extensionIsTypeScript(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) {
|
||||
if (resolvedModule && !resolutionExtensionIsTypeScriptOrJson(resolvedModule.extension) && resolutionDiagnostic === undefined || resolutionDiagnostic === Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type) {
|
||||
if (isForAugmentation) {
|
||||
const diag = Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
|
||||
error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
|
||||
@@ -4718,6 +4718,10 @@ namespace ts {
|
||||
return links.type = anyType;
|
||||
}
|
||||
// Handle export default expressions
|
||||
if (isSourceFile(declaration)) {
|
||||
const jsonSourceFile = cast(declaration, isJsonSourceFile);
|
||||
return links.type = jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType;
|
||||
}
|
||||
if (declaration.kind === SyntaxKind.ExportAssignment) {
|
||||
return links.type = checkExpression((<ExportAssignment>declaration).expression);
|
||||
}
|
||||
@@ -15597,7 +15601,7 @@ namespace ts {
|
||||
const contextualType = getApparentTypeOfContextualType(node);
|
||||
const contextualTypeHasPattern = contextualType && contextualType.pattern &&
|
||||
(contextualType.pattern.kind === SyntaxKind.ObjectBindingPattern || contextualType.pattern.kind === SyntaxKind.ObjectLiteralExpression);
|
||||
const isInJSFile = isInJavaScriptFile(node);
|
||||
const isInJSFile = isInJavaScriptFile(node) && !isInJsonFile(node);
|
||||
const isJSObjectLiteral = !contextualType && isInJSFile;
|
||||
let typeFlags: TypeFlags = 0;
|
||||
let patternWithComputedProperties = false;
|
||||
|
||||
@@ -501,6 +501,12 @@ namespace ts {
|
||||
category: Diagnostics.Advanced_Options,
|
||||
description: Diagnostics.Enable_tracing_of_the_name_resolution_process
|
||||
},
|
||||
{
|
||||
name: "resolveJsonModule",
|
||||
type: "boolean",
|
||||
category: Diagnostics.Advanced_Options,
|
||||
description: Diagnostics.Include_modules_imported_with_json_extension
|
||||
},
|
||||
{
|
||||
name: "listFiles",
|
||||
type: "boolean",
|
||||
@@ -953,9 +959,9 @@ namespace ts {
|
||||
* Read tsconfig.json file
|
||||
* @param fileName The path to the config file
|
||||
*/
|
||||
export function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): JsonSourceFile {
|
||||
export function readJsonConfigFile(fileName: string, readFile: (path: string) => string | undefined): TsConfigSourceFile {
|
||||
const textOrDiagnostic = tryReadFile(fileName, readFile);
|
||||
return isString(textOrDiagnostic) ? parseJsonText(fileName, textOrDiagnostic) : <JsonSourceFile>{ parseDiagnostics: [textOrDiagnostic] };
|
||||
return isString(textOrDiagnostic) ? parseJsonText(fileName, textOrDiagnostic) : <TsConfigSourceFile>{ parseDiagnostics: [textOrDiagnostic] };
|
||||
}
|
||||
|
||||
function tryReadFile(fileName: string, readFile: (path: string) => string | undefined): string | Diagnostic {
|
||||
@@ -973,58 +979,62 @@ namespace ts {
|
||||
return arrayToMap(options, option => option.name);
|
||||
}
|
||||
|
||||
let _tsconfigRootOptions: Map<CommandLineOption>;
|
||||
let _tsconfigRootOptions: TsConfigOnlyOption;
|
||||
function getTsconfigRootOptionsMap() {
|
||||
if (_tsconfigRootOptions === undefined) {
|
||||
_tsconfigRootOptions = commandLineOptionsToMap([
|
||||
{
|
||||
name: "compilerOptions",
|
||||
type: "object",
|
||||
elementOptions: commandLineOptionsToMap(optionDeclarations),
|
||||
extraKeyDiagnosticMessage: Diagnostics.Unknown_compiler_option_0
|
||||
},
|
||||
{
|
||||
name: "typingOptions",
|
||||
type: "object",
|
||||
elementOptions: commandLineOptionsToMap(typeAcquisitionDeclarations),
|
||||
extraKeyDiagnosticMessage: Diagnostics.Unknown_type_acquisition_option_0
|
||||
},
|
||||
{
|
||||
name: "typeAcquisition",
|
||||
type: "object",
|
||||
elementOptions: commandLineOptionsToMap(typeAcquisitionDeclarations),
|
||||
extraKeyDiagnosticMessage: Diagnostics.Unknown_type_acquisition_option_0
|
||||
},
|
||||
{
|
||||
name: "extends",
|
||||
type: "string"
|
||||
},
|
||||
{
|
||||
name: "files",
|
||||
type: "list",
|
||||
element: {
|
||||
_tsconfigRootOptions = {
|
||||
name: undefined, // should never be needed since this is root
|
||||
type: "object",
|
||||
elementOptions: commandLineOptionsToMap([
|
||||
{
|
||||
name: "compilerOptions",
|
||||
type: "object",
|
||||
elementOptions: commandLineOptionsToMap(optionDeclarations),
|
||||
extraKeyDiagnosticMessage: Diagnostics.Unknown_compiler_option_0
|
||||
},
|
||||
{
|
||||
name: "typingOptions",
|
||||
type: "object",
|
||||
elementOptions: commandLineOptionsToMap(typeAcquisitionDeclarations),
|
||||
extraKeyDiagnosticMessage: Diagnostics.Unknown_type_acquisition_option_0
|
||||
},
|
||||
{
|
||||
name: "typeAcquisition",
|
||||
type: "object",
|
||||
elementOptions: commandLineOptionsToMap(typeAcquisitionDeclarations),
|
||||
extraKeyDiagnosticMessage: Diagnostics.Unknown_type_acquisition_option_0
|
||||
},
|
||||
{
|
||||
name: "extends",
|
||||
type: "string"
|
||||
},
|
||||
{
|
||||
name: "files",
|
||||
type: "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "include",
|
||||
type: "list",
|
||||
element: {
|
||||
type: "list",
|
||||
element: {
|
||||
name: "files",
|
||||
type: "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "include",
|
||||
type: "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "exclude",
|
||||
type: "list",
|
||||
element: {
|
||||
type: "list",
|
||||
element: {
|
||||
name: "include",
|
||||
type: "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "exclude",
|
||||
type: "string"
|
||||
}
|
||||
},
|
||||
compileOnSaveCommandLineOption
|
||||
]);
|
||||
type: "list",
|
||||
element: {
|
||||
name: "exclude",
|
||||
type: "string"
|
||||
}
|
||||
},
|
||||
compileOnSaveCommandLineOption
|
||||
])
|
||||
};
|
||||
}
|
||||
return _tsconfigRootOptions;
|
||||
}
|
||||
@@ -1061,23 +1071,30 @@ namespace ts {
|
||||
* Convert the json syntax tree into the json value
|
||||
*/
|
||||
export function convertToObject(sourceFile: JsonSourceFile, errors: Push<Diagnostic>): any {
|
||||
return convertToObjectWorker(sourceFile, errors, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
|
||||
return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert the json syntax tree into the json value
|
||||
* Convert the json syntax tree into the json value and report errors
|
||||
* This returns the json value (apart from checking errors) only if returnValue provided is true.
|
||||
* Otherwise it just checks the errors and returns undefined
|
||||
*/
|
||||
function convertToObjectWorker(
|
||||
/*@internal*/
|
||||
export function convertToObjectWorker(
|
||||
sourceFile: JsonSourceFile,
|
||||
errors: Push<Diagnostic>,
|
||||
knownRootOptions: Map<CommandLineOption> | undefined,
|
||||
returnValue: boolean,
|
||||
knownRootOptions: CommandLineOption | undefined,
|
||||
jsonConversionNotifier: JsonConversionNotifier | undefined): any {
|
||||
if (!sourceFile.jsonObject) {
|
||||
return {};
|
||||
if (!sourceFile.statements.length) {
|
||||
return returnValue ? {} : undefined;
|
||||
}
|
||||
|
||||
return convertObjectLiteralExpressionToJson(sourceFile.jsonObject, knownRootOptions,
|
||||
/*extraKeyDiagnosticMessage*/ undefined, /*parentOption*/ undefined);
|
||||
return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions);
|
||||
|
||||
function isRootOptionMap(knownOptions: Map<CommandLineOption> | undefined) {
|
||||
return knownRootOptions && (knownRootOptions as TsConfigOnlyOption).elementOptions === knownOptions;
|
||||
}
|
||||
|
||||
function convertObjectLiteralExpressionToJson(
|
||||
node: ObjectLiteralExpression,
|
||||
@@ -1085,7 +1102,7 @@ namespace ts {
|
||||
extraKeyDiagnosticMessage: DiagnosticMessage | undefined,
|
||||
parentOption: string | undefined
|
||||
): any {
|
||||
const result: any = {};
|
||||
const result: any = returnValue ? {} : undefined;
|
||||
for (const element of node.properties) {
|
||||
if (element.kind !== SyntaxKind.PropertyAssignment) {
|
||||
errors.push(createDiagnosticForNodeInSourceFile(sourceFile, element, Diagnostics.Property_assignment_expected));
|
||||
@@ -1106,11 +1123,13 @@ namespace ts {
|
||||
}
|
||||
const value = convertPropertyValueToJson(element.initializer, option);
|
||||
if (typeof keyText !== "undefined") {
|
||||
result[keyText] = value;
|
||||
if (returnValue) {
|
||||
result[keyText] = value;
|
||||
}
|
||||
// Notify key value set, if user asked for it
|
||||
if (jsonConversionNotifier &&
|
||||
// Current callbacks are only on known parent option or if we are setting values in the root
|
||||
(parentOption || knownOptions === knownRootOptions)) {
|
||||
(parentOption || isRootOptionMap(knownOptions))) {
|
||||
const isValidOptionValue = isCompilerOptionsValue(option, value);
|
||||
if (parentOption) {
|
||||
if (isValidOptionValue) {
|
||||
@@ -1118,7 +1137,7 @@ namespace ts {
|
||||
jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value);
|
||||
}
|
||||
}
|
||||
else if (knownOptions === knownRootOptions) {
|
||||
else if (isRootOptionMap(knownOptions)) {
|
||||
if (isValidOptionValue) {
|
||||
// Notify about the valid root key value being set
|
||||
jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
|
||||
@@ -1137,8 +1156,8 @@ namespace ts {
|
||||
function convertArrayLiteralExpressionToJson(
|
||||
elements: NodeArray<Expression>,
|
||||
elementOption: CommandLineOption | undefined
|
||||
): any[] {
|
||||
return elements.map(element => convertPropertyValueToJson(element, elementOption));
|
||||
): any[] | void {
|
||||
return (returnValue ? elements.map : elements.forEach).call(elements, (element: Expression) => convertPropertyValueToJson(element, elementOption));
|
||||
}
|
||||
|
||||
function convertPropertyValueToJson(valueExpression: Expression, option: CommandLineOption): any {
|
||||
@@ -1433,12 +1452,12 @@ namespace ts {
|
||||
* @param basePath A root directory to resolve relative path entries in the config
|
||||
* file to. e.g. outDir
|
||||
*/
|
||||
export function parseJsonSourceFileConfigFileContent(sourceFile: JsonSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray<FileExtensionInfo>): ParsedCommandLine {
|
||||
export function parseJsonSourceFileConfigFileContent(sourceFile: TsConfigSourceFile, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[], extraFileExtensions?: ReadonlyArray<FileExtensionInfo>): ParsedCommandLine {
|
||||
return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions);
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export function setConfigFileInOptions(options: CompilerOptions, configFile: JsonSourceFile) {
|
||||
export function setConfigFileInOptions(options: CompilerOptions, configFile: TsConfigSourceFile) {
|
||||
if (configFile) {
|
||||
Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile });
|
||||
}
|
||||
@@ -1466,7 +1485,7 @@ namespace ts {
|
||||
*/
|
||||
function parseJsonConfigFileContentWorker(
|
||||
json: any,
|
||||
sourceFile: JsonSourceFile,
|
||||
sourceFile: TsConfigSourceFile,
|
||||
host: ParseConfigHost,
|
||||
basePath: string,
|
||||
existingOptions: CompilerOptions = {},
|
||||
@@ -1587,7 +1606,7 @@ namespace ts {
|
||||
*/
|
||||
function parseConfig(
|
||||
json: any,
|
||||
sourceFile: JsonSourceFile,
|
||||
sourceFile: TsConfigSourceFile,
|
||||
host: ParseConfigHost,
|
||||
basePath: string,
|
||||
configFileName: string,
|
||||
@@ -1664,7 +1683,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function parseOwnConfigOfJsonSourceFile(
|
||||
sourceFile: JsonSourceFile,
|
||||
sourceFile: TsConfigSourceFile,
|
||||
host: ParseConfigHost,
|
||||
basePath: string,
|
||||
configFileName: string | undefined,
|
||||
@@ -1711,7 +1730,7 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
};
|
||||
const json = convertToObjectWorker(sourceFile, errors, getTsconfigRootOptionsMap(), optionsIterator);
|
||||
const json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator);
|
||||
if (!typeAcquisition) {
|
||||
if (typingOptionstypeAcquisition) {
|
||||
typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
|
||||
@@ -1754,7 +1773,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function getExtendedConfig(
|
||||
sourceFile: JsonSourceFile,
|
||||
sourceFile: TsConfigSourceFile,
|
||||
extendedConfigPath: string,
|
||||
host: ParseConfigHost,
|
||||
basePath: string,
|
||||
@@ -2006,7 +2025,7 @@ namespace ts {
|
||||
host: ParseConfigHost,
|
||||
errors: Push<Diagnostic>,
|
||||
extraFileExtensions: ReadonlyArray<FileExtensionInfo>,
|
||||
jsonSourceFile: JsonSourceFile
|
||||
jsonSourceFile: TsConfigSourceFile
|
||||
): ExpandResult {
|
||||
basePath = normalizePath(basePath);
|
||||
let validatedIncludeSpecs: ReadonlyArray<string>, validatedExcludeSpecs: ReadonlyArray<string>;
|
||||
@@ -2107,7 +2126,7 @@ namespace ts {
|
||||
};
|
||||
}
|
||||
|
||||
function validateSpecs(specs: ReadonlyArray<string>, errors: Push<Diagnostic>, allowTrailingRecursion: boolean, jsonSourceFile: JsonSourceFile, specKey: string): ReadonlyArray<string> {
|
||||
function validateSpecs(specs: ReadonlyArray<string>, errors: Push<Diagnostic>, allowTrailingRecursion: boolean, jsonSourceFile: TsConfigSourceFile, specKey: string): ReadonlyArray<string> {
|
||||
return specs.filter(spec => {
|
||||
const diag = specToDiagnostic(spec, allowTrailingRecursion);
|
||||
if (diag !== undefined) {
|
||||
@@ -2117,18 +2136,10 @@ namespace ts {
|
||||
});
|
||||
|
||||
function createDiagnostic(message: DiagnosticMessage, spec: string): Diagnostic {
|
||||
if (jsonSourceFile && jsonSourceFile.jsonObject) {
|
||||
for (const property of getPropertyAssignment(jsonSourceFile.jsonObject, specKey)) {
|
||||
if (isArrayLiteralExpression(property.initializer)) {
|
||||
for (const element of property.initializer.elements) {
|
||||
if (isStringLiteral(element) && element.text === spec) {
|
||||
return createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return createCompilerDiagnostic(message, spec);
|
||||
const element = getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
|
||||
return element ?
|
||||
createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
|
||||
createCompilerDiagnostic(message, spec);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2966,7 +2966,7 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
const extensionsToRemove = [Extension.Dts, Extension.Ts, Extension.Js, Extension.Tsx, Extension.Jsx];
|
||||
const extensionsToRemove = [Extension.Dts, Extension.Ts, Extension.Js, Extension.Tsx, Extension.Jsx, Extension.Json];
|
||||
export function removeFileExtension(path: string): string {
|
||||
for (const ext of extensionsToRemove) {
|
||||
const extensionless = tryRemoveExtension(path, ext);
|
||||
@@ -3307,6 +3307,10 @@ namespace ts {
|
||||
return ext === Extension.Ts || ext === Extension.Tsx || ext === Extension.Dts;
|
||||
}
|
||||
|
||||
export function resolutionExtensionIsTypeScriptOrJson(ext: Extension) {
|
||||
return extensionIsTypeScript(ext) || ext === Extension.Json;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the extension from a path.
|
||||
* Path must have a valid extension.
|
||||
|
||||
@@ -2806,6 +2806,10 @@
|
||||
"category": "Error",
|
||||
"code": 5069
|
||||
},
|
||||
"Option '--resolveJsonModule' cannot be specified without 'node' module resolution strategy.": {
|
||||
"category": "Error",
|
||||
"code": 5070
|
||||
},
|
||||
|
||||
"Generates a sourcemap for each corresponding '.d.ts' file.": {
|
||||
"category": "Message",
|
||||
@@ -3543,6 +3547,11 @@
|
||||
"code": 6196,
|
||||
"reportsUnnecessary": true
|
||||
},
|
||||
"Include modules imported with '.json' extension": {
|
||||
"category": "Message",
|
||||
"code": 6197
|
||||
},
|
||||
|
||||
"Variable '{0}' implicitly has an '{1}' type.": {
|
||||
"category": "Error",
|
||||
"code": 7005
|
||||
|
||||
@@ -67,6 +67,10 @@ namespace ts {
|
||||
// For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
|
||||
/* @internal */
|
||||
export function getOutputExtension(sourceFile: SourceFile, options: CompilerOptions): Extension {
|
||||
if (isJsonSourceFile(sourceFile)) {
|
||||
return Extension.Json;
|
||||
}
|
||||
|
||||
if (options.jsx === JsxEmit.Preserve) {
|
||||
if (isSourceFileJavaScript(sourceFile)) {
|
||||
if (fileExtensionIs(sourceFile.fileName, Extension.Jsx)) {
|
||||
@@ -1682,7 +1686,9 @@ namespace ts {
|
||||
|
||||
function emitExpressionStatement(node: ExpressionStatement) {
|
||||
emitExpression(node.expression);
|
||||
writeSemicolon();
|
||||
if (!isJsonSourceFile(currentSourceFile)) {
|
||||
writeSemicolon();
|
||||
}
|
||||
}
|
||||
|
||||
function emitIfStatement(node: IfStatement) {
|
||||
|
||||
@@ -24,10 +24,8 @@ namespace ts {
|
||||
if (!elements || elements === emptyArray) {
|
||||
elements = [];
|
||||
}
|
||||
else {
|
||||
if (isNodeArray(elements)) {
|
||||
return elements;
|
||||
}
|
||||
else if (isNodeArray(elements)) {
|
||||
return elements;
|
||||
}
|
||||
|
||||
const array = <NodeArray<T>>elements;
|
||||
|
||||
@@ -45,6 +45,7 @@ namespace ts {
|
||||
enum Extensions {
|
||||
TypeScript, /** '.ts', '.tsx', or '.d.ts' */
|
||||
JavaScript, /** '.js' or '.jsx' */
|
||||
Json, /** '.json' */
|
||||
DtsOnly /** Only '.d.ts' */
|
||||
}
|
||||
|
||||
@@ -746,7 +747,11 @@ namespace ts {
|
||||
const failedLookupLocations: string[] = [];
|
||||
const state: ModuleResolutionState = { compilerOptions, host, traceEnabled };
|
||||
|
||||
const result = jsOnly ? tryResolve(Extensions.JavaScript) : (tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript));
|
||||
const result = jsOnly ?
|
||||
tryResolve(Extensions.JavaScript) :
|
||||
(tryResolve(Extensions.TypeScript) ||
|
||||
tryResolve(Extensions.JavaScript) ||
|
||||
(compilerOptions.resolveJsonModule ? tryResolve(Extensions.Json) : undefined));
|
||||
if (result && result.value) {
|
||||
const { resolved, originalPath, isExternalLibraryImport } = result.value;
|
||||
return createResolvedModuleWithFailedLookupLocations(resolved, originalPath, isExternalLibraryImport, failedLookupLocations);
|
||||
@@ -898,6 +903,11 @@ namespace ts {
|
||||
* in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations.
|
||||
*/
|
||||
function loadModuleFromFile(extensions: Extensions, candidate: string, failedLookupLocations: Push<string>, onlyRecordFailures: boolean, state: ModuleResolutionState): PathAndExtension | undefined {
|
||||
if (extensions === Extensions.Json) {
|
||||
const extensionLess = tryRemoveExtension(candidate, Extension.Json);
|
||||
return extensionLess && tryAddingExtensions(extensionLess, extensions, failedLookupLocations, onlyRecordFailures, state);
|
||||
}
|
||||
|
||||
// First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
|
||||
const resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocations, onlyRecordFailures, state);
|
||||
if (resolvedByAddingExtension) {
|
||||
@@ -933,6 +943,8 @@ namespace ts {
|
||||
return tryExtension(Extension.Ts) || tryExtension(Extension.Tsx) || tryExtension(Extension.Dts);
|
||||
case Extensions.JavaScript:
|
||||
return tryExtension(Extension.Js) || tryExtension(Extension.Jsx);
|
||||
case Extensions.Json:
|
||||
return tryExtension(Extension.Json);
|
||||
}
|
||||
|
||||
function tryExtension(ext: Extension): PathAndExtension | undefined {
|
||||
@@ -1030,7 +1042,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function loadModuleFromPackageJson(jsonContent: PackageJsonPathFields, extensions: Extensions, candidate: string, failedLookupLocations: Push<string>, state: ModuleResolutionState): PathAndExtension | undefined {
|
||||
const file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript, jsonContent, candidate, state);
|
||||
const file = tryReadPackageJsonFields(extensions !== Extensions.JavaScript && extensions !== Extensions.Json, jsonContent, candidate, state);
|
||||
if (!file) {
|
||||
return undefined;
|
||||
}
|
||||
@@ -1069,6 +1081,8 @@ namespace ts {
|
||||
switch (extensions) {
|
||||
case Extensions.JavaScript:
|
||||
return extension === Extension.Js || extension === Extension.Jsx;
|
||||
case Extensions.Json:
|
||||
return extension === Extension.Json;
|
||||
case Extensions.TypeScript:
|
||||
return extension === Extension.Ts || extension === Extension.Tsx || extension === Extension.Dts;
|
||||
case Extensions.DtsOnly:
|
||||
@@ -1144,7 +1158,7 @@ namespace ts {
|
||||
if (packageResult) {
|
||||
return packageResult;
|
||||
}
|
||||
if (extensions !== Extensions.JavaScript) {
|
||||
if (extensions !== Extensions.JavaScript && extensions !== Extensions.Json) {
|
||||
const nodeModulesAtTypes = combinePaths(nodeModulesFolder, "@types");
|
||||
let nodeModulesAtTypesExists = nodeModulesFolderExists;
|
||||
if (nodeModulesFolderExists && !directoryProbablyExists(nodeModulesAtTypes, state.host)) {
|
||||
|
||||
+50
-9
@@ -670,6 +670,13 @@ namespace ts {
|
||||
|
||||
export function parseSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, syntaxCursor: IncrementalParser.SyntaxCursor, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile {
|
||||
scriptKind = ensureScriptKind(fileName, scriptKind);
|
||||
if (scriptKind === ScriptKind.JSON) {
|
||||
const result = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
|
||||
convertToObjectWorker(result, result.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
|
||||
result.typeReferenceDirectives = emptyArray;
|
||||
result.amdDependencies = emptyArray;
|
||||
return result;
|
||||
}
|
||||
|
||||
initializeState(sourceText, languageVersion, syntaxCursor, scriptKind);
|
||||
|
||||
@@ -691,27 +698,59 @@ namespace ts {
|
||||
return isInvalid ? entityName : undefined;
|
||||
}
|
||||
|
||||
export function parseJsonText(fileName: string, sourceText: string): JsonSourceFile {
|
||||
initializeState(sourceText, ScriptTarget.ES2015, /*syntaxCursor*/ undefined, ScriptKind.JSON);
|
||||
export function parseJsonText(fileName: string, sourceText: string, languageVersion: ScriptTarget = ScriptTarget.ES2015, syntaxCursor?: IncrementalParser.SyntaxCursor, setParentNodes?: boolean): JsonSourceFile {
|
||||
initializeState(sourceText, languageVersion, syntaxCursor, ScriptKind.JSON);
|
||||
// Set source file so that errors will be reported with this file name
|
||||
sourceFile = createSourceFile(fileName, ScriptTarget.ES2015, ScriptKind.JSON, /*isDeclaration*/ false);
|
||||
const result = <JsonSourceFile>sourceFile;
|
||||
|
||||
// Prime the scanner.
|
||||
nextToken();
|
||||
const pos = getNodePos();
|
||||
if (token() === SyntaxKind.EndOfFileToken) {
|
||||
sourceFile.statements = createNodeArray([], pos, pos);
|
||||
sourceFile.endOfFileToken = parseTokenNode<EndOfFileToken>();
|
||||
}
|
||||
else if (token() === SyntaxKind.OpenBraceToken ||
|
||||
lookAhead(() => token() === SyntaxKind.StringLiteral)) {
|
||||
result.jsonObject = parseObjectLiteralExpression();
|
||||
else {
|
||||
const statement = createNode(SyntaxKind.ExpressionStatement) as JsonObjectExpressionStatement;
|
||||
switch (token()) {
|
||||
case SyntaxKind.OpenBracketToken:
|
||||
statement.expression = parseArrayLiteralExpression();
|
||||
break;
|
||||
case SyntaxKind.TrueKeyword:
|
||||
case SyntaxKind.FalseKeyword:
|
||||
case SyntaxKind.NullKeyword:
|
||||
statement.expression = parseTokenNode<BooleanLiteral | NullLiteral>();
|
||||
break;
|
||||
case SyntaxKind.MinusToken:
|
||||
if (lookAhead(() => nextToken() === SyntaxKind.NumericLiteral && nextToken() !== SyntaxKind.ColonToken)) {
|
||||
statement.expression = parsePrefixUnaryExpression() as JsonMinusNumericLiteral;
|
||||
}
|
||||
else {
|
||||
statement.expression = parseObjectLiteralExpression();
|
||||
}
|
||||
break;
|
||||
case SyntaxKind.NumericLiteral:
|
||||
case SyntaxKind.StringLiteral:
|
||||
if (lookAhead(() => nextToken() !== SyntaxKind.ColonToken)) {
|
||||
statement.expression = parseLiteralNode() as StringLiteral | NumericLiteral;
|
||||
break;
|
||||
}
|
||||
// falls through
|
||||
default:
|
||||
statement.expression = parseObjectLiteralExpression();
|
||||
break;
|
||||
}
|
||||
finishNode(statement);
|
||||
sourceFile.statements = createNodeArray([statement], pos);
|
||||
sourceFile.endOfFileToken = parseExpectedToken(SyntaxKind.EndOfFileToken, Diagnostics.Unexpected_token);
|
||||
}
|
||||
else {
|
||||
parseExpected(SyntaxKind.OpenBraceToken);
|
||||
|
||||
if (setParentNodes) {
|
||||
fixupParentReferences(sourceFile);
|
||||
}
|
||||
|
||||
sourceFile.parseDiagnostics = parseDiagnostics;
|
||||
const result = sourceFile as JsonSourceFile;
|
||||
clearState();
|
||||
return result;
|
||||
}
|
||||
@@ -739,9 +778,11 @@ namespace ts {
|
||||
switch (scriptKind) {
|
||||
case ScriptKind.JS:
|
||||
case ScriptKind.JSX:
|
||||
case ScriptKind.JSON:
|
||||
contextFlags = NodeFlags.JavaScriptFile;
|
||||
break;
|
||||
case ScriptKind.JSON:
|
||||
contextFlags = NodeFlags.JavaScriptFile | NodeFlags.JsonFile;
|
||||
break;
|
||||
default:
|
||||
contextFlags = NodeFlags.None;
|
||||
break;
|
||||
|
||||
Executable → Regular
+11
-3
@@ -1988,7 +1988,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
const isFromNodeModulesSearch = resolution.isExternalLibraryImport;
|
||||
const isJsFile = !extensionIsTypeScript(resolution.extension);
|
||||
const isJsFile = !resolutionExtensionIsTypeScriptOrJson(resolution.extension);
|
||||
const isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile;
|
||||
const resolvedFileName = resolution.resolvedFileName;
|
||||
|
||||
@@ -2200,6 +2200,12 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
if (options.resolveJsonModule) {
|
||||
if (getEmitModuleResolutionKind(options) !== ModuleResolutionKind.NodeJs) {
|
||||
createDiagnosticForOptionName(Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule");
|
||||
}
|
||||
}
|
||||
|
||||
// there has to be common source directory if user specified --outdir || --sourceRoot
|
||||
// if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
|
||||
if (options.outDir || // there is --outDir specified
|
||||
@@ -2355,8 +2361,9 @@ namespace ts {
|
||||
function getCompilerOptionsObjectLiteralSyntax() {
|
||||
if (_compilerOptionsObjectLiteralSyntax === undefined) {
|
||||
_compilerOptionsObjectLiteralSyntax = null; // tslint:disable-line:no-null-keyword
|
||||
if (options.configFile && options.configFile.jsonObject) {
|
||||
for (const prop of getPropertyAssignment(options.configFile.jsonObject, "compilerOptions")) {
|
||||
const jsonObjectLiteral = getTsConfigObjectLiteralExpression(options.configFile);
|
||||
if (jsonObjectLiteral) {
|
||||
for (const prop of getPropertyAssignment(jsonObjectLiteral, "compilerOptions")) {
|
||||
if (isObjectLiteralExpression(prop.initializer)) {
|
||||
_compilerOptionsObjectLiteralSyntax = prop.initializer;
|
||||
break;
|
||||
@@ -2426,6 +2433,7 @@ namespace ts {
|
||||
switch (extension) {
|
||||
case Extension.Ts:
|
||||
case Extension.Dts:
|
||||
case Extension.Json: // Since module is resolved to json file only when --resolveJsonModule, we dont need further check
|
||||
// These are always allowed.
|
||||
return undefined;
|
||||
case Extension.Tsx:
|
||||
|
||||
+18
-3
@@ -505,6 +505,7 @@ namespace ts {
|
||||
JSDoc = 1 << 21, // If node was parsed inside jsdoc
|
||||
/* @internal */ Ambient = 1 << 22, // If node was inside an ambient context -- a declaration file, or inside something with the `declare` modifier.
|
||||
/* @internal */ InWithStatement = 1 << 23, // If any ancestor of node was the `statement` of a WithStatement (not the `expression`)
|
||||
JsonFile = 1 << 24, // If node was parsed in a Json
|
||||
|
||||
BlockScoped = Let | Const,
|
||||
|
||||
@@ -2620,10 +2621,23 @@ namespace ts {
|
||||
}
|
||||
|
||||
export interface JsonSourceFile extends SourceFile {
|
||||
jsonObject?: ObjectLiteralExpression;
|
||||
statements: NodeArray<JsonObjectExpressionStatement>;
|
||||
}
|
||||
|
||||
export interface TsConfigSourceFile extends JsonSourceFile {
|
||||
extendedSourceFiles?: string[];
|
||||
}
|
||||
|
||||
export interface JsonMinusNumericLiteral extends PrefixUnaryExpression {
|
||||
kind: SyntaxKind.PrefixUnaryExpression;
|
||||
operator: SyntaxKind.MinusToken;
|
||||
operand: NumericLiteral;
|
||||
}
|
||||
|
||||
export interface JsonObjectExpressionStatement extends ExpressionStatement {
|
||||
expression: ObjectLiteralExpression | ArrayLiteralExpression | JsonMinusNumericLiteral | NumericLiteral | StringLiteral | BooleanLiteral | NullLiteral;
|
||||
}
|
||||
|
||||
export interface ScriptReferenceHost {
|
||||
getCompilerOptions(): CompilerOptions;
|
||||
getSourceFile(fileName: string): SourceFile | undefined;
|
||||
@@ -4176,7 +4190,7 @@ namespace ts {
|
||||
checkJs?: boolean;
|
||||
/* @internal */ configFilePath?: string;
|
||||
/** configFile is set as non enumerable property so as to avoid checking of json source files */
|
||||
/* @internal */ readonly configFile?: JsonSourceFile;
|
||||
/* @internal */ readonly configFile?: TsConfigSourceFile;
|
||||
declaration?: boolean;
|
||||
declarationMap?: boolean;
|
||||
emitDeclarationOnly?: boolean;
|
||||
@@ -4250,6 +4264,7 @@ namespace ts {
|
||||
/* @internal */ suppressOutputPathCheck?: boolean;
|
||||
target?: ScriptTarget;
|
||||
traceResolution?: boolean;
|
||||
resolveJsonModule?: boolean;
|
||||
types?: string[];
|
||||
/** Paths used to compute primary types search locations */
|
||||
typeRoots?: string[];
|
||||
@@ -4257,7 +4272,7 @@ namespace ts {
|
||||
/*@internal*/ watch?: boolean;
|
||||
esModuleInterop?: boolean;
|
||||
|
||||
[option: string]: CompilerOptionsValue | JsonSourceFile | undefined;
|
||||
[option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined;
|
||||
}
|
||||
|
||||
export interface TypeAcquisition {
|
||||
|
||||
@@ -724,6 +724,11 @@ namespace ts {
|
||||
return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
|
||||
}
|
||||
|
||||
|
||||
export function isJsonSourceFile(file: SourceFile): file is JsonSourceFile {
|
||||
return file.scriptKind === ScriptKind.JSON;
|
||||
}
|
||||
|
||||
export function isConstEnumDeclaration(node: Node): boolean {
|
||||
return node.kind === SyntaxKind.EnumDeclaration && isConst(node);
|
||||
}
|
||||
@@ -1071,6 +1076,22 @@ namespace ts {
|
||||
});
|
||||
}
|
||||
|
||||
export function getTsConfigObjectLiteralExpression(tsConfigSourceFile: TsConfigSourceFile | undefined) {
|
||||
if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
|
||||
const expression = tsConfigSourceFile.statements[0].expression;
|
||||
return isObjectLiteralExpression(expression) && expression;
|
||||
}
|
||||
}
|
||||
|
||||
export function getTsConfigPropArrayElementValue(tsConfigSourceFile: TsConfigSourceFile | undefined, propKey: string, elementValue: string): StringLiteral | undefined {
|
||||
const jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile);
|
||||
return jsonObjectLiteral &&
|
||||
firstDefined(getPropertyAssignment(jsonObjectLiteral, propKey), property =>
|
||||
isArrayLiteralExpression(property.initializer) ?
|
||||
find(property.initializer.elements, (element): element is StringLiteral => isStringLiteral(element) && element.text === elementValue) :
|
||||
undefined);
|
||||
}
|
||||
|
||||
export function getContainingFunction(node: Node): SignatureDeclaration {
|
||||
return findAncestor(node.parent, isFunctionLike);
|
||||
}
|
||||
@@ -1467,6 +1488,10 @@ namespace ts {
|
||||
return node && !!(node.flags & NodeFlags.JavaScriptFile);
|
||||
}
|
||||
|
||||
export function isInJsonFile(node: Node | undefined): boolean {
|
||||
return node && !!(node.flags & NodeFlags.JsonFile);
|
||||
}
|
||||
|
||||
export function isInJSDoc(node: Node | undefined): boolean {
|
||||
return node && !!(node.flags & NodeFlags.JSDoc);
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ namespace compiler {
|
||||
const dts = this.dts = new collections.SortedMap<string, documents.TextDocument>({ comparer: this.vfs.stringComparer, sort: "insertion" });
|
||||
const maps = this.maps = new collections.SortedMap<string, documents.TextDocument>({ comparer: this.vfs.stringComparer, sort: "insertion" });
|
||||
for (const document of this.host.outputs) {
|
||||
if (vpath.isJavaScript(document.file)) {
|
||||
if (vpath.isJavaScript(document.file) || ts.fileExtensionIs(document.file, ts.Extension.Json)) {
|
||||
js.set(document.file, document);
|
||||
}
|
||||
else if (vpath.isDeclaration(document.file)) {
|
||||
@@ -245,4 +245,4 @@ namespace compiler {
|
||||
const errors = ts.getPreEmitDiagnostics(program);
|
||||
return new CompilationResult(host, compilerOptions, program, emitResult, errors);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1217,7 +1217,7 @@ namespace Harness {
|
||||
}
|
||||
|
||||
const useCaseSensitiveFileNames = options.useCaseSensitiveFileNames !== undefined ? options.useCaseSensitiveFileNames : true;
|
||||
const programFileNames = inputFiles.map(file => file.unitName);
|
||||
const programFileNames = inputFiles.map(file => file.unitName).filter(fileName => !ts.fileExtensionIs(fileName, ts.Extension.Json));
|
||||
|
||||
// Files from built\local that are requested by test "@includeBuiltFiles" to be in the context.
|
||||
// Treat them as library files, so include them in build, but not in baselines.
|
||||
|
||||
@@ -10,12 +10,6 @@ namespace ts {
|
||||
assert.equal(JSON.stringify(parsed), JSON.stringify(expectedConfigObject));
|
||||
}
|
||||
|
||||
function assertParseError(jsonText: string) {
|
||||
const parsed = parseConfigFileTextToJson("/apath/tsconfig.json", jsonText);
|
||||
assert.deepEqual(parsed.config, {});
|
||||
assert.isTrue(undefined !== parsed.error);
|
||||
}
|
||||
|
||||
function assertParseErrorWithExcludesKeyword(jsonText: string) {
|
||||
{
|
||||
const parsed = parseConfigFileTextToJson("/apath/tsconfig.json", jsonText);
|
||||
@@ -138,7 +132,14 @@ namespace ts {
|
||||
});
|
||||
|
||||
it("returns object with error when json is invalid", () => {
|
||||
assertParseError("invalid");
|
||||
const parsed = parseConfigFileTextToJson("/apath/tsconfig.json", "invalid");
|
||||
assert.deepEqual(parsed.config, { invalid: undefined });
|
||||
const expected = createCompilerDiagnostic(Diagnostics._0_expected, "{");
|
||||
assert.equal(parsed.error.messageText, expected.messageText);
|
||||
assert.equal(parsed.error.category, expected.category);
|
||||
assert.equal(parsed.error.code, expected.code);
|
||||
assert.equal(parsed.error.start, 0);
|
||||
assert.equal(parsed.error.length, "invalid".length);
|
||||
});
|
||||
|
||||
it("returns object when users correctly specify library", () => {
|
||||
|
||||
@@ -2746,6 +2746,7 @@ namespace ts.server.protocol {
|
||||
suppressImplicitAnyIndexErrors?: boolean;
|
||||
target?: ScriptTarget | ts.ScriptTarget;
|
||||
traceResolution?: boolean;
|
||||
resolveJsonModule?: boolean;
|
||||
types?: string[];
|
||||
/** Paths used to used to compute primary types search locations */
|
||||
typeRoots?: string[];
|
||||
|
||||
@@ -15,21 +15,13 @@ namespace ts {
|
||||
}
|
||||
|
||||
function updateTsconfigFiles(program: Program, changeTracker: textChanges.ChangeTracker, oldFilePath: string, newFilePath: string): void {
|
||||
const cfg = program.getCompilerOptions().configFile;
|
||||
if (!cfg) return;
|
||||
const oldFile = cfg.jsonObject && getFilesEntry(cfg.jsonObject, oldFilePath);
|
||||
const configFile = program.getCompilerOptions().configFile;
|
||||
const oldFile = getTsConfigPropArrayElementValue(configFile, "files", oldFilePath);
|
||||
if (oldFile) {
|
||||
changeTracker.replaceRangeWithText(cfg, createStringRange(oldFile, cfg), newFilePath);
|
||||
changeTracker.replaceRangeWithText(configFile, createStringRange(oldFile, configFile), newFilePath);
|
||||
}
|
||||
}
|
||||
|
||||
function getFilesEntry(cfg: ObjectLiteralExpression, fileName: string): StringLiteral | undefined {
|
||||
const filesProp = find(cfg.properties, (prop): prop is PropertyAssignment =>
|
||||
isPropertyAssignment(prop) && isStringLiteral(prop.name) && prop.name.text === "files");
|
||||
const files = filesProp && filesProp.initializer;
|
||||
return files && isArrayLiteralExpression(files) ? find(files.elements, (e): e is StringLiteral => isStringLiteral(e) && e.text === fileName) : undefined;
|
||||
}
|
||||
|
||||
interface ToUpdate {
|
||||
readonly sourceFile: SourceFile;
|
||||
readonly toUpdate: StringLiteralLike | FileReference;
|
||||
|
||||
Reference in New Issue
Block a user