hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 1, "code_window": [ "import { ensureNoDisposablesAreLeakedInTestSuite } from 'vs/base/test/common/utils';\n", "import { toDisposable } from 'vs/base/common/lifecycle';\n", "import { mainWindow } from 'vs/base/browser/window';\n", "\n", "// Sets up an `onShow` listener to allow us to wait until the quick pick is shown (useful when triggering an `accept()` right after launching a quick pick)\n", "// kick this off before you launch the picker and then await the promise returned after you launch the picker.\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { QuickPick } from 'vs/platform/quickinput/browser/quickInput';\n", "import { IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';\n" ], "file_path": "src/vs/platform/quickinput/test/browser/quickinput.test.ts", "type": "add", "edit_start_line_idx": 20 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { ParseError, parse, getNodeType } from 'vs/base/common/json'; import { IJSONSchema } from 'vs/base/common/jsonSchema'; import * as types from 'vs/base/common/types'; import { URI } from 'vs/base/common/uri'; import { CharacterPair, CommentRule, EnterAction, ExplicitLanguageConfiguration, FoldingMarkers, FoldingRules, IAutoClosingPair, IAutoClosingPairConditional, IndentAction, IndentationRule, OnEnterRule } from 'vs/editor/common/languages/languageConfiguration'; import { ILanguageConfigurationService } from 'vs/editor/common/languages/languageConfigurationRegistry'; import { ILanguageService } from 'vs/editor/common/languages/language'; import { Extensions, IJSONContributionRegistry } from 'vs/platform/jsonschemas/common/jsonContributionRegistry'; import { Registry } from 'vs/platform/registry/common/platform'; import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions'; import { getParseErrorMessage } from 'vs/base/common/jsonErrorMessages'; import { IExtensionResourceLoaderService } from 'vs/platform/extensionResourceLoader/common/extensionResourceLoader'; import { hash } from 'vs/base/common/hash'; import { Disposable } from 'vs/base/common/lifecycle'; interface IRegExp { pattern: string; flags?: string; } interface IIndentationRules { decreaseIndentPattern: string | IRegExp; increaseIndentPattern: string | IRegExp; indentNextLinePattern?: string | IRegExp; unIndentedLinePattern?: string | IRegExp; } interface IEnterAction { indent: 'none' | 'indent' | 'indentOutdent' | 'outdent'; appendText?: string; removeText?: number; } interface IOnEnterRule { beforeText: string | IRegExp; afterText?: string | IRegExp; previousLineText?: string | IRegExp; action: IEnterAction; } /** * Serialized form of a language configuration */ interface ILanguageConfiguration { comments?: CommentRule; brackets?: CharacterPair[]; autoClosingPairs?: Array<CharacterPair | IAutoClosingPairConditional>; surroundingPairs?: Array<CharacterPair | IAutoClosingPair>; colorizedBracketPairs?: Array<CharacterPair>; wordPattern?: string | IRegExp; indentationRules?: IIndentationRules; folding?: { offSide?: boolean; markers?: { start?: string | IRegExp; end?: string | IRegExp; }; }; autoCloseBefore?: string; onEnterRules?: IOnEnterRule[]; } function isStringArr(something: string[] | null): something is string[] { if (!Array.isArray(something)) { return false; } for (let i = 0, len = something.length; i < len; i++) { if (typeof something[i] !== 'string') { return false; } } return true; } function isCharacterPair(something: CharacterPair | null): boolean { return ( isStringArr(something) && something.length === 2 ); } export class LanguageConfigurationFileHandler extends Disposable { /** * A map from language id to a hash computed from the config files locations. */ private readonly _done = new Map<string, number>(); constructor( @ILanguageService private readonly _languageService: ILanguageService, @IExtensionResourceLoaderService private readonly _extensionResourceLoaderService: IExtensionResourceLoaderService, @IExtensionService private readonly _extensionService: IExtensionService, @ILanguageConfigurationService private readonly _languageConfigurationService: ILanguageConfigurationService, ) { super(); this._register(this._languageService.onDidRequestBasicLanguageFeatures(async (languageIdentifier) => { // Modes can be instantiated before the extension points have finished registering this._extensionService.whenInstalledExtensionsRegistered().then(() => { this._loadConfigurationsForMode(languageIdentifier); }); })); this._register(this._languageService.onDidChange(() => { // reload language configurations as necessary for (const [languageId] of this._done) { this._loadConfigurationsForMode(languageId); } })); } private async _loadConfigurationsForMode(languageId: string): Promise<void> { const configurationFiles = this._languageService.getConfigurationFiles(languageId); const configurationHash = hash(configurationFiles.map(uri => uri.toString())); if (this._done.get(languageId) === configurationHash) { return; } this._done.set(languageId, configurationHash); const configs = await Promise.all(configurationFiles.map(configFile => this._readConfigFile(configFile))); for (const config of configs) { this._handleConfig(languageId, config); } } private async _readConfigFile(configFileLocation: URI): Promise<ILanguageConfiguration> { try { const contents = await this._extensionResourceLoaderService.readExtensionResource(configFileLocation); const errors: ParseError[] = []; let configuration = <ILanguageConfiguration>parse(contents, errors); if (errors.length) { console.error(nls.localize('parseErrors', "Errors parsing {0}: {1}", configFileLocation.toString(), errors.map(e => (`[${e.offset}, ${e.length}] ${getParseErrorMessage(e.error)}`)).join('\n'))); } if (getNodeType(configuration) !== 'object') { console.error(nls.localize('formatError', "{0}: Invalid format, JSON object expected.", configFileLocation.toString())); configuration = {}; } return configuration; } catch (err) { console.error(err); return {}; } } private _extractValidCommentRule(languageId: string, configuration: ILanguageConfiguration): CommentRule | undefined { const source = configuration.comments; if (typeof source === 'undefined') { return undefined; } if (!types.isObject(source)) { console.warn(`[${languageId}]: language configuration: expected \`comments\` to be an object.`); return undefined; } let result: CommentRule | undefined = undefined; if (typeof source.lineComment !== 'undefined') { if (typeof source.lineComment !== 'string') { console.warn(`[${languageId}]: language configuration: expected \`comments.lineComment\` to be a string.`); } else { result = result || {}; result.lineComment = source.lineComment; } } if (typeof source.blockComment !== 'undefined') { if (!isCharacterPair(source.blockComment)) { console.warn(`[${languageId}]: language configuration: expected \`comments.blockComment\` to be an array of two strings.`); } else { result = result || {}; result.blockComment = source.blockComment; } } return result; } private _extractValidBrackets(languageId: string, configuration: ILanguageConfiguration): CharacterPair[] | undefined { const source = configuration.brackets; if (typeof source === 'undefined') { return undefined; } if (!Array.isArray(source)) { console.warn(`[${languageId}]: language configuration: expected \`brackets\` to be an array.`); return undefined; } let result: CharacterPair[] | undefined = undefined; for (let i = 0, len = source.length; i < len; i++) { const pair = source[i]; if (!isCharacterPair(pair)) { console.warn(`[${languageId}]: language configuration: expected \`brackets[${i}]\` to be an array of two strings.`); continue; } result = result || []; result.push(pair); } return result; } private _extractValidAutoClosingPairs(languageId: string, configuration: ILanguageConfiguration): IAutoClosingPairConditional[] | undefined { const source = configuration.autoClosingPairs; if (typeof source === 'undefined') { return undefined; } if (!Array.isArray(source)) { console.warn(`[${languageId}]: language configuration: expected \`autoClosingPairs\` to be an array.`); return undefined; } let result: IAutoClosingPairConditional[] | undefined = undefined; for (let i = 0, len = source.length; i < len; i++) { const pair = source[i]; if (Array.isArray(pair)) { if (!isCharacterPair(pair)) { console.warn(`[${languageId}]: language configuration: expected \`autoClosingPairs[${i}]\` to be an array of two strings or an object.`); continue; } result = result || []; result.push({ open: pair[0], close: pair[1] }); } else { if (!types.isObject(pair)) { console.warn(`[${languageId}]: language configuration: expected \`autoClosingPairs[${i}]\` to be an array of two strings or an object.`); continue; } if (typeof pair.open !== 'string') { console.warn(`[${languageId}]: language configuration: expected \`autoClosingPairs[${i}].open\` to be a string.`); continue; } if (typeof pair.close !== 'string') { console.warn(`[${languageId}]: language configuration: expected \`autoClosingPairs[${i}].close\` to be a string.`); continue; } if (typeof pair.notIn !== 'undefined') { if (!isStringArr(pair.notIn)) { console.warn(`[${languageId}]: language configuration: expected \`autoClosingPairs[${i}].notIn\` to be a string array.`); continue; } } result = result || []; result.push({ open: pair.open, close: pair.close, notIn: pair.notIn }); } } return result; } private _extractValidSurroundingPairs(languageId: string, configuration: ILanguageConfiguration): IAutoClosingPair[] | undefined { const source = configuration.surroundingPairs; if (typeof source === 'undefined') { return undefined; } if (!Array.isArray(source)) { console.warn(`[${languageId}]: language configuration: expected \`surroundingPairs\` to be an array.`); return undefined; } let result: IAutoClosingPair[] | undefined = undefined; for (let i = 0, len = source.length; i < len; i++) { const pair = source[i]; if (Array.isArray(pair)) { if (!isCharacterPair(pair)) { console.warn(`[${languageId}]: language configuration: expected \`surroundingPairs[${i}]\` to be an array of two strings or an object.`); continue; } result = result || []; result.push({ open: pair[0], close: pair[1] }); } else { if (!types.isObject(pair)) { console.warn(`[${languageId}]: language configuration: expected \`surroundingPairs[${i}]\` to be an array of two strings or an object.`); continue; } if (typeof pair.open !== 'string') { console.warn(`[${languageId}]: language configuration: expected \`surroundingPairs[${i}].open\` to be a string.`); continue; } if (typeof pair.close !== 'string') { console.warn(`[${languageId}]: language configuration: expected \`surroundingPairs[${i}].close\` to be a string.`); continue; } result = result || []; result.push({ open: pair.open, close: pair.close }); } } return result; } private _extractValidColorizedBracketPairs(languageId: string, configuration: ILanguageConfiguration): CharacterPair[] | undefined { const source = configuration.colorizedBracketPairs; if (typeof source === 'undefined') { return undefined; } if (!Array.isArray(source)) { console.warn(`[${languageId}]: language configuration: expected \`colorizedBracketPairs\` to be an array.`); return undefined; } const result: CharacterPair[] = []; for (let i = 0, len = source.length; i < len; i++) { const pair = source[i]; if (!isCharacterPair(pair)) { console.warn(`[${languageId}]: language configuration: expected \`colorizedBracketPairs[${i}]\` to be an array of two strings.`); continue; } result.push([pair[0], pair[1]]); } return result; } private _extractValidOnEnterRules(languageId: string, configuration: ILanguageConfiguration): OnEnterRule[] | undefined { const source = configuration.onEnterRules; if (typeof source === 'undefined') { return undefined; } if (!Array.isArray(source)) { console.warn(`[${languageId}]: language configuration: expected \`onEnterRules\` to be an array.`); return undefined; } let result: OnEnterRule[] | undefined = undefined; for (let i = 0, len = source.length; i < len; i++) { const onEnterRule = source[i]; if (!types.isObject(onEnterRule)) { console.warn(`[${languageId}]: language configuration: expected \`onEnterRules[${i}]\` to be an object.`); continue; } if (!types.isObject(onEnterRule.action)) { console.warn(`[${languageId}]: language configuration: expected \`onEnterRules[${i}].action\` to be an object.`); continue; } let indentAction: IndentAction; if (onEnterRule.action.indent === 'none') { indentAction = IndentAction.None; } else if (onEnterRule.action.indent === 'indent') { indentAction = IndentAction.Indent; } else if (onEnterRule.action.indent === 'indentOutdent') { indentAction = IndentAction.IndentOutdent; } else if (onEnterRule.action.indent === 'outdent') { indentAction = IndentAction.Outdent; } else { console.warn(`[${languageId}]: language configuration: expected \`onEnterRules[${i}].action.indent\` to be 'none', 'indent', 'indentOutdent' or 'outdent'.`); continue; } const action: EnterAction = { indentAction }; if (onEnterRule.action.appendText) { if (typeof onEnterRule.action.appendText === 'string') { action.appendText = onEnterRule.action.appendText; } else { console.warn(`[${languageId}]: language configuration: expected \`onEnterRules[${i}].action.appendText\` to be undefined or a string.`); } } if (onEnterRule.action.removeText) { if (typeof onEnterRule.action.removeText === 'number') { action.removeText = onEnterRule.action.removeText; } else { console.warn(`[${languageId}]: language configuration: expected \`onEnterRules[${i}].action.removeText\` to be undefined or a number.`); } } const beforeText = this._parseRegex(languageId, `onEnterRules[${i}].beforeText`, onEnterRule.beforeText); if (!beforeText) { continue; } const resultingOnEnterRule: OnEnterRule = { beforeText, action }; if (onEnterRule.afterText) { const afterText = this._parseRegex(languageId, `onEnterRules[${i}].afterText`, onEnterRule.afterText); if (afterText) { resultingOnEnterRule.afterText = afterText; } } if (onEnterRule.previousLineText) { const previousLineText = this._parseRegex(languageId, `onEnterRules[${i}].previousLineText`, onEnterRule.previousLineText); if (previousLineText) { resultingOnEnterRule.previousLineText = previousLineText; } } result = result || []; result.push(resultingOnEnterRule); } return result; } private _handleConfig(languageId: string, configuration: ILanguageConfiguration): void { const comments = this._extractValidCommentRule(languageId, configuration); const brackets = this._extractValidBrackets(languageId, configuration); const autoClosingPairs = this._extractValidAutoClosingPairs(languageId, configuration); const surroundingPairs = this._extractValidSurroundingPairs(languageId, configuration); const colorizedBracketPairs = this._extractValidColorizedBracketPairs(languageId, configuration); const autoCloseBefore = (typeof configuration.autoCloseBefore === 'string' ? configuration.autoCloseBefore : undefined); const wordPattern = (configuration.wordPattern ? this._parseRegex(languageId, `wordPattern`, configuration.wordPattern) : undefined); const indentationRules = (configuration.indentationRules ? this._mapIndentationRules(languageId, configuration.indentationRules) : undefined); let folding: FoldingRules | undefined = undefined; if (configuration.folding) { const rawMarkers = configuration.folding.markers; const startMarker = (rawMarkers && rawMarkers.start ? this._parseRegex(languageId, `folding.markers.start`, rawMarkers.start) : undefined); const endMarker = (rawMarkers && rawMarkers.end ? this._parseRegex(languageId, `folding.markers.end`, rawMarkers.end) : undefined); const markers: FoldingMarkers | undefined = (startMarker && endMarker ? { start: startMarker, end: endMarker } : undefined); folding = { offSide: configuration.folding.offSide, markers }; } const onEnterRules = this._extractValidOnEnterRules(languageId, configuration); const richEditConfig: ExplicitLanguageConfiguration = { comments, brackets, wordPattern, indentationRules, onEnterRules, autoClosingPairs, surroundingPairs, colorizedBracketPairs, autoCloseBefore, folding, __electricCharacterSupport: undefined, }; this._languageConfigurationService.register(languageId, richEditConfig, 50); } private _parseRegex(languageId: string, confPath: string, value: string | IRegExp): RegExp | undefined { if (typeof value === 'string') { try { return new RegExp(value, ''); } catch (err) { console.warn(`[${languageId}]: Invalid regular expression in \`${confPath}\`: `, err); return undefined; } } if (types.isObject(value)) { if (typeof value.pattern !== 'string') { console.warn(`[${languageId}]: language configuration: expected \`${confPath}.pattern\` to be a string.`); return undefined; } if (typeof value.flags !== 'undefined' && typeof value.flags !== 'string') { console.warn(`[${languageId}]: language configuration: expected \`${confPath}.flags\` to be a string.`); return undefined; } try { return new RegExp(value.pattern, value.flags); } catch (err) { console.warn(`[${languageId}]: Invalid regular expression in \`${confPath}\`: `, err); return undefined; } } console.warn(`[${languageId}]: language configuration: expected \`${confPath}\` to be a string or an object.`); return undefined; } private _mapIndentationRules(languageId: string, indentationRules: IIndentationRules): IndentationRule | undefined { const increaseIndentPattern = this._parseRegex(languageId, `indentationRules.increaseIndentPattern`, indentationRules.increaseIndentPattern); if (!increaseIndentPattern) { return undefined; } const decreaseIndentPattern = this._parseRegex(languageId, `indentationRules.decreaseIndentPattern`, indentationRules.decreaseIndentPattern); if (!decreaseIndentPattern) { return undefined; } const result: IndentationRule = { increaseIndentPattern: increaseIndentPattern, decreaseIndentPattern: decreaseIndentPattern }; if (indentationRules.indentNextLinePattern) { result.indentNextLinePattern = this._parseRegex(languageId, `indentationRules.indentNextLinePattern`, indentationRules.indentNextLinePattern); } if (indentationRules.unIndentedLinePattern) { result.unIndentedLinePattern = this._parseRegex(languageId, `indentationRules.unIndentedLinePattern`, indentationRules.unIndentedLinePattern); } return result; } } const schemaId = 'vscode://schemas/language-configuration'; const schema: IJSONSchema = { allowComments: true, allowTrailingCommas: true, default: { comments: { blockComment: ['/*', '*/'], lineComment: '//' }, brackets: [['(', ')'], ['[', ']'], ['{', '}']], autoClosingPairs: [['(', ')'], ['[', ']'], ['{', '}']], surroundingPairs: [['(', ')'], ['[', ']'], ['{', '}']] }, definitions: { openBracket: { type: 'string', description: nls.localize('schema.openBracket', 'The opening bracket character or string sequence.') }, closeBracket: { type: 'string', description: nls.localize('schema.closeBracket', 'The closing bracket character or string sequence.') }, bracketPair: { type: 'array', items: [{ $ref: '#/definitions/openBracket' }, { $ref: '#/definitions/closeBracket' }] } }, properties: { comments: { default: { blockComment: ['/*', '*/'], lineComment: '//' }, description: nls.localize('schema.comments', 'Defines the comment symbols'), type: 'object', properties: { blockComment: { type: 'array', description: nls.localize('schema.blockComments', 'Defines how block comments are marked.'), items: [{ type: 'string', description: nls.localize('schema.blockComment.begin', 'The character sequence that starts a block comment.') }, { type: 'string', description: nls.localize('schema.blockComment.end', 'The character sequence that ends a block comment.') }] }, lineComment: { type: 'string', description: nls.localize('schema.lineComment', 'The character sequence that starts a line comment.') } } }, brackets: { default: [['(', ')'], ['[', ']'], ['{', '}']], markdownDescription: nls.localize('schema.brackets', 'Defines the bracket symbols that increase or decrease the indentation. When bracket pair colorization is enabled and {0} is not defined, this also defines the bracket pairs that are colorized by their nesting level.', '\`colorizedBracketPairs\`'), type: 'array', items: { $ref: '#/definitions/bracketPair' } }, colorizedBracketPairs: { default: [['(', ')'], ['[', ']'], ['{', '}']], markdownDescription: nls.localize('schema.colorizedBracketPairs', 'Defines the bracket pairs that are colorized by their nesting level if bracket pair colorization is enabled. Any brackets included here that are not included in {0} will be automatically included in {0}.', '\`brackets\`'), type: 'array', items: { $ref: '#/definitions/bracketPair' } }, autoClosingPairs: { default: [['(', ')'], ['[', ']'], ['{', '}']], description: nls.localize('schema.autoClosingPairs', 'Defines the bracket pairs. When a opening bracket is entered, the closing bracket is inserted automatically.'), type: 'array', items: { oneOf: [{ $ref: '#/definitions/bracketPair' }, { type: 'object', properties: { open: { $ref: '#/definitions/openBracket' }, close: { $ref: '#/definitions/closeBracket' }, notIn: { type: 'array', description: nls.localize('schema.autoClosingPairs.notIn', 'Defines a list of scopes where the auto pairs are disabled.'), items: { enum: ['string', 'comment'] } } } }] } }, autoCloseBefore: { default: ';:.,=}])> \n\t', description: nls.localize('schema.autoCloseBefore', 'Defines what characters must be after the cursor in order for bracket or quote autoclosing to occur when using the \'languageDefined\' autoclosing setting. This is typically the set of characters which can not start an expression.'), type: 'string', }, surroundingPairs: { default: [['(', ')'], ['[', ']'], ['{', '}']], description: nls.localize('schema.surroundingPairs', 'Defines the bracket pairs that can be used to surround a selected string.'), type: 'array', items: { oneOf: [{ $ref: '#/definitions/bracketPair' }, { type: 'object', properties: { open: { $ref: '#/definitions/openBracket' }, close: { $ref: '#/definitions/closeBracket' } } }] } }, wordPattern: { default: '', description: nls.localize('schema.wordPattern', 'Defines what is considered to be a word in the programming language.'), type: ['string', 'object'], properties: { pattern: { type: 'string', description: nls.localize('schema.wordPattern.pattern', 'The RegExp pattern used to match words.'), default: '', }, flags: { type: 'string', description: nls.localize('schema.wordPattern.flags', 'The RegExp flags used to match words.'), default: 'g', pattern: '^([gimuy]+)$', patternErrorMessage: nls.localize('schema.wordPattern.flags.errorMessage', 'Must match the pattern `/^([gimuy]+)$/`.') } } }, indentationRules: { default: { increaseIndentPattern: '', decreaseIndentPattern: '' }, description: nls.localize('schema.indentationRules', 'The language\'s indentation settings.'), type: 'object', properties: { increaseIndentPattern: { type: ['string', 'object'], description: nls.localize('schema.indentationRules.increaseIndentPattern', 'If a line matches this pattern, then all the lines after it should be indented once (until another rule matches).'), properties: { pattern: { type: 'string', description: nls.localize('schema.indentationRules.increaseIndentPattern.pattern', 'The RegExp pattern for increaseIndentPattern.'), default: '', }, flags: { type: 'string', description: nls.localize('schema.indentationRules.increaseIndentPattern.flags', 'The RegExp flags for increaseIndentPattern.'), default: '', pattern: '^([gimuy]+)$', patternErrorMessage: nls.localize('schema.indentationRules.increaseIndentPattern.errorMessage', 'Must match the pattern `/^([gimuy]+)$/`.') } } }, decreaseIndentPattern: { type: ['string', 'object'], description: nls.localize('schema.indentationRules.decreaseIndentPattern', 'If a line matches this pattern, then all the lines after it should be unindented once (until another rule matches).'), properties: { pattern: { type: 'string', description: nls.localize('schema.indentationRules.decreaseIndentPattern.pattern', 'The RegExp pattern for decreaseIndentPattern.'), default: '', }, flags: { type: 'string', description: nls.localize('schema.indentationRules.decreaseIndentPattern.flags', 'The RegExp flags for decreaseIndentPattern.'), default: '', pattern: '^([gimuy]+)$', patternErrorMessage: nls.localize('schema.indentationRules.decreaseIndentPattern.errorMessage', 'Must match the pattern `/^([gimuy]+)$/`.') } } }, indentNextLinePattern: { type: ['string', 'object'], description: nls.localize('schema.indentationRules.indentNextLinePattern', 'If a line matches this pattern, then **only the next line** after it should be indented once.'), properties: { pattern: { type: 'string', description: nls.localize('schema.indentationRules.indentNextLinePattern.pattern', 'The RegExp pattern for indentNextLinePattern.'), default: '', }, flags: { type: 'string', description: nls.localize('schema.indentationRules.indentNextLinePattern.flags', 'The RegExp flags for indentNextLinePattern.'), default: '', pattern: '^([gimuy]+)$', patternErrorMessage: nls.localize('schema.indentationRules.indentNextLinePattern.errorMessage', 'Must match the pattern `/^([gimuy]+)$/`.') } } }, unIndentedLinePattern: { type: ['string', 'object'], description: nls.localize('schema.indentationRules.unIndentedLinePattern', 'If a line matches this pattern, then its indentation should not be changed and it should not be evaluated against the other rules.'), properties: { pattern: { type: 'string', description: nls.localize('schema.indentationRules.unIndentedLinePattern.pattern', 'The RegExp pattern for unIndentedLinePattern.'), default: '', }, flags: { type: 'string', description: nls.localize('schema.indentationRules.unIndentedLinePattern.flags', 'The RegExp flags for unIndentedLinePattern.'), default: '', pattern: '^([gimuy]+)$', patternErrorMessage: nls.localize('schema.indentationRules.unIndentedLinePattern.errorMessage', 'Must match the pattern `/^([gimuy]+)$/`.') } } } } }, folding: { type: 'object', description: nls.localize('schema.folding', 'The language\'s folding settings.'), properties: { offSide: { type: 'boolean', description: nls.localize('schema.folding.offSide', 'A language adheres to the off-side rule if blocks in that language are expressed by their indentation. If set, empty lines belong to the subsequent block.'), }, markers: { type: 'object', description: nls.localize('schema.folding.markers', 'Language specific folding markers such as \'#region\' and \'#endregion\'. The start and end regexes will be tested against the contents of all lines and must be designed efficiently'), properties: { start: { type: 'string', description: nls.localize('schema.folding.markers.start', 'The RegExp pattern for the start marker. The regexp must start with \'^\'.') }, end: { type: 'string', description: nls.localize('schema.folding.markers.end', 'The RegExp pattern for the end marker. The regexp must start with \'^\'.') }, } } } }, onEnterRules: { type: 'array', description: nls.localize('schema.onEnterRules', 'The language\'s rules to be evaluated when pressing Enter.'), items: { type: 'object', description: nls.localize('schema.onEnterRules', 'The language\'s rules to be evaluated when pressing Enter.'), required: ['beforeText', 'action'], properties: { beforeText: { type: ['string', 'object'], description: nls.localize('schema.onEnterRules.beforeText', 'This rule will only execute if the text before the cursor matches this regular expression.'), properties: { pattern: { type: 'string', description: nls.localize('schema.onEnterRules.beforeText.pattern', 'The RegExp pattern for beforeText.'), default: '', }, flags: { type: 'string', description: nls.localize('schema.onEnterRules.beforeText.flags', 'The RegExp flags for beforeText.'), default: '', pattern: '^([gimuy]+)$', patternErrorMessage: nls.localize('schema.onEnterRules.beforeText.errorMessage', 'Must match the pattern `/^([gimuy]+)$/`.') } } }, afterText: { type: ['string', 'object'], description: nls.localize('schema.onEnterRules.afterText', 'This rule will only execute if the text after the cursor matches this regular expression.'), properties: { pattern: { type: 'string', description: nls.localize('schema.onEnterRules.afterText.pattern', 'The RegExp pattern for afterText.'), default: '', }, flags: { type: 'string', description: nls.localize('schema.onEnterRules.afterText.flags', 'The RegExp flags for afterText.'), default: '', pattern: '^([gimuy]+)$', patternErrorMessage: nls.localize('schema.onEnterRules.afterText.errorMessage', 'Must match the pattern `/^([gimuy]+)$/`.') } } }, previousLineText: { type: ['string', 'object'], description: nls.localize('schema.onEnterRules.previousLineText', 'This rule will only execute if the text above the line matches this regular expression.'), properties: { pattern: { type: 'string', description: nls.localize('schema.onEnterRules.previousLineText.pattern', 'The RegExp pattern for previousLineText.'), default: '', }, flags: { type: 'string', description: nls.localize('schema.onEnterRules.previousLineText.flags', 'The RegExp flags for previousLineText.'), default: '', pattern: '^([gimuy]+)$', patternErrorMessage: nls.localize('schema.onEnterRules.previousLineText.errorMessage', 'Must match the pattern `/^([gimuy]+)$/`.') } } }, action: { type: ['string', 'object'], description: nls.localize('schema.onEnterRules.action', 'The action to execute.'), required: ['indent'], default: { 'indent': 'indent' }, properties: { indent: { type: 'string', description: nls.localize('schema.onEnterRules.action.indent', "Describe what to do with the indentation"), default: 'indent', enum: ['none', 'indent', 'indentOutdent', 'outdent'], markdownEnumDescriptions: [ nls.localize('schema.onEnterRules.action.indent.none', "Insert new line and copy the previous line's indentation."), nls.localize('schema.onEnterRules.action.indent.indent', "Insert new line and indent once (relative to the previous line's indentation)."), nls.localize('schema.onEnterRules.action.indent.indentOutdent', "Insert two new lines:\n - the first one indented which will hold the cursor\n - the second one at the same indentation level"), nls.localize('schema.onEnterRules.action.indent.outdent', "Insert new line and outdent once (relative to the previous line's indentation).") ] }, appendText: { type: 'string', description: nls.localize('schema.onEnterRules.action.appendText', 'Describes text to be appended after the new line and after the indentation.'), default: '', }, removeText: { type: 'number', description: nls.localize('schema.onEnterRules.action.removeText', 'Describes the number of characters to remove from the new line\'s indentation.'), default: 0, } } } } } } } }; const schemaRegistry = Registry.as<IJSONContributionRegistry>(Extensions.JSONContribution); schemaRegistry.registerSchema(schemaId, schema);
src/vs/workbench/contrib/codeEditor/browser/languageConfigurationExtensionPoint.ts
0
https://github.com/microsoft/vscode/commit/ac6641096645db4a29b2798de3fc8d11cf6ec0e5
[ 0.00043395633110776544, 0.00017431499145459384, 0.00016564628458581865, 0.0001714685931801796, 0.00002858685729734134 ]
{ "id": 1, "code_window": [ "import { ensureNoDisposablesAreLeakedInTestSuite } from 'vs/base/test/common/utils';\n", "import { toDisposable } from 'vs/base/common/lifecycle';\n", "import { mainWindow } from 'vs/base/browser/window';\n", "\n", "// Sets up an `onShow` listener to allow us to wait until the quick pick is shown (useful when triggering an `accept()` right after launching a quick pick)\n", "// kick this off before you launch the picker and then await the promise returned after you launch the picker.\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { QuickPick } from 'vs/platform/quickinput/browser/quickInput';\n", "import { IQuickPickItem } from 'vs/platform/quickinput/common/quickInput';\n" ], "file_path": "src/vs/platform/quickinput/test/browser/quickinput.test.ts", "type": "add", "edit_start_line_idx": 20 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { distinct } from 'vs/base/common/arrays'; import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { ILocalExtension } from 'vs/platform/extensionManagement/common/extensionManagement'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; export const IIgnoredExtensionsManagementService = createDecorator<IIgnoredExtensionsManagementService>('IIgnoredExtensionsManagementService'); export interface IIgnoredExtensionsManagementService { readonly _serviceBrand: any; getIgnoredExtensions(installed: ILocalExtension[]): string[]; hasToNeverSyncExtension(extensionId: string): boolean; hasToAlwaysSyncExtension(extensionId: string): boolean; updateIgnoredExtensions(ignoredExtensionId: string, ignore: boolean): Promise<void>; updateSynchronizedExtensions(ignoredExtensionId: string, sync: boolean): Promise<void>; } export class IgnoredExtensionsManagementService implements IIgnoredExtensionsManagementService { declare readonly _serviceBrand: undefined; constructor( @IConfigurationService private readonly configurationService: IConfigurationService, ) { } hasToNeverSyncExtension(extensionId: string): boolean { const configuredIgnoredExtensions = this.getConfiguredIgnoredExtensions(); return configuredIgnoredExtensions.includes(extensionId.toLowerCase()); } hasToAlwaysSyncExtension(extensionId: string): boolean { const configuredIgnoredExtensions = this.getConfiguredIgnoredExtensions(); return configuredIgnoredExtensions.includes(`-${extensionId.toLowerCase()}`); } updateIgnoredExtensions(ignoredExtensionId: string, ignore: boolean): Promise<void> { // first remove the extension completely from ignored extensions let currentValue = [...this.configurationService.getValue<string[]>('settingsSync.ignoredExtensions')].map(id => id.toLowerCase()); currentValue = currentValue.filter(v => v !== ignoredExtensionId && v !== `-${ignoredExtensionId}`); // Add only if ignored if (ignore) { currentValue.push(ignoredExtensionId.toLowerCase()); } return this.configurationService.updateValue('settingsSync.ignoredExtensions', currentValue.length ? currentValue : undefined, ConfigurationTarget.USER); } updateSynchronizedExtensions(extensionId: string, sync: boolean): Promise<void> { // first remove the extension completely from ignored extensions let currentValue = [...this.configurationService.getValue<string[]>('settingsSync.ignoredExtensions')].map(id => id.toLowerCase()); currentValue = currentValue.filter(v => v !== extensionId && v !== `-${extensionId}`); // Add only if synced if (sync) { currentValue.push(`-${extensionId.toLowerCase()}`); } return this.configurationService.updateValue('settingsSync.ignoredExtensions', currentValue.length ? currentValue : undefined, ConfigurationTarget.USER); } getIgnoredExtensions(installed: ILocalExtension[]): string[] { const defaultIgnoredExtensions = installed.filter(i => i.isMachineScoped).map(i => i.identifier.id.toLowerCase()); const value = this.getConfiguredIgnoredExtensions().map(id => id.toLowerCase()); const added: string[] = [], removed: string[] = []; if (Array.isArray(value)) { for (const key of value) { if (key.startsWith('-')) { removed.push(key.substring(1)); } else { added.push(key); } } } return distinct([...defaultIgnoredExtensions, ...added,].filter(setting => !removed.includes(setting))); } private getConfiguredIgnoredExtensions(): ReadonlyArray<string> { let userValue = this.configurationService.inspect<string[]>('settingsSync.ignoredExtensions').userValue; if (userValue !== undefined) { return userValue; } userValue = this.configurationService.inspect<string[]>('sync.ignoredExtensions').userValue; if (userValue !== undefined) { return userValue; } return (this.configurationService.getValue<string[]>('settingsSync.ignoredExtensions') || []).map(id => id.toLowerCase()); } }
src/vs/platform/userDataSync/common/ignoredExtensions.ts
0
https://github.com/microsoft/vscode/commit/ac6641096645db4a29b2798de3fc8d11cf6ec0e5
[ 0.00017307398957200348, 0.00017017697973642498, 0.00016626041906420141, 0.00017062568804249167, 0.0000022319222807709593 ]
{ "id": 2, "code_window": [ "\t\t\tquickpick.dispose();\n", "\t\t}\n", "\t});\n", "\n", "\ttest('keepScrollPosition - works with activeItems', async () => {\n", "\t\tconst quickpick = store.add(controller.createQuickPick());\n", "\n", "\t\tconst items = [];\n", "\t\tfor (let i = 0; i < 1000; i++) {\n", "\t\t\titems.push({ label: `item ${i}` });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst quickpick = store.add(controller.createQuickPick() as QuickPick<IQuickPickItem>);\n" ], "file_path": "src/vs/platform/quickinput/test/browser/quickinput.test.ts", "type": "replace", "edit_start_line_idx": 148 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { unthemedInboxStyles } from 'vs/base/browser/ui/inputbox/inputBox'; import { unthemedButtonStyles } from 'vs/base/browser/ui/button/button'; import { IListRenderer, IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { IListOptions, List, unthemedListStyles } from 'vs/base/browser/ui/list/listWidget'; import { unthemedToggleStyles } from 'vs/base/browser/ui/toggle/toggle'; import { raceTimeout } from 'vs/base/common/async'; import { unthemedCountStyles } from 'vs/base/browser/ui/countBadge/countBadge'; import { unthemedKeybindingLabelOptions } from 'vs/base/browser/ui/keybindingLabel/keybindingLabel'; import { unthemedProgressBarOptions } from 'vs/base/browser/ui/progressbar/progressbar'; import { QuickInputController } from 'vs/platform/quickinput/browser/quickInputController'; import { TestThemeService } from 'vs/platform/theme/test/common/testThemeService'; import { ensureNoDisposablesAreLeakedInTestSuite } from 'vs/base/test/common/utils'; import { toDisposable } from 'vs/base/common/lifecycle'; import { mainWindow } from 'vs/base/browser/window'; // Sets up an `onShow` listener to allow us to wait until the quick pick is shown (useful when triggering an `accept()` right after launching a quick pick) // kick this off before you launch the picker and then await the promise returned after you launch the picker. async function setupWaitTilShownListener(controller: QuickInputController): Promise<void> { const result = await raceTimeout(new Promise<boolean>(resolve => { const event = controller.onShow(_ => { event.dispose(); resolve(true); }); }), 2000); if (!result) { throw new Error('Cancelled'); } } suite('QuickInput', () => { // https://github.com/microsoft/vscode/issues/147543 const store = ensureNoDisposablesAreLeakedInTestSuite(); let controller: QuickInputController; setup(() => { const fixture = document.createElement('div'); mainWindow.document.body.appendChild(fixture); store.add(toDisposable(() => mainWindow.document.body.removeChild(fixture))); controller = store.add(new QuickInputController({ container: fixture, idPrefix: 'testQuickInput', ignoreFocusOut() { return true; }, returnFocus() { }, backKeybindingLabel() { return undefined; }, setContextKey() { return undefined; }, linkOpenerDelegate(content) { }, createList: <T>( user: string, container: HTMLElement, delegate: IListVirtualDelegate<T>, renderers: IListRenderer<T, any>[], options: IListOptions<T>, ) => new List<T>(user, container, delegate, renderers, options), hoverDelegate: { showHover(options, focus) { return undefined; }, delay: 200 }, styles: { button: unthemedButtonStyles, countBadge: unthemedCountStyles, inputBox: unthemedInboxStyles, toggle: unthemedToggleStyles, keybindingLabel: unthemedKeybindingLabelOptions, list: unthemedListStyles, progressBar: unthemedProgressBarOptions, widget: { quickInputBackground: undefined, quickInputForeground: undefined, quickInputTitleBackground: undefined, widgetBorder: undefined, widgetShadow: undefined, }, pickerGroup: { pickerGroupBorder: undefined, pickerGroupForeground: undefined, } } }, new TestThemeService(), { activeContainer: fixture } as any)); // initial layout controller.layout({ height: 20, width: 40 }, 0); }); test('pick - basecase', async () => { const item = { label: 'foo' }; const wait = setupWaitTilShownListener(controller); const pickPromise = controller.pick([item, { label: 'bar' }]); await wait; controller.accept(); const pick = await raceTimeout(pickPromise, 2000); assert.strictEqual(pick, item); }); test('pick - activeItem is honored', async () => { const item = { label: 'foo' }; const wait = setupWaitTilShownListener(controller); const pickPromise = controller.pick([{ label: 'bar' }, item], { activeItem: item }); await wait; controller.accept(); const pick = await pickPromise; assert.strictEqual(pick, item); }); test('input - basecase', async () => { const wait = setupWaitTilShownListener(controller); const inputPromise = controller.input({ value: 'foo' }); await wait; controller.accept(); const value = await raceTimeout(inputPromise, 2000); assert.strictEqual(value, 'foo'); }); test('onDidChangeValue - gets triggered when .value is set', async () => { const quickpick = store.add(controller.createQuickPick()); let value: string | undefined = undefined; store.add(quickpick.onDidChangeValue((e) => value = e)); // Trigger a change quickpick.value = 'changed'; try { assert.strictEqual(value, quickpick.value); } finally { quickpick.dispose(); } }); test('keepScrollPosition - works with activeItems', async () => { const quickpick = store.add(controller.createQuickPick()); const items = []; for (let i = 0; i < 1000; i++) { items.push({ label: `item ${i}` }); } quickpick.items = items; // setting the active item should cause the quick pick to scroll to the bottom quickpick.activeItems = [items[items.length - 1]]; quickpick.show(); const cursorTop = quickpick.scrollTop; assert.notStrictEqual(cursorTop, 0); quickpick.keepScrollPosition = true; quickpick.activeItems = [items[0]]; assert.strictEqual(cursorTop, quickpick.scrollTop); quickpick.keepScrollPosition = false; quickpick.activeItems = [items[0]]; assert.strictEqual(quickpick.scrollTop, 0); }); test('keepScrollPosition - works with items', async () => { const quickpick = store.add(controller.createQuickPick()); const items = []; for (let i = 0; i < 1000; i++) { items.push({ label: `item ${i}` }); } quickpick.items = items; // setting the active item should cause the quick pick to scroll to the bottom quickpick.activeItems = [items[items.length - 1]]; quickpick.show(); const cursorTop = quickpick.scrollTop; assert.notStrictEqual(cursorTop, 0); quickpick.keepScrollPosition = true; quickpick.items = items; assert.strictEqual(cursorTop, quickpick.scrollTop); quickpick.keepScrollPosition = false; quickpick.items = items; assert.strictEqual(quickpick.scrollTop, 0); }); test('selectedItems - verify previous selectedItems does not hang over to next set of items', async () => { const quickpick = store.add(controller.createQuickPick()); quickpick.items = [{ label: 'step 1' }]; quickpick.show(); void (await new Promise<void>(resolve => { store.add(quickpick.onDidAccept(() => { quickpick.canSelectMany = true; quickpick.items = [{ label: 'a' }, { label: 'b' }, { label: 'c' }]; resolve(); })); // accept 'step 1' controller.accept(); })); // accept in multi-select controller.accept(); // Since we don't select any items, the selected items should be empty assert.strictEqual(quickpick.selectedItems.length, 0); }); });
src/vs/platform/quickinput/test/browser/quickinput.test.ts
1
https://github.com/microsoft/vscode/commit/ac6641096645db4a29b2798de3fc8d11cf6ec0e5
[ 0.9992883801460266, 0.36695167422294617, 0.00016494462033733726, 0.0023147552274167538, 0.47688451409339905 ]
{ "id": 2, "code_window": [ "\t\t\tquickpick.dispose();\n", "\t\t}\n", "\t});\n", "\n", "\ttest('keepScrollPosition - works with activeItems', async () => {\n", "\t\tconst quickpick = store.add(controller.createQuickPick());\n", "\n", "\t\tconst items = [];\n", "\t\tfor (let i = 0; i < 1000; i++) {\n", "\t\t\titems.push({ label: `item ${i}` });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst quickpick = store.add(controller.createQuickPick() as QuickPick<IQuickPickItem>);\n" ], "file_path": "src/vs/platform/quickinput/test/browser/quickinput.test.ts", "type": "replace", "edit_start_line_idx": 148 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { findLast } from 'vs/base/common/arraysFind'; import { Disposable } from 'vs/base/common/lifecycle'; import { derived, derivedObservableWithWritableCache, IObservable, IReader, ITransaction, observableValue, transaction } from 'vs/base/common/observable'; import { Range } from 'vs/editor/common/core/range'; import { ScrollType } from 'vs/editor/common/editorCommon'; import { ITextModel } from 'vs/editor/common/model'; import { localize } from 'vs/nls'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { LineRange } from 'vs/workbench/contrib/mergeEditor/browser/model/lineRange'; import { MergeEditorModel } from 'vs/workbench/contrib/mergeEditor/browser/model/mergeEditorModel'; import { InputNumber, ModifiedBaseRange, ModifiedBaseRangeState } from 'vs/workbench/contrib/mergeEditor/browser/model/modifiedBaseRange'; import { observableConfigValue } from 'vs/workbench/contrib/mergeEditor/browser/utils'; import { BaseCodeEditorView } from 'vs/workbench/contrib/mergeEditor/browser/view/editors/baseCodeEditorView'; import { CodeEditorView } from 'vs/workbench/contrib/mergeEditor/browser/view/editors/codeEditorView'; import { InputCodeEditorView } from 'vs/workbench/contrib/mergeEditor/browser/view/editors/inputCodeEditorView'; import { ResultCodeEditorView } from 'vs/workbench/contrib/mergeEditor/browser/view/editors/resultCodeEditorView'; export class MergeEditorViewModel extends Disposable { private readonly manuallySetActiveModifiedBaseRange = observableValue< { range: ModifiedBaseRange | undefined; counter: number } >(this, { range: undefined, counter: 0 }); private readonly attachedHistory = this._register(new AttachedHistory(this.model.resultTextModel)); constructor( public readonly model: MergeEditorModel, public readonly inputCodeEditorView1: InputCodeEditorView, public readonly inputCodeEditorView2: InputCodeEditorView, public readonly resultCodeEditorView: ResultCodeEditorView, public readonly baseCodeEditorView: IObservable<BaseCodeEditorView | undefined>, public readonly showNonConflictingChanges: IObservable<boolean>, @IConfigurationService private readonly configurationService: IConfigurationService, @INotificationService private readonly notificationService: INotificationService, ) { super(); this._register(resultCodeEditorView.editor.onDidChangeModelContent(e => { if (this.model.isApplyingEditInResult || e.isRedoing || e.isUndoing) { return; } const baseRangeStates: ModifiedBaseRange[] = []; for (const change of e.changes) { const rangeInBase = this.model.translateResultRangeToBase(Range.lift(change.range)); const baseRanges = this.model.findModifiedBaseRangesInRange(new LineRange(rangeInBase.startLineNumber, rangeInBase.endLineNumber - rangeInBase.startLineNumber)); if (baseRanges.length === 1) { const isHandled = this.model.isHandled(baseRanges[0]).get(); if (!isHandled) { baseRangeStates.push(baseRanges[0]); } } } if (baseRangeStates.length === 0) { return; } const element = { model: this.model, redo() { transaction(tx => { /** @description Mark conflicts touched by manual edits as handled */ for (const r of baseRangeStates) { this.model.setHandled(r, true, tx); } }); }, undo() { transaction(tx => { /** @description Mark conflicts touched by manual edits as handled */ for (const r of baseRangeStates) { this.model.setHandled(r, false, tx); } }); }, }; this.attachedHistory.pushAttachedHistoryElement(element); element.redo(); })); } public readonly shouldUseAppendInsteadOfAccept = observableConfigValue<boolean>( 'mergeEditor.shouldUseAppendInsteadOfAccept', false, this.configurationService, ); private counter = 0; private readonly lastFocusedEditor = derivedObservableWithWritableCache< { view: CodeEditorView | undefined; counter: number } >(this, (reader, lastValue) => { const editors = [ this.inputCodeEditorView1, this.inputCodeEditorView2, this.resultCodeEditorView, this.baseCodeEditorView.read(reader), ]; const view = editors.find((e) => e && e.isFocused.read(reader)); return view ? { view, counter: this.counter++ } : lastValue || { view: undefined, counter: this.counter++ }; }); public readonly baseShowDiffAgainst = derived<1 | 2 | undefined>(this, reader => { const lastFocusedEditor = this.lastFocusedEditor.read(reader); if (lastFocusedEditor.view === this.inputCodeEditorView1) { return 1; } else if (lastFocusedEditor.view === this.inputCodeEditorView2) { return 2; } return undefined; }); public readonly selectionInBase = derived(this, reader => { const sourceEditor = this.lastFocusedEditor.read(reader).view; if (!sourceEditor) { return undefined; } const selections = sourceEditor.selection.read(reader) || []; const rangesInBase = selections.map((selection) => { if (sourceEditor === this.inputCodeEditorView1) { return this.model.translateInputRangeToBase(1, selection); } else if (sourceEditor === this.inputCodeEditorView2) { return this.model.translateInputRangeToBase(2, selection); } else if (sourceEditor === this.resultCodeEditorView) { return this.model.translateResultRangeToBase(selection); } else if (sourceEditor === this.baseCodeEditorView.read(reader)) { return selection; } else { return selection; } }); return { rangesInBase, sourceEditor }; }); private getRangeOfModifiedBaseRange(editor: CodeEditorView, modifiedBaseRange: ModifiedBaseRange, reader: IReader | undefined): LineRange { if (editor === this.resultCodeEditorView) { return this.model.getLineRangeInResult(modifiedBaseRange.baseRange, reader); } else if (editor === this.baseCodeEditorView.get()) { return modifiedBaseRange.baseRange; } else { const input = editor === this.inputCodeEditorView1 ? 1 : 2; return modifiedBaseRange.getInputRange(input); } } public readonly activeModifiedBaseRange = derived(this, (reader) => { /** @description activeModifiedBaseRange */ const focusedEditor = this.lastFocusedEditor.read(reader); const manualRange = this.manuallySetActiveModifiedBaseRange.read(reader); if (manualRange.counter > focusedEditor.counter) { return manualRange.range; } if (!focusedEditor.view) { return; } const cursorLineNumber = focusedEditor.view.cursorLineNumber.read(reader); if (!cursorLineNumber) { return undefined; } const modifiedBaseRanges = this.model.modifiedBaseRanges.read(reader); return modifiedBaseRanges.find((r) => { const range = this.getRangeOfModifiedBaseRange(focusedEditor.view!, r, reader); return range.isEmpty ? range.startLineNumber === cursorLineNumber : range.contains(cursorLineNumber); }); } ); public setActiveModifiedBaseRange(range: ModifiedBaseRange | undefined, tx: ITransaction): void { this.manuallySetActiveModifiedBaseRange.set({ range, counter: this.counter++ }, tx); } public setState( baseRange: ModifiedBaseRange, state: ModifiedBaseRangeState, tx: ITransaction, inputNumber: InputNumber, ): void { this.manuallySetActiveModifiedBaseRange.set({ range: baseRange, counter: this.counter++ }, tx); this.model.setState(baseRange, state, inputNumber, tx); } private goToConflict(getModifiedBaseRange: (editor: CodeEditorView, curLineNumber: number) => ModifiedBaseRange | undefined): void { let editor = this.lastFocusedEditor.get().view; if (!editor) { editor = this.resultCodeEditorView; } const curLineNumber = editor.editor.getPosition()?.lineNumber; if (curLineNumber === undefined) { return; } const modifiedBaseRange = getModifiedBaseRange(editor, curLineNumber); if (modifiedBaseRange) { const range = this.getRangeOfModifiedBaseRange(editor, modifiedBaseRange, undefined); editor.editor.focus(); let startLineNumber = range.startLineNumber; let endLineNumberExclusive = range.endLineNumberExclusive; if (range.startLineNumber > editor.editor.getModel()!.getLineCount()) { transaction(tx => { this.setActiveModifiedBaseRange(modifiedBaseRange, tx); }); startLineNumber = endLineNumberExclusive = editor.editor.getModel()!.getLineCount(); } editor.editor.setPosition({ lineNumber: startLineNumber, column: editor.editor.getModel()!.getLineFirstNonWhitespaceColumn(startLineNumber), }); editor.editor.revealLinesNearTop(startLineNumber, endLineNumberExclusive, ScrollType.Smooth); } } public goToNextModifiedBaseRange(predicate: (m: ModifiedBaseRange) => boolean): void { this.goToConflict( (e, l) => this.model.modifiedBaseRanges .get() .find( (r) => predicate(r) && this.getRangeOfModifiedBaseRange(e, r, undefined).startLineNumber > l ) || this.model.modifiedBaseRanges .get() .find((r) => predicate(r)) ); } public goToPreviousModifiedBaseRange(predicate: (m: ModifiedBaseRange) => boolean): void { this.goToConflict( (e, l) => findLast( this.model.modifiedBaseRanges.get(), (r) => predicate(r) && this.getRangeOfModifiedBaseRange(e, r, undefined).endLineNumberExclusive < l ) || findLast( this.model.modifiedBaseRanges.get(), (r) => predicate(r) ) ); } public toggleActiveConflict(inputNumber: 1 | 2): void { const activeModifiedBaseRange = this.activeModifiedBaseRange.get(); if (!activeModifiedBaseRange) { this.notificationService.error(localize('noConflictMessage', "There is currently no conflict focused that can be toggled.")); return; } transaction(tx => { /** @description Toggle Active Conflict */ this.setState( activeModifiedBaseRange, this.model.getState(activeModifiedBaseRange).get().toggle(inputNumber), tx, inputNumber, ); }); } public acceptAll(inputNumber: 1 | 2): void { transaction(tx => { /** @description Toggle Active Conflict */ for (const range of this.model.modifiedBaseRanges.get()) { this.setState( range, this.model.getState(range).get().withInputValue(inputNumber, true), tx, inputNumber ); } }); } } class AttachedHistory extends Disposable { private readonly attachedHistory: { element: IAttachedHistoryElement; altId: number }[] = []; private previousAltId: number = this.model.getAlternativeVersionId(); constructor(private readonly model: ITextModel) { super(); this._register(model.onDidChangeContent((e) => { const currentAltId = model.getAlternativeVersionId(); if (e.isRedoing) { for (const item of this.attachedHistory) { if (this.previousAltId < item.altId && item.altId <= currentAltId) { item.element.redo(); } } } else if (e.isUndoing) { for (let i = this.attachedHistory.length - 1; i >= 0; i--) { const item = this.attachedHistory[i]; if (currentAltId < item.altId && item.altId <= this.previousAltId) { item.element.undo(); } } } else { // The user destroyed the redo stack by performing a non redo/undo operation. // Thus we also need to remove all history elements after the last version id. while ( this.attachedHistory.length > 0 && this.attachedHistory[this.attachedHistory.length - 1]!.altId > this.previousAltId ) { this.attachedHistory.pop(); } } this.previousAltId = currentAltId; })); } /** * Pushes an history item that is tied to the last text edit (or an extension of it). * When the last text edit is undone/redone, so is is this history item. */ public pushAttachedHistoryElement(element: IAttachedHistoryElement): void { this.attachedHistory.push({ altId: this.model.getAlternativeVersionId(), element }); } } interface IAttachedHistoryElement { undo(): void; redo(): void; }
src/vs/workbench/contrib/mergeEditor/browser/view/viewModel.ts
0
https://github.com/microsoft/vscode/commit/ac6641096645db4a29b2798de3fc8d11cf6ec0e5
[ 0.019264470785856247, 0.0007192401681095362, 0.00016609151498414576, 0.00017437433416489512, 0.003180481493473053 ]
{ "id": 2, "code_window": [ "\t\t\tquickpick.dispose();\n", "\t\t}\n", "\t});\n", "\n", "\ttest('keepScrollPosition - works with activeItems', async () => {\n", "\t\tconst quickpick = store.add(controller.createQuickPick());\n", "\n", "\t\tconst items = [];\n", "\t\tfor (let i = 0; i < 1000; i++) {\n", "\t\t\titems.push({ label: `item ${i}` });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst quickpick = store.add(controller.createQuickPick() as QuickPick<IQuickPickItem>);\n" ], "file_path": "src/vs/platform/quickinput/test/browser/quickinput.test.ts", "type": "replace", "edit_start_line_idx": 148 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from 'vs/nls'; import { Event } from 'vs/base/common/event'; import { onUnexpectedError } from 'vs/base/common/errors'; import { Disposable } from 'vs/base/common/lifecycle'; import { IExtensionManagementService, ILocalExtension, IExtensionIdentifier, InstallOperation } from 'vs/platform/extensionManagement/common/extensionManagement'; import { IWorkbenchExtensionEnablementService, EnablementState } from 'vs/workbench/services/extensionManagement/common/extensionManagement'; import { IExtensionRecommendationsService } from 'vs/workbench/services/extensionRecommendations/common/extensionRecommendations'; import { ILifecycleService } from 'vs/workbench/services/lifecycle/common/lifecycle'; import { IWorkbenchContribution } from 'vs/workbench/common/contributions'; import { ServicesAccessor, IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { areSameExtensions } from 'vs/platform/extensionManagement/common/extensionManagementUtil'; import { Severity, INotificationService } from 'vs/platform/notification/common/notification'; export interface IExtensionStatus { identifier: IExtensionIdentifier; local: ILocalExtension; globallyEnabled: boolean; } export class KeymapExtensions extends Disposable implements IWorkbenchContribution { constructor( @IInstantiationService private readonly instantiationService: IInstantiationService, @IWorkbenchExtensionEnablementService private readonly extensionEnablementService: IWorkbenchExtensionEnablementService, @IExtensionRecommendationsService private readonly tipsService: IExtensionRecommendationsService, @ILifecycleService lifecycleService: ILifecycleService, @INotificationService private readonly notificationService: INotificationService, ) { super(); this._register(lifecycleService.onDidShutdown(() => this.dispose())); this._register(instantiationService.invokeFunction(onExtensionChanged)((identifiers => { Promise.all(identifiers.map(identifier => this.checkForOtherKeymaps(identifier))) .then(undefined, onUnexpectedError); }))); } private checkForOtherKeymaps(extensionIdentifier: IExtensionIdentifier): Promise<void> { return this.instantiationService.invokeFunction(getInstalledExtensions).then(extensions => { const keymaps = extensions.filter(extension => isKeymapExtension(this.tipsService, extension)); const extension = keymaps.find(extension => areSameExtensions(extension.identifier, extensionIdentifier)); if (extension && extension.globallyEnabled) { const otherKeymaps = keymaps.filter(extension => !areSameExtensions(extension.identifier, extensionIdentifier) && extension.globallyEnabled); if (otherKeymaps.length) { return this.promptForDisablingOtherKeymaps(extension, otherKeymaps); } } return undefined; }); } private promptForDisablingOtherKeymaps(newKeymap: IExtensionStatus, oldKeymaps: IExtensionStatus[]): void { const onPrompt = (confirmed: boolean) => { if (confirmed) { this.extensionEnablementService.setEnablement(oldKeymaps.map(keymap => keymap.local), EnablementState.DisabledGlobally); } }; this.notificationService.prompt(Severity.Info, localize('disableOtherKeymapsConfirmation', "Disable other keymaps ({0}) to avoid conflicts between keybindings?", oldKeymaps.map(k => `'${k.local.manifest.displayName}'`).join(', ')), [{ label: localize('yes', "Yes"), run: () => onPrompt(true) }, { label: localize('no', "No"), run: () => onPrompt(false) }] ); } } function onExtensionChanged(accessor: ServicesAccessor): Event<IExtensionIdentifier[]> { const extensionService = accessor.get(IExtensionManagementService); const extensionEnablementService = accessor.get(IWorkbenchExtensionEnablementService); const onDidInstallExtensions = Event.chain(extensionService.onDidInstallExtensions, $ => $.filter(e => e.some(({ operation }) => operation === InstallOperation.Install)) .map(e => e.map(({ identifier }) => identifier)) ); return Event.debounce<IExtensionIdentifier[], IExtensionIdentifier[]>(Event.any( Event.any(onDidInstallExtensions, Event.map(extensionService.onDidUninstallExtension, e => [e.identifier])), Event.map(extensionEnablementService.onEnablementChanged, extensions => extensions.map(e => e.identifier)) ), (result: IExtensionIdentifier[] | undefined, identifiers: IExtensionIdentifier[]) => { result = result || []; for (const identifier of identifiers) { if (result.some(l => !areSameExtensions(l, identifier))) { result.push(identifier); } } return result; }); } export async function getInstalledExtensions(accessor: ServicesAccessor): Promise<IExtensionStatus[]> { const extensionService = accessor.get(IExtensionManagementService); const extensionEnablementService = accessor.get(IWorkbenchExtensionEnablementService); const extensions = await extensionService.getInstalled(); return extensions.map(extension => { return { identifier: extension.identifier, local: extension, globallyEnabled: extensionEnablementService.isEnabled(extension) }; }); } function isKeymapExtension(tipsService: IExtensionRecommendationsService, extension: IExtensionStatus): boolean { const cats = extension.local.manifest.categories; return cats && cats.indexOf('Keymaps') !== -1 || tipsService.getKeymapRecommendations().some(extensionId => areSameExtensions({ id: extensionId }, extension.local.identifier)); }
src/vs/workbench/contrib/extensions/common/extensionsUtils.ts
0
https://github.com/microsoft/vscode/commit/ac6641096645db4a29b2798de3fc8d11cf6ec0e5
[ 0.00017690497043076903, 0.00017394544556736946, 0.0001701267174212262, 0.00017401445074938238, 0.0000022407946289604297 ]
{ "id": 2, "code_window": [ "\t\t\tquickpick.dispose();\n", "\t\t}\n", "\t});\n", "\n", "\ttest('keepScrollPosition - works with activeItems', async () => {\n", "\t\tconst quickpick = store.add(controller.createQuickPick());\n", "\n", "\t\tconst items = [];\n", "\t\tfor (let i = 0; i < 1000; i++) {\n", "\t\t\titems.push({ label: `item ${i}` });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst quickpick = store.add(controller.createQuickPick() as QuickPick<IQuickPickItem>);\n" ], "file_path": "src/vs/platform/quickinput/test/browser/quickinput.test.ts", "type": "replace", "edit_start_line_idx": 148 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import type { VSBuffer } from 'vs/base/common/buffer'; import type { CancellationToken } from 'vs/base/common/cancellation'; export interface IRPCProtocol { /** * Returns a proxy to an object addressable/named in the extension host process or in the renderer process. */ getProxy<T>(identifier: ProxyIdentifier<T>): Proxied<T>; /** * Register manually created instance. */ set<T, R extends T>(identifier: ProxyIdentifier<T>, instance: R): R; /** * Assert these identifiers are already registered via `.set`. */ assertRegistered(identifiers: ProxyIdentifier<any>[]): void; /** * Wait for the write buffer (if applicable) to become empty. */ drain(): Promise<void>; dispose(): void; } export class ProxyIdentifier<T> { public static count = 0; _proxyIdentifierBrand: void = undefined; public readonly sid: string; public readonly nid: number; constructor(sid: string) { this.sid = sid; this.nid = (++ProxyIdentifier.count); } } const identifiers: ProxyIdentifier<any>[] = []; export function createProxyIdentifier<T>(identifier: string): ProxyIdentifier<T> { const result = new ProxyIdentifier<T>(identifier); identifiers[result.nid] = result; return result; } /** * Mapped-type that replaces all JSONable-types with their toJSON-result type */ export type Dto<T> = T extends { toJSON(): infer U } ? U : T extends VSBuffer // VSBuffer is understood by rpc-logic ? T : T extends CancellationToken // CancellationToken is understood by rpc-logic ? T : T extends Function // functions are dropped during JSON-stringify ? never : T extends object // recurse ? { [k in keyof T]: Dto<T[k]>; } : T; export type Proxied<T> = { [K in keyof T]: T[K] extends (...args: infer A) => infer R ? (...args: { [K in keyof A]: Dto<A[K]> }) => Promise<Dto<Awaited<R>>> : never }; export function getStringIdentifierForProxy(nid: number): string { return identifiers[nid].sid; } /** * Marks the object as containing buffers that should be serialized more efficiently. */ export class SerializableObjectWithBuffers<T> { constructor( public readonly value: T ) { } }
src/vs/workbench/services/extensions/common/proxyIdentifier.ts
0
https://github.com/microsoft/vscode/commit/ac6641096645db4a29b2798de3fc8d11cf6ec0e5
[ 0.0005276111769489944, 0.00021119127632118762, 0.0001663350994931534, 0.00017236583516933024, 0.00011191271914867684 ]
{ "id": 3, "code_window": [ "\t\tassert.strictEqual(quickpick.scrollTop, 0);\n", "\t});\n", "\n", "\ttest('keepScrollPosition - works with items', async () => {\n", "\t\tconst quickpick = store.add(controller.createQuickPick());\n", "\n", "\t\tconst items = [];\n", "\t\tfor (let i = 0; i < 1000; i++) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst quickpick = store.add(controller.createQuickPick() as QuickPick<IQuickPickItem>);\n" ], "file_path": "src/vs/platform/quickinput/test/browser/quickinput.test.ts", "type": "replace", "edit_start_line_idx": 173 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { unthemedInboxStyles } from 'vs/base/browser/ui/inputbox/inputBox'; import { unthemedButtonStyles } from 'vs/base/browser/ui/button/button'; import { IListRenderer, IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { IListOptions, List, unthemedListStyles } from 'vs/base/browser/ui/list/listWidget'; import { unthemedToggleStyles } from 'vs/base/browser/ui/toggle/toggle'; import { raceTimeout } from 'vs/base/common/async'; import { unthemedCountStyles } from 'vs/base/browser/ui/countBadge/countBadge'; import { unthemedKeybindingLabelOptions } from 'vs/base/browser/ui/keybindingLabel/keybindingLabel'; import { unthemedProgressBarOptions } from 'vs/base/browser/ui/progressbar/progressbar'; import { QuickInputController } from 'vs/platform/quickinput/browser/quickInputController'; import { TestThemeService } from 'vs/platform/theme/test/common/testThemeService'; import { ensureNoDisposablesAreLeakedInTestSuite } from 'vs/base/test/common/utils'; import { toDisposable } from 'vs/base/common/lifecycle'; import { mainWindow } from 'vs/base/browser/window'; // Sets up an `onShow` listener to allow us to wait until the quick pick is shown (useful when triggering an `accept()` right after launching a quick pick) // kick this off before you launch the picker and then await the promise returned after you launch the picker. async function setupWaitTilShownListener(controller: QuickInputController): Promise<void> { const result = await raceTimeout(new Promise<boolean>(resolve => { const event = controller.onShow(_ => { event.dispose(); resolve(true); }); }), 2000); if (!result) { throw new Error('Cancelled'); } } suite('QuickInput', () => { // https://github.com/microsoft/vscode/issues/147543 const store = ensureNoDisposablesAreLeakedInTestSuite(); let controller: QuickInputController; setup(() => { const fixture = document.createElement('div'); mainWindow.document.body.appendChild(fixture); store.add(toDisposable(() => mainWindow.document.body.removeChild(fixture))); controller = store.add(new QuickInputController({ container: fixture, idPrefix: 'testQuickInput', ignoreFocusOut() { return true; }, returnFocus() { }, backKeybindingLabel() { return undefined; }, setContextKey() { return undefined; }, linkOpenerDelegate(content) { }, createList: <T>( user: string, container: HTMLElement, delegate: IListVirtualDelegate<T>, renderers: IListRenderer<T, any>[], options: IListOptions<T>, ) => new List<T>(user, container, delegate, renderers, options), hoverDelegate: { showHover(options, focus) { return undefined; }, delay: 200 }, styles: { button: unthemedButtonStyles, countBadge: unthemedCountStyles, inputBox: unthemedInboxStyles, toggle: unthemedToggleStyles, keybindingLabel: unthemedKeybindingLabelOptions, list: unthemedListStyles, progressBar: unthemedProgressBarOptions, widget: { quickInputBackground: undefined, quickInputForeground: undefined, quickInputTitleBackground: undefined, widgetBorder: undefined, widgetShadow: undefined, }, pickerGroup: { pickerGroupBorder: undefined, pickerGroupForeground: undefined, } } }, new TestThemeService(), { activeContainer: fixture } as any)); // initial layout controller.layout({ height: 20, width: 40 }, 0); }); test('pick - basecase', async () => { const item = { label: 'foo' }; const wait = setupWaitTilShownListener(controller); const pickPromise = controller.pick([item, { label: 'bar' }]); await wait; controller.accept(); const pick = await raceTimeout(pickPromise, 2000); assert.strictEqual(pick, item); }); test('pick - activeItem is honored', async () => { const item = { label: 'foo' }; const wait = setupWaitTilShownListener(controller); const pickPromise = controller.pick([{ label: 'bar' }, item], { activeItem: item }); await wait; controller.accept(); const pick = await pickPromise; assert.strictEqual(pick, item); }); test('input - basecase', async () => { const wait = setupWaitTilShownListener(controller); const inputPromise = controller.input({ value: 'foo' }); await wait; controller.accept(); const value = await raceTimeout(inputPromise, 2000); assert.strictEqual(value, 'foo'); }); test('onDidChangeValue - gets triggered when .value is set', async () => { const quickpick = store.add(controller.createQuickPick()); let value: string | undefined = undefined; store.add(quickpick.onDidChangeValue((e) => value = e)); // Trigger a change quickpick.value = 'changed'; try { assert.strictEqual(value, quickpick.value); } finally { quickpick.dispose(); } }); test('keepScrollPosition - works with activeItems', async () => { const quickpick = store.add(controller.createQuickPick()); const items = []; for (let i = 0; i < 1000; i++) { items.push({ label: `item ${i}` }); } quickpick.items = items; // setting the active item should cause the quick pick to scroll to the bottom quickpick.activeItems = [items[items.length - 1]]; quickpick.show(); const cursorTop = quickpick.scrollTop; assert.notStrictEqual(cursorTop, 0); quickpick.keepScrollPosition = true; quickpick.activeItems = [items[0]]; assert.strictEqual(cursorTop, quickpick.scrollTop); quickpick.keepScrollPosition = false; quickpick.activeItems = [items[0]]; assert.strictEqual(quickpick.scrollTop, 0); }); test('keepScrollPosition - works with items', async () => { const quickpick = store.add(controller.createQuickPick()); const items = []; for (let i = 0; i < 1000; i++) { items.push({ label: `item ${i}` }); } quickpick.items = items; // setting the active item should cause the quick pick to scroll to the bottom quickpick.activeItems = [items[items.length - 1]]; quickpick.show(); const cursorTop = quickpick.scrollTop; assert.notStrictEqual(cursorTop, 0); quickpick.keepScrollPosition = true; quickpick.items = items; assert.strictEqual(cursorTop, quickpick.scrollTop); quickpick.keepScrollPosition = false; quickpick.items = items; assert.strictEqual(quickpick.scrollTop, 0); }); test('selectedItems - verify previous selectedItems does not hang over to next set of items', async () => { const quickpick = store.add(controller.createQuickPick()); quickpick.items = [{ label: 'step 1' }]; quickpick.show(); void (await new Promise<void>(resolve => { store.add(quickpick.onDidAccept(() => { quickpick.canSelectMany = true; quickpick.items = [{ label: 'a' }, { label: 'b' }, { label: 'c' }]; resolve(); })); // accept 'step 1' controller.accept(); })); // accept in multi-select controller.accept(); // Since we don't select any items, the selected items should be empty assert.strictEqual(quickpick.selectedItems.length, 0); }); });
src/vs/platform/quickinput/test/browser/quickinput.test.ts
1
https://github.com/microsoft/vscode/commit/ac6641096645db4a29b2798de3fc8d11cf6ec0e5
[ 0.9992159605026245, 0.3726431727409363, 0.00016902109200600535, 0.005762984044849873, 0.4745253622531891 ]
{ "id": 3, "code_window": [ "\t\tassert.strictEqual(quickpick.scrollTop, 0);\n", "\t});\n", "\n", "\ttest('keepScrollPosition - works with items', async () => {\n", "\t\tconst quickpick = store.add(controller.createQuickPick());\n", "\n", "\t\tconst items = [];\n", "\t\tfor (let i = 0; i < 1000; i++) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst quickpick = store.add(controller.createQuickPick() as QuickPick<IQuickPickItem>);\n" ], "file_path": "src/vs/platform/quickinput/test/browser/quickinput.test.ts", "type": "replace", "edit_start_line_idx": 173 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { $window } from 'vs/base/browser/window'; import { applyFontInfo } from 'vs/editor/browser/config/domFontInfo'; import { BareFontInfo } from 'vs/editor/common/config/fontInfo'; export const enum CharWidthRequestType { Regular = 0, Italic = 1, Bold = 2 } export class CharWidthRequest { public readonly chr: string; public readonly type: CharWidthRequestType; public width: number; constructor(chr: string, type: CharWidthRequestType) { this.chr = chr; this.type = type; this.width = 0; } public fulfill(width: number) { this.width = width; } } class DomCharWidthReader { private readonly _bareFontInfo: BareFontInfo; private readonly _requests: CharWidthRequest[]; private _container: HTMLElement | null; private _testElements: HTMLSpanElement[] | null; constructor(bareFontInfo: BareFontInfo, requests: CharWidthRequest[]) { this._bareFontInfo = bareFontInfo; this._requests = requests; this._container = null; this._testElements = null; } public read(): void { // Create a test container with all these test elements this._createDomElements(); // Add the container to the DOM $window.document.body.appendChild(this._container!); // Read character widths this._readFromDomElements(); // Remove the container from the DOM $window.document.body.removeChild(this._container!); this._container = null; this._testElements = null; } private _createDomElements(): void { const container = document.createElement('div'); container.style.position = 'absolute'; container.style.top = '-50000px'; container.style.width = '50000px'; const regularDomNode = document.createElement('div'); applyFontInfo(regularDomNode, this._bareFontInfo); container.appendChild(regularDomNode); const boldDomNode = document.createElement('div'); applyFontInfo(boldDomNode, this._bareFontInfo); boldDomNode.style.fontWeight = 'bold'; container.appendChild(boldDomNode); const italicDomNode = document.createElement('div'); applyFontInfo(italicDomNode, this._bareFontInfo); italicDomNode.style.fontStyle = 'italic'; container.appendChild(italicDomNode); const testElements: HTMLSpanElement[] = []; for (const request of this._requests) { let parent: HTMLElement; if (request.type === CharWidthRequestType.Regular) { parent = regularDomNode; } if (request.type === CharWidthRequestType.Bold) { parent = boldDomNode; } if (request.type === CharWidthRequestType.Italic) { parent = italicDomNode; } parent!.appendChild(document.createElement('br')); const testElement = document.createElement('span'); DomCharWidthReader._render(testElement, request); parent!.appendChild(testElement); testElements.push(testElement); } this._container = container; this._testElements = testElements; } private static _render(testElement: HTMLElement, request: CharWidthRequest): void { if (request.chr === ' ') { let htmlString = '\u00a0'; // Repeat character 256 (2^8) times for (let i = 0; i < 8; i++) { htmlString += htmlString; } testElement.innerText = htmlString; } else { let testString = request.chr; // Repeat character 256 (2^8) times for (let i = 0; i < 8; i++) { testString += testString; } testElement.textContent = testString; } } private _readFromDomElements(): void { for (let i = 0, len = this._requests.length; i < len; i++) { const request = this._requests[i]; const testElement = this._testElements![i]; request.fulfill(testElement.offsetWidth / 256); } } } export function readCharWidths(bareFontInfo: BareFontInfo, requests: CharWidthRequest[]): void { const reader = new DomCharWidthReader(bareFontInfo, requests); reader.read(); }
src/vs/editor/browser/config/charWidthReader.ts
0
https://github.com/microsoft/vscode/commit/ac6641096645db4a29b2798de3fc8d11cf6ec0e5
[ 0.0002793632447719574, 0.00017853379540611058, 0.00016430244431830943, 0.00017089657194446772, 0.000027742991733248346 ]
{ "id": 3, "code_window": [ "\t\tassert.strictEqual(quickpick.scrollTop, 0);\n", "\t});\n", "\n", "\ttest('keepScrollPosition - works with items', async () => {\n", "\t\tconst quickpick = store.add(controller.createQuickPick());\n", "\n", "\t\tconst items = [];\n", "\t\tfor (let i = 0; i < 1000; i++) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst quickpick = store.add(controller.createQuickPick() as QuickPick<IQuickPickItem>);\n" ], "file_path": "src/vs/platform/quickinput/test/browser/quickinput.test.ts", "type": "replace", "edit_start_line_idx": 173 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { IViewletViewOptions } from 'vs/workbench/browser/parts/views/viewsViewlet'; import { normalize, isAbsolute, posix } from 'vs/base/common/path'; import { ViewPane } from 'vs/workbench/browser/parts/views/viewPane'; import { IContextMenuService } from 'vs/platform/contextview/browser/contextView'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { renderViewTree } from 'vs/workbench/contrib/debug/browser/baseDebugView'; import { IDebugSession, IDebugService, CONTEXT_LOADED_SCRIPTS_ITEM_TYPE } from 'vs/workbench/contrib/debug/common/debug'; import { Source } from 'vs/workbench/contrib/debug/common/debugSource'; import { IWorkspaceContextService, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { normalizeDriveLetter, tildify } from 'vs/base/common/labels'; import { isWindows } from 'vs/base/common/platform'; import { URI } from 'vs/base/common/uri'; import { ltrim } from 'vs/base/common/strings'; import { RunOnceScheduler } from 'vs/base/common/async'; import { ResourceLabels, IResourceLabelProps, IResourceLabelOptions, IResourceLabel } from 'vs/workbench/browser/labels'; import { FileKind } from 'vs/platform/files/common/files'; import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { ITreeNode, ITreeFilter, TreeVisibility, TreeFilterResult, ITreeElement } from 'vs/base/browser/ui/tree/tree'; import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { WorkbenchCompressibleObjectTree } from 'vs/platform/list/browser/listService'; import { dispose } from 'vs/base/common/lifecycle'; import { createMatches, FuzzyScore } from 'vs/base/common/filters'; import { DebugContentProvider } from 'vs/workbench/contrib/debug/common/debugContentProvider'; import { ILabelService } from 'vs/platform/label/common/label'; import type { ICompressedTreeNode } from 'vs/base/browser/ui/tree/compressedObjectTreeModel'; import type { ICompressibleTreeRenderer } from 'vs/base/browser/ui/tree/objectTree'; import { IViewDescriptorService } from 'vs/workbench/common/views'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IPathService } from 'vs/workbench/services/path/common/pathService'; import { TreeFindMode } from 'vs/base/browser/ui/tree/abstractTree'; const NEW_STYLE_COMPRESS = true; // RFC 2396, Appendix A: https://www.ietf.org/rfc/rfc2396.txt const URI_SCHEMA_PATTERN = /^[a-zA-Z][a-zA-Z0-9\+\-\.]+:/; type LoadedScriptsItem = BaseTreeItem; class BaseTreeItem { private _showedMoreThanOne: boolean; private _children = new Map<string, BaseTreeItem>(); private _source: Source | undefined; constructor(private _parent: BaseTreeItem | undefined, private _label: string, public readonly isIncompressible = false) { this._showedMoreThanOne = false; } updateLabel(label: string) { this._label = label; } isLeaf(): boolean { return this._children.size === 0; } getSession(): IDebugSession | undefined { if (this._parent) { return this._parent.getSession(); } return undefined; } setSource(session: IDebugSession, source: Source): void { this._source = source; this._children.clear(); if (source.raw && source.raw.sources) { for (const src of source.raw.sources) { if (src.name && src.path) { const s = new BaseTreeItem(this, src.name); this._children.set(src.path, s); const ss = session.getSource(src); s.setSource(session, ss); } } } } createIfNeeded<T extends BaseTreeItem>(key: string, factory: (parent: BaseTreeItem, label: string) => T): T { let child = <T>this._children.get(key); if (!child) { child = factory(this, key); this._children.set(key, child); } return child; } getChild(key: string): BaseTreeItem | undefined { return this._children.get(key); } remove(key: string): void { this._children.delete(key); } removeFromParent(): void { if (this._parent) { this._parent.remove(this._label); if (this._parent._children.size === 0) { this._parent.removeFromParent(); } } } getTemplateId(): string { return 'id'; } // a dynamic ID based on the parent chain; required for reparenting (see #55448) getId(): string { const parent = this.getParent(); return parent ? `${parent.getId()}/${this.getInternalId()}` : this.getInternalId(); } getInternalId(): string { return this._label; } // skips intermediate single-child nodes getParent(): BaseTreeItem | undefined { if (this._parent) { if (this._parent.isSkipped()) { return this._parent.getParent(); } return this._parent; } return undefined; } isSkipped(): boolean { if (this._parent) { if (this._parent.oneChild()) { return true; // skipped if I'm the only child of my parents } return false; } return true; // roots are never skipped } // skips intermediate single-child nodes hasChildren(): boolean { const child = this.oneChild(); if (child) { return child.hasChildren(); } return this._children.size > 0; } // skips intermediate single-child nodes getChildren(): BaseTreeItem[] { const child = this.oneChild(); if (child) { return child.getChildren(); } const array: BaseTreeItem[] = []; for (const child of this._children.values()) { array.push(child); } return array.sort((a, b) => this.compare(a, b)); } // skips intermediate single-child nodes getLabel(separateRootFolder = true): string { const child = this.oneChild(); if (child) { const sep = (this instanceof RootFolderTreeItem && separateRootFolder) ? ' • ' : posix.sep; return `${this._label}${sep}${child.getLabel()}`; } return this._label; } // skips intermediate single-child nodes getHoverLabel(): string | undefined { if (this._source && this._parent && this._parent._source) { return this._source.raw.path || this._source.raw.name; } const label = this.getLabel(false); const parent = this.getParent(); if (parent) { const hover = parent.getHoverLabel(); if (hover) { return `${hover}/${label}`; } } return label; } // skips intermediate single-child nodes getSource(): Source | undefined { const child = this.oneChild(); if (child) { return child.getSource(); } return this._source; } protected compare(a: BaseTreeItem, b: BaseTreeItem): number { if (a._label && b._label) { return a._label.localeCompare(b._label); } return 0; } private oneChild(): BaseTreeItem | undefined { if (!this._source && !this._showedMoreThanOne && this.skipOneChild()) { if (this._children.size === 1) { return this._children.values().next().value; } // if a node had more than one child once, it will never be skipped again if (this._children.size > 1) { this._showedMoreThanOne = true; } } return undefined; } private skipOneChild(): boolean { if (NEW_STYLE_COMPRESS) { // if the root node has only one Session, don't show the session return this instanceof RootTreeItem; } else { return !(this instanceof RootFolderTreeItem) && !(this instanceof SessionTreeItem); } } } class RootFolderTreeItem extends BaseTreeItem { constructor(parent: BaseTreeItem, public folder: IWorkspaceFolder) { super(parent, folder.name, true); } } class RootTreeItem extends BaseTreeItem { constructor(private _pathService: IPathService, private _contextService: IWorkspaceContextService, private _labelService: ILabelService) { super(undefined, 'Root'); } add(session: IDebugSession): SessionTreeItem { return this.createIfNeeded(session.getId(), () => new SessionTreeItem(this._labelService, this, session, this._pathService, this._contextService)); } find(session: IDebugSession): SessionTreeItem { return <SessionTreeItem>this.getChild(session.getId()); } } class SessionTreeItem extends BaseTreeItem { private static readonly URL_REGEXP = /^(https?:\/\/[^/]+)(\/.*)$/; private _session: IDebugSession; private _map = new Map<string, BaseTreeItem>(); private _labelService: ILabelService; constructor(labelService: ILabelService, parent: BaseTreeItem, session: IDebugSession, private _pathService: IPathService, private rootProvider: IWorkspaceContextService) { super(parent, session.getLabel(), true); this._labelService = labelService; this._session = session; } override getInternalId(): string { return this._session.getId(); } override getSession(): IDebugSession { return this._session; } override getHoverLabel(): string | undefined { return undefined; } override hasChildren(): boolean { return true; } protected override compare(a: BaseTreeItem, b: BaseTreeItem): number { const acat = this.category(a); const bcat = this.category(b); if (acat !== bcat) { return acat - bcat; } return super.compare(a, b); } private category(item: BaseTreeItem): number { // workspace scripts come at the beginning in "folder" order if (item instanceof RootFolderTreeItem) { return item.folder.index; } // <...> come at the very end const l = item.getLabel(); if (l && /^<.+>$/.test(l)) { return 1000; } // everything else in between return 999; } async addPath(source: Source): Promise<void> { let folder: IWorkspaceFolder | null; let url: string; let path = source.raw.path; if (!path) { return; } if (this._labelService && URI_SCHEMA_PATTERN.test(path)) { path = this._labelService.getUriLabel(URI.parse(path)); } const match = SessionTreeItem.URL_REGEXP.exec(path); if (match && match.length === 3) { url = match[1]; path = decodeURI(match[2]); } else { if (isAbsolute(path)) { const resource = URI.file(path); // return early if we can resolve a relative path label from the root folder folder = this.rootProvider ? this.rootProvider.getWorkspaceFolder(resource) : null; if (folder) { // strip off the root folder path path = normalize(ltrim(resource.path.substring(folder.uri.path.length), posix.sep)); const hasMultipleRoots = this.rootProvider.getWorkspace().folders.length > 1; if (hasMultipleRoots) { path = posix.sep + path; } else { // don't show root folder folder = null; } } else { // on unix try to tildify absolute paths path = normalize(path); if (isWindows) { path = normalizeDriveLetter(path); } else { path = tildify(path, (await this._pathService.userHome()).fsPath); } } } } let leaf: BaseTreeItem = this; path.split(/[\/\\]/).forEach((segment, i) => { if (i === 0 && folder) { const f = folder; leaf = leaf.createIfNeeded(folder.name, parent => new RootFolderTreeItem(parent, f)); } else if (i === 0 && url) { leaf = leaf.createIfNeeded(url, parent => new BaseTreeItem(parent, url)); } else { leaf = leaf.createIfNeeded(segment, parent => new BaseTreeItem(parent, segment)); } }); leaf.setSource(this._session, source); if (source.raw.path) { this._map.set(source.raw.path, leaf); } } removePath(source: Source): boolean { if (source.raw.path) { const leaf = this._map.get(source.raw.path); if (leaf) { leaf.removeFromParent(); return true; } } return false; } } interface IViewState { readonly expanded: Set<string>; } /** * This maps a model item into a view model item. */ function asTreeElement(item: BaseTreeItem, viewState?: IViewState): ITreeElement<LoadedScriptsItem> { const children = item.getChildren(); const collapsed = viewState ? !viewState.expanded.has(item.getId()) : !(item instanceof SessionTreeItem); return { element: item, collapsed, collapsible: item.hasChildren(), children: children.map(i => asTreeElement(i, viewState)) }; } export class LoadedScriptsView extends ViewPane { private treeContainer!: HTMLElement; private loadedScriptsItemType: IContextKey<string>; private tree!: WorkbenchCompressibleObjectTree<LoadedScriptsItem, FuzzyScore>; private treeLabels!: ResourceLabels; private changeScheduler!: RunOnceScheduler; private treeNeedsRefreshOnVisible = false; private filter!: LoadedScriptsFilter; constructor( options: IViewletViewOptions, @IContextMenuService contextMenuService: IContextMenuService, @IKeybindingService keybindingService: IKeybindingService, @IInstantiationService instantiationService: IInstantiationService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IConfigurationService configurationService: IConfigurationService, @IEditorService private readonly editorService: IEditorService, @IContextKeyService contextKeyService: IContextKeyService, @IWorkspaceContextService private readonly contextService: IWorkspaceContextService, @IDebugService private readonly debugService: IDebugService, @ILabelService private readonly labelService: ILabelService, @IPathService private readonly pathService: IPathService, @IOpenerService openerService: IOpenerService, @IThemeService themeService: IThemeService, @ITelemetryService telemetryService: ITelemetryService ) { super(options, keybindingService, contextMenuService, configurationService, contextKeyService, viewDescriptorService, instantiationService, openerService, themeService, telemetryService); this.loadedScriptsItemType = CONTEXT_LOADED_SCRIPTS_ITEM_TYPE.bindTo(contextKeyService); } protected override renderBody(container: HTMLElement): void { super.renderBody(container); this.element.classList.add('debug-pane'); container.classList.add('debug-loaded-scripts'); container.classList.add('show-file-icons'); this.treeContainer = renderViewTree(container); this.filter = new LoadedScriptsFilter(); const root = new RootTreeItem(this.pathService, this.contextService, this.labelService); this.treeLabels = this.instantiationService.createInstance(ResourceLabels, { onDidChangeVisibility: this.onDidChangeBodyVisibility }); this._register(this.treeLabels); this.tree = <WorkbenchCompressibleObjectTree<LoadedScriptsItem, FuzzyScore>>this.instantiationService.createInstance(WorkbenchCompressibleObjectTree, 'LoadedScriptsView', this.treeContainer, new LoadedScriptsDelegate(), [new LoadedScriptsRenderer(this.treeLabels)], { compressionEnabled: NEW_STYLE_COMPRESS, collapseByDefault: true, hideTwistiesOfChildlessElements: true, identityProvider: { getId: (element: LoadedScriptsItem) => element.getId() }, keyboardNavigationLabelProvider: { getKeyboardNavigationLabel: (element: LoadedScriptsItem) => { return element.getLabel(); }, getCompressedNodeKeyboardNavigationLabel: (elements: LoadedScriptsItem[]) => { return elements.map(e => e.getLabel()).join('/'); } }, filter: this.filter, accessibilityProvider: new LoadedSciptsAccessibilityProvider(), overrideStyles: { listBackground: this.getBackgroundColor() } } ); const updateView = (viewState?: IViewState) => this.tree.setChildren(null, asTreeElement(root, viewState).children); updateView(); this.changeScheduler = new RunOnceScheduler(() => { this.treeNeedsRefreshOnVisible = false; if (this.tree) { updateView(); } }, 300); this._register(this.changeScheduler); this._register(this.tree.onDidOpen(e => { if (e.element instanceof BaseTreeItem) { const source = e.element.getSource(); if (source && source.available) { const nullRange = { startLineNumber: 0, startColumn: 0, endLineNumber: 0, endColumn: 0 }; source.openInEditor(this.editorService, nullRange, e.editorOptions.preserveFocus, e.sideBySide, e.editorOptions.pinned); } } })); this._register(this.tree.onDidChangeFocus(() => { const focus = this.tree.getFocus(); if (focus instanceof SessionTreeItem) { this.loadedScriptsItemType.set('session'); } else { this.loadedScriptsItemType.reset(); } })); const scheduleRefreshOnVisible = () => { if (this.isBodyVisible()) { this.changeScheduler.schedule(); } else { this.treeNeedsRefreshOnVisible = true; } }; const addSourcePathsToSession = async (session: IDebugSession) => { if (session.capabilities.supportsLoadedSourcesRequest) { const sessionNode = root.add(session); const paths = await session.getLoadedSources(); for (const path of paths) { await sessionNode.addPath(path); } scheduleRefreshOnVisible(); } }; const registerSessionListeners = (session: IDebugSession) => { this._register(session.onDidChangeName(async () => { const sessionRoot = root.find(session); if (sessionRoot) { sessionRoot.updateLabel(session.getLabel()); scheduleRefreshOnVisible(); } })); this._register(session.onDidLoadedSource(async event => { let sessionRoot: SessionTreeItem; switch (event.reason) { case 'new': case 'changed': sessionRoot = root.add(session); await sessionRoot.addPath(event.source); scheduleRefreshOnVisible(); if (event.reason === 'changed') { DebugContentProvider.refreshDebugContent(event.source.uri); } break; case 'removed': sessionRoot = root.find(session); if (sessionRoot && sessionRoot.removePath(event.source)) { scheduleRefreshOnVisible(); } break; default: this.filter.setFilter(event.source.name); this.tree.refilter(); break; } })); }; this._register(this.debugService.onDidNewSession(registerSessionListeners)); this.debugService.getModel().getSessions().forEach(registerSessionListeners); this._register(this.debugService.onDidEndSession(({ session }) => { root.remove(session.getId()); this.changeScheduler.schedule(); })); this.changeScheduler.schedule(0); this._register(this.onDidChangeBodyVisibility(visible => { if (visible && this.treeNeedsRefreshOnVisible) { this.changeScheduler.schedule(); } })); // feature: expand all nodes when filtering (not when finding) let viewState: IViewState | undefined; this._register(this.tree.onDidChangeFindPattern(pattern => { if (this.tree.findMode === TreeFindMode.Highlight) { return; } if (!viewState && pattern) { const expanded = new Set<string>(); const visit = (node: ITreeNode<BaseTreeItem | null, FuzzyScore>) => { if (node.element && !node.collapsed) { expanded.add(node.element.getId()); } for (const child of node.children) { visit(child); } }; visit(this.tree.getNode()); viewState = { expanded }; this.tree.expandAll(); } else if (!pattern && viewState) { this.tree.setFocus([]); updateView(viewState); viewState = undefined; } })); // populate tree model with source paths from all debug sessions this.debugService.getModel().getSessions().forEach(session => addSourcePathsToSession(session)); } protected override layoutBody(height: number, width: number): void { super.layoutBody(height, width); this.tree.layout(height, width); } override dispose(): void { dispose(this.tree); dispose(this.treeLabels); super.dispose(); } } class LoadedScriptsDelegate implements IListVirtualDelegate<LoadedScriptsItem> { getHeight(element: LoadedScriptsItem): number { return 22; } getTemplateId(element: LoadedScriptsItem): string { return LoadedScriptsRenderer.ID; } } interface ILoadedScriptsItemTemplateData { label: IResourceLabel; } class LoadedScriptsRenderer implements ICompressibleTreeRenderer<BaseTreeItem, FuzzyScore, ILoadedScriptsItemTemplateData> { static readonly ID = 'lsrenderer'; constructor( private labels: ResourceLabels ) { } get templateId(): string { return LoadedScriptsRenderer.ID; } renderTemplate(container: HTMLElement): ILoadedScriptsItemTemplateData { const label = this.labels.create(container, { supportHighlights: true }); return { label }; } renderElement(node: ITreeNode<BaseTreeItem, FuzzyScore>, index: number, data: ILoadedScriptsItemTemplateData): void { const element = node.element; const label = element.getLabel(); this.render(element, label, data, node.filterData); } renderCompressedElements(node: ITreeNode<ICompressedTreeNode<BaseTreeItem>, FuzzyScore>, index: number, data: ILoadedScriptsItemTemplateData, height: number | undefined): void { const element = node.element.elements[node.element.elements.length - 1]; const labels = node.element.elements.map(e => e.getLabel()); this.render(element, labels, data, node.filterData); } private render(element: BaseTreeItem, labels: string | string[], data: ILoadedScriptsItemTemplateData, filterData: FuzzyScore | undefined) { const label: IResourceLabelProps = { name: labels }; const options: IResourceLabelOptions = { title: element.getHoverLabel() }; if (element instanceof RootFolderTreeItem) { options.fileKind = FileKind.ROOT_FOLDER; } else if (element instanceof SessionTreeItem) { options.title = nls.localize('loadedScriptsSession', "Debug Session"); options.hideIcon = true; } else if (element instanceof BaseTreeItem) { const src = element.getSource(); if (src && src.uri) { label.resource = src.uri; options.fileKind = FileKind.FILE; } else { options.fileKind = FileKind.FOLDER; } } options.matches = createMatches(filterData); data.label.setResource(label, options); } disposeTemplate(templateData: ILoadedScriptsItemTemplateData): void { templateData.label.dispose(); } } class LoadedSciptsAccessibilityProvider implements IListAccessibilityProvider<LoadedScriptsItem> { getWidgetAriaLabel(): string { return nls.localize({ comment: ['Debug is a noun in this context, not a verb.'], key: 'loadedScriptsAriaLabel' }, "Debug Loaded Scripts"); } getAriaLabel(element: LoadedScriptsItem): string { if (element instanceof RootFolderTreeItem) { return nls.localize('loadedScriptsRootFolderAriaLabel', "Workspace folder {0}, loaded script, debug", element.getLabel()); } if (element instanceof SessionTreeItem) { return nls.localize('loadedScriptsSessionAriaLabel', "Session {0}, loaded script, debug", element.getLabel()); } if (element.hasChildren()) { return nls.localize('loadedScriptsFolderAriaLabel', "Folder {0}, loaded script, debug", element.getLabel()); } else { return nls.localize('loadedScriptsSourceAriaLabel', "{0}, loaded script, debug", element.getLabel()); } } } class LoadedScriptsFilter implements ITreeFilter<BaseTreeItem, FuzzyScore> { private filterText: string | undefined; setFilter(filterText: string) { this.filterText = filterText; } filter(element: BaseTreeItem, parentVisibility: TreeVisibility): TreeFilterResult<FuzzyScore> { if (!this.filterText) { return TreeVisibility.Visible; } if (element.isLeaf()) { const name = element.getLabel(); if (name.indexOf(this.filterText) >= 0) { return TreeVisibility.Visible; } return TreeVisibility.Hidden; } return TreeVisibility.Recurse; } }
src/vs/workbench/contrib/debug/browser/loadedScriptsView.ts
0
https://github.com/microsoft/vscode/commit/ac6641096645db4a29b2798de3fc8d11cf6ec0e5
[ 0.00034162754309363663, 0.00017334072617813945, 0.00016392828547395766, 0.0001706241600913927, 0.00001979209264391102 ]
{ "id": 3, "code_window": [ "\t\tassert.strictEqual(quickpick.scrollTop, 0);\n", "\t});\n", "\n", "\ttest('keepScrollPosition - works with items', async () => {\n", "\t\tconst quickpick = store.add(controller.createQuickPick());\n", "\n", "\t\tconst items = [];\n", "\t\tfor (let i = 0; i < 1000; i++) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tconst quickpick = store.add(controller.createQuickPick() as QuickPick<IQuickPickItem>);\n" ], "file_path": "src/vs/platform/quickinput/test/browser/quickinput.test.ts", "type": "replace", "edit_start_line_idx": 173 }
{ "original": { "content": "const { selected, all, suggestions, hidden } = notebookKernelService.getMatchingKernel(notebook);\n", "fileName": "./1.tst" }, "modified": { "content": "const scopedContextKeyService = editor.scopedContextKeyService;\nconst matchResult = notebookKernelService.getMatchingKernel(notebook);\nconst { selected, all } = matchResult;\n", "fileName": "./2.tst" }, "diffs": [ { "originalRange": "[1,2)", "modifiedRange": "[1,4)", "innerChanges": [ { "originalRange": "[1,7 -> 1,32]", "modifiedRange": "[1,7 -> 2,2]" }, { "originalRange": "[1,35 -> 1,45]", "modifiedRange": "[2,5 -> 2,18]" }, { "originalRange": "[1,98 -> 1,98 EOL]", "modifiedRange": "[2,71 -> 3,39 EOL]" } ] } ] }
src/vs/editor/test/node/diffing/fixtures/random-match-3/legacy.expected.diff.json
0
https://github.com/microsoft/vscode/commit/ac6641096645db4a29b2798de3fc8d11cf6ec0e5
[ 0.00017521432891953737, 0.00017152258078567684, 0.00016899160982575268, 0.0001709422213025391, 0.00000252013069257373 ]
{ "id": 0, "code_window": [ " // - error TS2531: Object is possibly 'null'.\n", " // - error TS2339: Property 'value' does not exist on type 'EventTarget'.\n", " checkTypeOfDomEvents: false,\n", " checkTypeOfPipes: true,\n", " strictSafeNavigationTypes: true,\n", " };\n", " } else {\n", " typeCheckingConfig = {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " checkTypeOfReferences: true,\n" ], "file_path": "packages/compiler-cli/src/ngtsc/program.ts", "type": "add", "edit_start_line_idx": 437 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {BoundTarget, DirectiveMeta, SchemaMetadata} from '@angular/compiler'; import * as ts from 'typescript'; import {Reference} from '../../imports'; import {TemplateGuardMeta} from '../../metadata'; import {ClassDeclaration} from '../../reflection'; /** * Extension of `DirectiveMeta` that includes additional information required to type-check the * usage of a particular directive. */ export interface TypeCheckableDirectiveMeta extends DirectiveMeta { ref: Reference<ClassDeclaration>; queries: string[]; ngTemplateGuards: TemplateGuardMeta[]; hasNgTemplateContextGuard: boolean; } /** * Metadata required in addition to a component class in order to generate a type check block (TCB) * for that component. */ export interface TypeCheckBlockMetadata { /** * A unique identifier for the class which gave rise to this TCB. * * This can be used to map errors back to the `ts.ClassDeclaration` for the component. */ id: string; /** * Semantic information about the template of the component. */ boundTarget: BoundTarget<TypeCheckableDirectiveMeta>; /* * Pipes used in the template of the component. */ pipes: Map<string, Reference<ClassDeclaration<ts.ClassDeclaration>>>; /** * Schemas that apply to this template. */ schemas: SchemaMetadata[]; } export interface TypeCtorMetadata { /** * The name of the requested type constructor function. */ fnName: string; /** * Whether to generate a body for the function or not. */ body: boolean; /** * Input, output, and query field names in the type which should be included as constructor input. */ fields: {inputs: string[]; outputs: string[]; queries: string[];}; } export interface TypeCheckingConfig { /** * Whether to check the left-hand side type of binding operations. * * For example, if this is `false` then the expression `[input]="expr"` will have `expr` type- * checked, but not the assignment of the resulting type to the `input` property of whichever * directive or component is receiving the binding. If set to `true`, both sides of the assignment * are checked. * * This flag only affects bindings to components/directives. Bindings to the DOM are checked if * `checkTypeOfDomBindings` is set. */ checkTypeOfInputBindings: boolean; /** * Whether to use strict null types for input bindings for directives. * * If this is `true`, applications that are compiled with TypeScript's `strictNullChecks` enabled * will produce type errors for bindings which can evaluate to `undefined` or `null` where the * inputs's type does not include `undefined` or `null` in its type. If set to `false`, all * binding expressions are wrapped in a non-null assertion operator to effectively disable strict * null checks. This may be particularly useful when the directive is from a library that is not * compiled with `strictNullChecks` enabled. */ strictNullInputBindings: boolean; /** * Whether to check the left-hand side type of binding operations to DOM properties. * * As `checkTypeOfBindings`, but only applies to bindings to DOM properties. * * This does not affect the use of the `DomSchemaChecker` to validate the template against the DOM * schema. Rather, this flag is an experimental, not yet complete feature which uses the * lib.dom.d.ts DOM typings in TypeScript to validate that DOM bindings are of the correct type * for assignability to the underlying DOM element properties. */ checkTypeOfDomBindings: boolean; /** * Whether to infer the type of the `$event` variable in event bindings for directive outputs. * * If this is `true`, the type of `$event` will be inferred based on the generic type of * `EventEmitter`/`Subject` of the output. If set to `false`, the `$event` variable will be of * type `any`. */ checkTypeOfOutputEvents: boolean; /** * Whether to infer the type of the `$event` variable in event bindings for animations. * * If this is `true`, the type of `$event` will be `AnimationEvent` from `@angular/animations`. * If set to `false`, the `$event` variable will be of type `any`. */ checkTypeOfAnimationEvents: boolean; /** * Whether to infer the type of the `$event` variable in event bindings to DOM events. * * If this is `true`, the type of `$event` will be inferred based on TypeScript's * `HTMLElementEventMap`, with a fallback to the native `Event` type. If set to `false`, the * `$event` variable will be of type `any`. */ checkTypeOfDomEvents: boolean; /** * Whether to include type information from pipes in the type-checking operation. * * If this is `true`, then the pipe's type signature for `transform()` will be used to check the * usage of the pipe. If this is `false`, then the result of applying a pipe will be `any`, and * the types of the pipe's value and arguments will not be matched against the `transform()` * method. */ checkTypeOfPipes: boolean; /** * Whether to narrow the types of template contexts. */ applyTemplateContextGuards: boolean; /** * Whether to use a strict type for null-safe navigation operations. * * If this is `false`, then the return type of `a?.b` or `a?()` will be `any`. If set to `true`, * then the return type of `a?.b` for example will be the same as the type of the ternary * expression `a != null ? a.b : a`. */ strictSafeNavigationTypes: boolean; /** * Whether to descend into template bodies and check any bindings there. */ checkTemplateBodies: boolean; /** * Whether to check resolvable queries. * * This is currently an unsupported feature. */ checkQueries: false; } export type TemplateSourceMapping = DirectTemplateSourceMapping | IndirectTemplateSourceMapping | ExternalTemplateSourceMapping; /** * A mapping to an inline template in a TS file. * * `ParseSourceSpan`s for this template should be accurate for direct reporting in a TS error * message. */ export interface DirectTemplateSourceMapping { type: 'direct'; node: ts.StringLiteral|ts.NoSubstitutionTemplateLiteral; } /** * A mapping to a template which is still in a TS file, but where the node positions in any * `ParseSourceSpan`s are not accurate for one reason or another. * * This can occur if the template expression was interpolated in a way where the compiler could not * construct a contiguous mapping for the template string. The `node` refers to the `template` * expression. */ export interface IndirectTemplateSourceMapping { type: 'indirect'; componentClass: ClassDeclaration; node: ts.Expression; template: string; } /** * A mapping to a template declared in an external HTML file, where node positions in * `ParseSourceSpan`s represent accurate offsets into the external file. * * In this case, the given `node` refers to the `templateUrl` expression. */ export interface ExternalTemplateSourceMapping { type: 'external'; componentClass: ClassDeclaration; node: ts.Expression; template: string; templateUrl: string; }
packages/compiler-cli/src/ngtsc/typecheck/src/api.ts
1
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.006870772689580917, 0.0017422701930627227, 0.00016436231089755893, 0.00019032236014027148, 0.002200064016506076 ]
{ "id": 0, "code_window": [ " // - error TS2531: Object is possibly 'null'.\n", " // - error TS2339: Property 'value' does not exist on type 'EventTarget'.\n", " checkTypeOfDomEvents: false,\n", " checkTypeOfPipes: true,\n", " strictSafeNavigationTypes: true,\n", " };\n", " } else {\n", " typeCheckingConfig = {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " checkTypeOfReferences: true,\n" ], "file_path": "packages/compiler-cli/src/ngtsc/program.ts", "type": "add", "edit_start_line_idx": 437 }
import { browser, element, by } from 'protractor'; import { logging } from 'selenium-webdriver'; describe('Template Expression Operators', function () { beforeAll(function () { browser.get(''); }); it('should have title Inputs and Outputs', function () { let title = element.all(by.css('h1')).get(0); expect(title.getText()).toEqual('Template Expression Operators'); }); it('should display json data', function () { let jsonDate = element.all(by.css('p')).get(4); expect(jsonDate.getText()).toContain('1980'); }); it('should display $98', function () { let jsonDate = element.all(by.css('p')).get(5); expect(jsonDate.getText()).toContain('$98.00'); }); it('should display Telephone', function () { let jsonDate = element.all(by.css('p')).get(6); expect(jsonDate.getText()).toContain('Telephone'); }); });
aio/content/examples/template-expression-operators/e2e/src/app.e2e-spec.ts
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.00017753442807588726, 0.00017523652059026062, 0.00017274805577471852, 0.00017533177742734551, 0.0000020567017600114923 ]
{ "id": 0, "code_window": [ " // - error TS2531: Object is possibly 'null'.\n", " // - error TS2339: Property 'value' does not exist on type 'EventTarget'.\n", " checkTypeOfDomEvents: false,\n", " checkTypeOfPipes: true,\n", " strictSafeNavigationTypes: true,\n", " };\n", " } else {\n", " typeCheckingConfig = {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " checkTypeOfReferences: true,\n" ], "file_path": "packages/compiler-cli/src/ngtsc/program.ts", "type": "add", "edit_start_line_idx": 437 }
load("//tools:defaults.bzl", "ng_module") load("@npm_bazel_typescript//:index.bzl", "ts_devserver") package(default_visibility = ["//modules/playground:__subpackages__"]) ng_module( name = "todo", srcs = glob(["**/*.ts"]), assets = ["todo.html"], tsconfig = "//modules/playground:tsconfig-build.json", # TODO: FW-1004 Type checking is currently not complete. type_check = False, deps = [ "//packages/core", "//packages/forms", "//packages/platform-webworker", "//packages/platform-webworker-dynamic", ], ) ts_devserver( name = "devserver", data = [ "css/main.css", "loader.js", "//modules/playground/src/web_workers:worker-config", "@npm//:node_modules/rxjs/bundles/rxjs.umd.js", "@npm//:node_modules/tslib/tslib.js", ], entry_module = "angular/modules/playground/src/web_workers/todo/index", index_html = "index.html", port = 4200, scripts = [ "@npm//:node_modules/tslib/tslib.js", "//tools/rxjs:rxjs_umd_modules", ], static_files = [ "@npm//:node_modules/systemjs/dist/system.js", "@npm//:node_modules/zone.js/dist/zone.js", "@npm//:node_modules/zone.js/dist/long-stack-trace-zone.js", "@npm//:node_modules/reflect-metadata/Reflect.js", ], deps = [":todo"], )
modules/playground/src/web_workers/todo/BUILD.bazel
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.00017611360817681998, 0.00017121637938544154, 0.000164457451319322, 0.00017402402590960264, 0.00000463616879642359 ]
{ "id": 0, "code_window": [ " // - error TS2531: Object is possibly 'null'.\n", " // - error TS2339: Property 'value' does not exist on type 'EventTarget'.\n", " checkTypeOfDomEvents: false,\n", " checkTypeOfPipes: true,\n", " strictSafeNavigationTypes: true,\n", " };\n", " } else {\n", " typeCheckingConfig = {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " checkTypeOfReferences: true,\n" ], "file_path": "packages/compiler-cli/src/ngtsc/program.ts", "type": "add", "edit_start_line_idx": 437 }
import {platformBrowser} from '@angular/platform-browser'; import {AppModuleNgFactory} from './app.module.ngfactory'; platformBrowser().bootstrapModuleFactory(AppModuleNgFactory);
integration/bazel/src/main.ts
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.00017580122221261263, 0.00017580122221261263, 0.00017580122221261263, 0.00017580122221261263, 0 ]
{ "id": 1, "code_window": [ " checkTypeOfOutputEvents: false,\n", " checkTypeOfAnimationEvents: false,\n", " checkTypeOfDomEvents: false,\n", " checkTypeOfPipes: false,\n", " strictSafeNavigationTypes: false,\n", " };\n", " }\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " checkTypeOfReferences: false,\n" ], "file_path": "packages/compiler-cli/src/ngtsc/program.ts", "type": "add", "edit_start_line_idx": 451 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {GeneratedFile} from '@angular/compiler'; import * as ts from 'typescript'; import * as api from '../transformers/api'; import {nocollapseHack} from '../transformers/nocollapse_hack'; import {ComponentDecoratorHandler, DirectiveDecoratorHandler, InjectableDecoratorHandler, NgModuleDecoratorHandler, NoopReferencesRegistry, PipeDecoratorHandler, ReferencesRegistry} from './annotations'; import {BaseDefDecoratorHandler} from './annotations/src/base_def'; import {CycleAnalyzer, ImportGraph} from './cycles'; import {ErrorCode, ngErrorCode} from './diagnostics'; import {FlatIndexGenerator, ReferenceGraph, checkForPrivateExports, findFlatIndexEntryPoint} from './entry_point'; import {AbsoluteFsPath, LogicalFileSystem, absoluteFrom} from './file_system'; import {AbsoluteModuleStrategy, AliasStrategy, AliasingHost, DefaultImportTracker, FileToModuleAliasingHost, FileToModuleHost, FileToModuleStrategy, ImportRewriter, LocalIdentifierStrategy, LogicalProjectStrategy, ModuleResolver, NoopImportRewriter, PrivateExportAliasingHost, R3SymbolsImportRewriter, Reference, ReferenceEmitter} from './imports'; import {IncrementalState} from './incremental'; import {IndexedComponent, IndexingContext} from './indexer'; import {generateAnalysis} from './indexer/src/transform'; import {CompoundMetadataReader, CompoundMetadataRegistry, DtsMetadataReader, LocalMetadataRegistry, MetadataReader} from './metadata'; import {PartialEvaluator} from './partial_evaluator'; import {NOOP_PERF_RECORDER, PerfRecorder, PerfTracker} from './perf'; import {TypeScriptReflectionHost} from './reflection'; import {HostResourceLoader} from './resource_loader'; import {NgModuleRouteAnalyzer, entryPointKeyFor} from './routing'; import {CompoundComponentScopeReader, LocalModuleScopeRegistry, MetadataDtsModuleScopeResolver} from './scope'; import {FactoryGenerator, FactoryInfo, GeneratedShimsHostWrapper, ShimGenerator, SummaryGenerator, TypeCheckShimGenerator, generatedFactoryTransform} from './shims'; import {ivySwitchTransform} from './switch'; import {IvyCompilation, declarationTransformFactory, ivyTransformFactory} from './transform'; import {aliasTransformFactory} from './transform/src/alias'; import {TypeCheckContext, TypeCheckingConfig, typeCheckFilePath} from './typecheck'; import {normalizeSeparators} from './util/src/path'; import {getRootDirs, getSourceFileOrNull, isDtsPath, resolveModuleName} from './util/src/typescript'; export class NgtscProgram implements api.Program { private tsProgram: ts.Program; private reuseTsProgram: ts.Program; private resourceManager: HostResourceLoader; private compilation: IvyCompilation|undefined = undefined; private factoryToSourceInfo: Map<string, FactoryInfo>|null = null; private sourceToFactorySymbols: Map<string, Set<string>>|null = null; private _coreImportsFrom: ts.SourceFile|null|undefined = undefined; private _importRewriter: ImportRewriter|undefined = undefined; private _reflector: TypeScriptReflectionHost|undefined = undefined; private _isCore: boolean|undefined = undefined; private rootDirs: AbsoluteFsPath[]; private closureCompilerEnabled: boolean; private entryPoint: ts.SourceFile|null; private exportReferenceGraph: ReferenceGraph|null = null; private flatIndexGenerator: FlatIndexGenerator|null = null; private routeAnalyzer: NgModuleRouteAnalyzer|null = null; private constructionDiagnostics: ts.Diagnostic[] = []; private moduleResolver: ModuleResolver; private cycleAnalyzer: CycleAnalyzer; private metaReader: MetadataReader|null = null; private aliasingHost: AliasingHost|null = null; private refEmitter: ReferenceEmitter|null = null; private fileToModuleHost: FileToModuleHost|null = null; private defaultImportTracker: DefaultImportTracker; private perfRecorder: PerfRecorder = NOOP_PERF_RECORDER; private perfTracker: PerfTracker|null = null; private incrementalState: IncrementalState; private typeCheckFilePath: AbsoluteFsPath; private modifiedResourceFiles: Set<string>|null; constructor( rootNames: ReadonlyArray<string>, private options: api.CompilerOptions, private host: api.CompilerHost, oldProgram?: NgtscProgram) { if (shouldEnablePerfTracing(options)) { this.perfTracker = PerfTracker.zeroedToNow(); this.perfRecorder = this.perfTracker; } this.modifiedResourceFiles = this.host.getModifiedResourceFiles && this.host.getModifiedResourceFiles() || null; this.rootDirs = getRootDirs(host, options); this.closureCompilerEnabled = !!options.annotateForClosureCompiler; this.resourceManager = new HostResourceLoader(host, options); // TODO(alxhub): remove the fallback to allowEmptyCodegenFiles after verifying that the rest of // our build tooling is no longer relying on it. const allowEmptyCodegenFiles = options.allowEmptyCodegenFiles || false; const shouldGenerateFactoryShims = options.generateNgFactoryShims !== undefined ? options.generateNgFactoryShims : allowEmptyCodegenFiles; const shouldGenerateSummaryShims = options.generateNgSummaryShims !== undefined ? options.generateNgSummaryShims : allowEmptyCodegenFiles; const normalizedRootNames = rootNames.map(n => absoluteFrom(n)); if (host.fileNameToModuleName !== undefined) { this.fileToModuleHost = host as FileToModuleHost; } let rootFiles = [...rootNames]; const generators: ShimGenerator[] = []; let summaryGenerator: SummaryGenerator|null = null; if (shouldGenerateSummaryShims) { // Summary generation. summaryGenerator = SummaryGenerator.forRootFiles(normalizedRootNames); generators.push(summaryGenerator); } if (shouldGenerateFactoryShims) { // Factory generation. const factoryGenerator = FactoryGenerator.forRootFiles(normalizedRootNames); const factoryFileMap = factoryGenerator.factoryFileMap; this.factoryToSourceInfo = new Map<string, FactoryInfo>(); this.sourceToFactorySymbols = new Map<string, Set<string>>(); factoryFileMap.forEach((sourceFilePath, factoryPath) => { const moduleSymbolNames = new Set<string>(); this.sourceToFactorySymbols !.set(sourceFilePath, moduleSymbolNames); this.factoryToSourceInfo !.set(factoryPath, {sourceFilePath, moduleSymbolNames}); }); const factoryFileNames = Array.from(factoryFileMap.keys()); rootFiles.push(...factoryFileNames); generators.push(factoryGenerator); } // Done separately to preserve the order of factory files before summary files in rootFiles. // TODO(alxhub): validate that this is necessary. if (shouldGenerateSummaryShims) { rootFiles.push(...summaryGenerator !.getSummaryFileNames()); } this.typeCheckFilePath = typeCheckFilePath(this.rootDirs); generators.push(new TypeCheckShimGenerator(this.typeCheckFilePath)); rootFiles.push(this.typeCheckFilePath); let entryPoint: AbsoluteFsPath|null = null; if (options.flatModuleOutFile != null && options.flatModuleOutFile !== '') { entryPoint = findFlatIndexEntryPoint(normalizedRootNames); if (entryPoint === null) { // This error message talks specifically about having a single .ts file in "files". However // the actual logic is a bit more permissive. If a single file exists, that will be taken, // otherwise the highest level (shortest path) "index.ts" file will be used as the flat // module entry point instead. If neither of these conditions apply, the error below is // given. // // The user is not informed about the "index.ts" option as this behavior is deprecated - // an explicit entrypoint should always be specified. this.constructionDiagnostics.push({ category: ts.DiagnosticCategory.Error, code: ngErrorCode(ErrorCode.CONFIG_FLAT_MODULE_NO_INDEX), file: undefined, start: undefined, length: undefined, messageText: 'Angular compiler option "flatModuleOutFile" requires one and only one .ts file in the "files" field.', }); } else { const flatModuleId = options.flatModuleId || null; const flatModuleOutFile = normalizeSeparators(options.flatModuleOutFile); this.flatIndexGenerator = new FlatIndexGenerator(entryPoint, flatModuleOutFile, flatModuleId); generators.push(this.flatIndexGenerator); rootFiles.push(this.flatIndexGenerator.flatIndexPath); } } if (generators.length > 0) { // FIXME: Remove the any cast once google3 is fully on TS3.6. this.host = (new GeneratedShimsHostWrapper(host, generators) as any); } this.tsProgram = ts.createProgram(rootFiles, options, this.host, oldProgram && oldProgram.reuseTsProgram); this.reuseTsProgram = this.tsProgram; this.entryPoint = entryPoint !== null ? getSourceFileOrNull(this.tsProgram, entryPoint) : null; this.moduleResolver = new ModuleResolver(this.tsProgram, options, this.host); this.cycleAnalyzer = new CycleAnalyzer(new ImportGraph(this.moduleResolver)); this.defaultImportTracker = new DefaultImportTracker(); if (oldProgram === undefined) { this.incrementalState = IncrementalState.fresh(); } else { this.incrementalState = IncrementalState.reconcile( oldProgram.incrementalState, oldProgram.reuseTsProgram, this.tsProgram, this.modifiedResourceFiles); } } getTsProgram(): ts.Program { return this.tsProgram; } getTsOptionDiagnostics(cancellationToken?: ts.CancellationToken| undefined): ReadonlyArray<ts.Diagnostic> { return this.tsProgram.getOptionsDiagnostics(cancellationToken); } getNgOptionDiagnostics(cancellationToken?: ts.CancellationToken| undefined): ReadonlyArray<ts.Diagnostic> { return this.constructionDiagnostics; } getTsSyntacticDiagnostics( sourceFile?: ts.SourceFile|undefined, cancellationToken?: ts.CancellationToken|undefined): ReadonlyArray<ts.Diagnostic> { return this.tsProgram.getSyntacticDiagnostics(sourceFile, cancellationToken); } getNgStructuralDiagnostics(cancellationToken?: ts.CancellationToken| undefined): ReadonlyArray<api.Diagnostic> { return []; } getTsSemanticDiagnostics( sourceFile?: ts.SourceFile|undefined, cancellationToken?: ts.CancellationToken|undefined): ReadonlyArray<ts.Diagnostic> { return this.tsProgram.getSemanticDiagnostics(sourceFile, cancellationToken); } getNgSemanticDiagnostics( fileName?: string|undefined, cancellationToken?: ts.CancellationToken|undefined): ReadonlyArray<ts.Diagnostic> { const compilation = this.ensureAnalyzed(); const diagnostics = [...compilation.diagnostics, ...this.getTemplateDiagnostics()]; if (this.entryPoint !== null && this.exportReferenceGraph !== null) { diagnostics.push(...checkForPrivateExports( this.entryPoint, this.tsProgram.getTypeChecker(), this.exportReferenceGraph)); } return diagnostics; } async loadNgStructureAsync(): Promise<void> { if (this.compilation === undefined) { this.compilation = this.makeCompilation(); } const analyzeSpan = this.perfRecorder.start('analyze'); await Promise.all(this.tsProgram.getSourceFiles() .filter(file => !file.fileName.endsWith('.d.ts')) .map(file => { const analyzeFileSpan = this.perfRecorder.start('analyzeFile', file); let analysisPromise = this.compilation !.analyzeAsync(file); if (analysisPromise === undefined) { this.perfRecorder.stop(analyzeFileSpan); } else if (this.perfRecorder.enabled) { analysisPromise = analysisPromise.then( () => this.perfRecorder.stop(analyzeFileSpan)); } return analysisPromise; }) .filter((result): result is Promise<void> => result !== undefined)); this.perfRecorder.stop(analyzeSpan); this.compilation.resolve(); } listLazyRoutes(entryRoute?: string|undefined): api.LazyRoute[] { if (entryRoute) { // Note: // This resolution step is here to match the implementation of the old `AotCompilerHost` (see // https://github.com/angular/angular/blob/50732e156/packages/compiler-cli/src/transformers/compiler_host.ts#L175-L188). // // `@angular/cli` will always call this API with an absolute path, so the resolution step is // not necessary, but keeping it backwards compatible in case someone else is using the API. // Relative entry paths are disallowed. if (entryRoute.startsWith('.')) { throw new Error( `Failed to list lazy routes: Resolution of relative paths (${entryRoute}) is not supported.`); } // Non-relative entry paths fall into one of the following categories: // - Absolute system paths (e.g. `/foo/bar/my-project/my-module`), which are unaffected by the // logic below. // - Paths to enternal modules (e.g. `some-lib`). // - Paths mapped to directories in `tsconfig.json` (e.g. `shared/my-module`). // (See https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping.) // // In all cases above, the `containingFile` argument is ignored, so we can just take the first // of the root files. const containingFile = this.tsProgram.getRootFileNames()[0]; const [entryPath, moduleName] = entryRoute.split('#'); const resolvedModule = resolveModuleName(entryPath, containingFile, this.options, this.host); if (resolvedModule) { entryRoute = entryPointKeyFor(resolvedModule.resolvedFileName, moduleName); } } this.ensureAnalyzed(); return this.routeAnalyzer !.listLazyRoutes(entryRoute); } getLibrarySummaries(): Map<string, api.LibrarySummary> { throw new Error('Method not implemented.'); } getEmittedGeneratedFiles(): Map<string, GeneratedFile> { throw new Error('Method not implemented.'); } getEmittedSourceFiles(): Map<string, ts.SourceFile> { throw new Error('Method not implemented.'); } private ensureAnalyzed(): IvyCompilation { if (this.compilation === undefined) { const analyzeSpan = this.perfRecorder.start('analyze'); this.compilation = this.makeCompilation(); this.tsProgram.getSourceFiles() .filter(file => !file.fileName.endsWith('.d.ts')) .forEach(file => { const analyzeFileSpan = this.perfRecorder.start('analyzeFile', file); this.compilation !.analyzeSync(file); this.perfRecorder.stop(analyzeFileSpan); }); this.perfRecorder.stop(analyzeSpan); this.compilation.resolve(); } return this.compilation; } emit(opts?: { emitFlags?: api.EmitFlags, cancellationToken?: ts.CancellationToken, customTransformers?: api.CustomTransformers, emitCallback?: api.TsEmitCallback, mergeEmitResultsCallback?: api.TsMergeEmitResultsCallback }): ts.EmitResult { const emitCallback = opts && opts.emitCallback || defaultEmitCallback; const compilation = this.ensureAnalyzed(); const writeFile: ts.WriteFileCallback = (fileName: string, data: string, writeByteOrderMark: boolean, onError: ((message: string) => void) | undefined, sourceFiles: ReadonlyArray<ts.SourceFile>| undefined) => { if (this.closureCompilerEnabled && fileName.endsWith('.js')) { data = nocollapseHack(data); } this.host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }; const customTransforms = opts && opts.customTransformers; const beforeTransforms = [ ivyTransformFactory( compilation, this.reflector, this.importRewriter, this.defaultImportTracker, this.isCore, this.closureCompilerEnabled), aliasTransformFactory(compilation.exportStatements) as ts.TransformerFactory<ts.SourceFile>, this.defaultImportTracker.importPreservingTransformer(), ]; const afterDeclarationsTransforms = [ declarationTransformFactory(compilation), ]; // Only add aliasing re-exports to the .d.ts output if the `AliasingHost` requests it. if (this.aliasingHost !== null && this.aliasingHost.aliasExportsInDts) { afterDeclarationsTransforms.push(aliasTransformFactory(compilation.exportStatements)); } if (this.factoryToSourceInfo !== null) { beforeTransforms.push( generatedFactoryTransform(this.factoryToSourceInfo, this.importRewriter)); } beforeTransforms.push(ivySwitchTransform); if (customTransforms && customTransforms.beforeTs) { beforeTransforms.push(...customTransforms.beforeTs); } const emitSpan = this.perfRecorder.start('emit'); const emitResults: ts.EmitResult[] = []; const typeCheckFile = getSourceFileOrNull(this.tsProgram, this.typeCheckFilePath); for (const targetSourceFile of this.tsProgram.getSourceFiles()) { if (targetSourceFile.isDeclarationFile || targetSourceFile === typeCheckFile) { continue; } if (this.incrementalState.safeToSkip(targetSourceFile)) { continue; } const fileEmitSpan = this.perfRecorder.start('emitFile', targetSourceFile); emitResults.push(emitCallback({ targetSourceFile, program: this.tsProgram, host: this.host, options: this.options, emitOnlyDtsFiles: false, writeFile, customTransformers: { before: beforeTransforms, after: customTransforms && customTransforms.afterTs, afterDeclarations: afterDeclarationsTransforms, }, })); this.perfRecorder.stop(fileEmitSpan); } this.perfRecorder.stop(emitSpan); if (this.perfTracker !== null && this.options.tracePerformance !== undefined) { this.perfTracker.serializeToFile(this.options.tracePerformance, this.host); } // Run the emit, including a custom transformer that will downlevel the Ivy decorators in code. return ((opts && opts.mergeEmitResultsCallback) || mergeEmitResults)(emitResults); } private getTemplateDiagnostics(): ReadonlyArray<ts.Diagnostic> { // Skip template type-checking if it's disabled. if (this.options.ivyTemplateTypeCheck === false && this.options.fullTemplateTypeCheck !== true) { return []; } const compilation = this.ensureAnalyzed(); // Run template type-checking. // First select a type-checking configuration, based on whether full template type-checking is // requested. let typeCheckingConfig: TypeCheckingConfig; if (this.options.fullTemplateTypeCheck) { typeCheckingConfig = { applyTemplateContextGuards: true, checkQueries: false, checkTemplateBodies: true, checkTypeOfInputBindings: true, strictNullInputBindings: true, // Even in full template type-checking mode, DOM binding checks are not quite ready yet. checkTypeOfDomBindings: false, checkTypeOfOutputEvents: true, checkTypeOfAnimationEvents: true, // Checking of DOM events currently has an adverse effect on developer experience, // e.g. for `<input (blur)="update($event.target.value)">` enabling this check results in: // - error TS2531: Object is possibly 'null'. // - error TS2339: Property 'value' does not exist on type 'EventTarget'. checkTypeOfDomEvents: false, checkTypeOfPipes: true, strictSafeNavigationTypes: true, }; } else { typeCheckingConfig = { applyTemplateContextGuards: false, checkQueries: false, checkTemplateBodies: false, checkTypeOfInputBindings: false, strictNullInputBindings: false, checkTypeOfDomBindings: false, checkTypeOfOutputEvents: false, checkTypeOfAnimationEvents: false, checkTypeOfDomEvents: false, checkTypeOfPipes: false, strictSafeNavigationTypes: false, }; } // Execute the typeCheck phase of each decorator in the program. const prepSpan = this.perfRecorder.start('typeCheckPrep'); const ctx = new TypeCheckContext(typeCheckingConfig, this.refEmitter !, this.typeCheckFilePath); compilation.typeCheck(ctx); this.perfRecorder.stop(prepSpan); // Get the diagnostics. const typeCheckSpan = this.perfRecorder.start('typeCheckDiagnostics'); const {diagnostics, program} = ctx.calculateTemplateDiagnostics(this.tsProgram, this.host, this.options); this.perfRecorder.stop(typeCheckSpan); this.reuseTsProgram = program; return diagnostics; } getIndexedComponents(): Map<ts.Declaration, IndexedComponent> { const compilation = this.ensureAnalyzed(); const context = new IndexingContext(); compilation.index(context); return generateAnalysis(context); } private makeCompilation(): IvyCompilation { const checker = this.tsProgram.getTypeChecker(); // Construct the ReferenceEmitter. if (this.fileToModuleHost === null || !this.options._useHostForImportGeneration) { // The CompilerHost doesn't have fileNameToModuleName, so build an NPM-centric reference // resolution strategy. this.refEmitter = new ReferenceEmitter([ // First, try to use local identifiers if available. new LocalIdentifierStrategy(), // Next, attempt to use an absolute import. new AbsoluteModuleStrategy( this.tsProgram, checker, this.options, this.host, this.reflector), // Finally, check if the reference is being written into a file within the project's logical // file system, and use a relative import if so. If this fails, ReferenceEmitter will throw // an error. new LogicalProjectStrategy(this.reflector, new LogicalFileSystem(this.rootDirs)), ]); // If an entrypoint is present, then all user imports should be directed through the // entrypoint and private exports are not needed. The compiler will validate that all publicly // visible directives/pipes are importable via this entrypoint. if (this.entryPoint === null && this.options.generateDeepReexports === true) { // No entrypoint is present and deep re-exports were requested, so configure the aliasing // system to generate them. this.aliasingHost = new PrivateExportAliasingHost(this.reflector); } } else { // The CompilerHost supports fileNameToModuleName, so use that to emit imports. this.refEmitter = new ReferenceEmitter([ // First, try to use local identifiers if available. new LocalIdentifierStrategy(), // Then use aliased references (this is a workaround to StrictDeps checks). new AliasStrategy(), // Then use fileNameToModuleName to emit imports. new FileToModuleStrategy(this.reflector, this.fileToModuleHost), ]); this.aliasingHost = new FileToModuleAliasingHost(this.fileToModuleHost); } const evaluator = new PartialEvaluator(this.reflector, checker, this.incrementalState); const dtsReader = new DtsMetadataReader(checker, this.reflector); const localMetaRegistry = new LocalMetadataRegistry(); const localMetaReader = new CompoundMetadataReader([localMetaRegistry, this.incrementalState]); const depScopeReader = new MetadataDtsModuleScopeResolver(dtsReader, this.aliasingHost); const scopeRegistry = new LocalModuleScopeRegistry( localMetaReader, depScopeReader, this.refEmitter, this.aliasingHost, this.incrementalState); const scopeReader = new CompoundComponentScopeReader([scopeRegistry, this.incrementalState]); const metaRegistry = new CompoundMetadataRegistry([localMetaRegistry, scopeRegistry, this.incrementalState]); this.metaReader = new CompoundMetadataReader([localMetaReader, dtsReader]); // If a flat module entrypoint was specified, then track references via a `ReferenceGraph` // in // order to produce proper diagnostics for incorrectly exported directives/pipes/etc. If // there // is no flat module entrypoint then don't pay the cost of tracking references. let referencesRegistry: ReferencesRegistry; if (this.entryPoint !== null) { this.exportReferenceGraph = new ReferenceGraph(); referencesRegistry = new ReferenceGraphAdapter(this.exportReferenceGraph); } else { referencesRegistry = new NoopReferencesRegistry(); } this.routeAnalyzer = new NgModuleRouteAnalyzer(this.moduleResolver, evaluator); // Set up the IvyCompilation, which manages state for the Ivy transformer. const handlers = [ new BaseDefDecoratorHandler(this.reflector, evaluator, this.isCore), new ComponentDecoratorHandler( this.reflector, evaluator, metaRegistry, this.metaReader !, scopeReader, scopeRegistry, this.isCore, this.resourceManager, this.rootDirs, this.options.preserveWhitespaces || false, this.options.i18nUseExternalIds !== false, this.getI18nLegacyMessageFormat(), this.moduleResolver, this.cycleAnalyzer, this.refEmitter, this.defaultImportTracker, this.incrementalState), new DirectiveDecoratorHandler( this.reflector, evaluator, metaRegistry, this.defaultImportTracker, this.isCore), new InjectableDecoratorHandler( this.reflector, this.defaultImportTracker, this.isCore, this.options.strictInjectionParameters || false), new NgModuleDecoratorHandler( this.reflector, evaluator, this.metaReader, metaRegistry, scopeRegistry, referencesRegistry, this.isCore, this.routeAnalyzer, this.refEmitter, this.defaultImportTracker, this.options.i18nInLocale), new PipeDecoratorHandler( this.reflector, evaluator, metaRegistry, this.defaultImportTracker, this.isCore), ]; return new IvyCompilation( handlers, this.reflector, this.importRewriter, this.incrementalState, this.perfRecorder, this.sourceToFactorySymbols, scopeRegistry); } private getI18nLegacyMessageFormat(): string { return this.options.enableI18nLegacyMessageIdFormat !== false && this.options.i18nInFormat || ''; } private get reflector(): TypeScriptReflectionHost { if (this._reflector === undefined) { this._reflector = new TypeScriptReflectionHost(this.tsProgram.getTypeChecker()); } return this._reflector; } private get coreImportsFrom(): ts.SourceFile|null { if (this._coreImportsFrom === undefined) { this._coreImportsFrom = this.isCore && getR3SymbolsFile(this.tsProgram) || null; } return this._coreImportsFrom; } private get isCore(): boolean { if (this._isCore === undefined) { this._isCore = isAngularCorePackage(this.tsProgram); } return this._isCore; } private get importRewriter(): ImportRewriter { if (this._importRewriter === undefined) { const coreImportsFrom = this.coreImportsFrom; this._importRewriter = coreImportsFrom !== null ? new R3SymbolsImportRewriter(coreImportsFrom.fileName) : new NoopImportRewriter(); } return this._importRewriter; } } const defaultEmitCallback: api.TsEmitCallback = ({program, targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers}) => program.emit( targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); function mergeEmitResults(emitResults: ts.EmitResult[]): ts.EmitResult { const diagnostics: ts.Diagnostic[] = []; let emitSkipped = false; const emittedFiles: string[] = []; for (const er of emitResults) { diagnostics.push(...er.diagnostics); emitSkipped = emitSkipped || er.emitSkipped; emittedFiles.push(...(er.emittedFiles || [])); } return {diagnostics, emitSkipped, emittedFiles}; } /** * Find the 'r3_symbols.ts' file in the given `Program`, or return `null` if it wasn't there. */ function getR3SymbolsFile(program: ts.Program): ts.SourceFile|null { return program.getSourceFiles().find(file => file.fileName.indexOf('r3_symbols.ts') >= 0) || null; } /** * Determine if the given `Program` is @angular/core. */ function isAngularCorePackage(program: ts.Program): boolean { // Look for its_just_angular.ts somewhere in the program. const r3Symbols = getR3SymbolsFile(program); if (r3Symbols === null) { return false; } // Look for the constant ITS_JUST_ANGULAR in that file. return r3Symbols.statements.some(stmt => { // The statement must be a variable declaration statement. if (!ts.isVariableStatement(stmt)) { return false; } // It must be exported. if (stmt.modifiers === undefined || !stmt.modifiers.some(mod => mod.kind === ts.SyntaxKind.ExportKeyword)) { return false; } // It must declare ITS_JUST_ANGULAR. return stmt.declarationList.declarations.some(decl => { // The declaration must match the name. if (!ts.isIdentifier(decl.name) || decl.name.text !== 'ITS_JUST_ANGULAR') { return false; } // It must initialize the variable to true. if (decl.initializer === undefined || decl.initializer.kind !== ts.SyntaxKind.TrueKeyword) { return false; } // This definition matches. return true; }); }); } export class ReferenceGraphAdapter implements ReferencesRegistry { constructor(private graph: ReferenceGraph) {} add(source: ts.Declaration, ...references: Reference<ts.Declaration>[]): void { for (const {node} of references) { let sourceFile = node.getSourceFile(); if (sourceFile === undefined) { sourceFile = ts.getOriginalNode(node).getSourceFile(); } // Only record local references (not references into .d.ts files). if (sourceFile === undefined || !isDtsPath(sourceFile.fileName)) { this.graph.add(source, node); } } } } function shouldEnablePerfTracing(options: api.CompilerOptions): boolean { return options.tracePerformance !== undefined; }
packages/compiler-cli/src/ngtsc/program.ts
1
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.019437633454799652, 0.0005771881551481783, 0.00016244308790192008, 0.0001729534997139126, 0.002360727870836854 ]
{ "id": 1, "code_window": [ " checkTypeOfOutputEvents: false,\n", " checkTypeOfAnimationEvents: false,\n", " checkTypeOfDomEvents: false,\n", " checkTypeOfPipes: false,\n", " strictSafeNavigationTypes: false,\n", " };\n", " }\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " checkTypeOfReferences: false,\n" ], "file_path": "packages/compiler-cli/src/ngtsc/program.ts", "type": "add", "edit_start_line_idx": 451 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // Needed to run animation tests require('zone.js/dist/zone-node.js'); import '@angular/compiler'; // For JIT mode. Must be in front of any other @angular/* imports. import {DominoAdapter} from '@angular/platform-server/src/domino_adapter'; import {ɵgetDOM as getDOM} from '@angular/common'; if (typeof window == 'undefined') { const domino = require('domino'); DominoAdapter.makeCurrent(); (global as any).document = getDOM().getDefaultDocument(); // Trick to avoid Event patching from // https://github.com/angular/angular/blob/7cf5e95ac9f0f2648beebf0d5bd9056b79946970/packages/platform-browser/src/dom/events/dom_events.ts#L112-L132 // It fails with Domino with TypeError: Cannot assign to read only property // 'stopImmediatePropagation' of object '#<Event>' (global as any).Event = null; // For animation tests, see // https://github.com/angular/angular/blob/master/packages/animations/browser/src/render/shared.ts#L140 (global as any).Element = domino.impl.Element; (global as any).isBrowser = false; (global as any).isNode = true; }
packages/core/test/render3/load_domino.ts
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.00017469852173235267, 0.00017243811453226954, 0.00016706500900909305, 0.0001739944564178586, 0.000003119180064459215 ]
{ "id": 1, "code_window": [ " checkTypeOfOutputEvents: false,\n", " checkTypeOfAnimationEvents: false,\n", " checkTypeOfDomEvents: false,\n", " checkTypeOfPipes: false,\n", " strictSafeNavigationTypes: false,\n", " };\n", " }\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " checkTypeOfReferences: false,\n" ], "file_path": "packages/compiler-cli/src/ngtsc/program.ts", "type": "add", "edit_start_line_idx": 451 }
// #docplaster // #docregion declare var angular: angular.IAngularStatic; import { downgradeComponent } from '@angular/upgrade/static'; // #docregion initialclass import { Component } from '@angular/core'; import { Phone, PhoneData } from '../core/phone/phone.service'; // #enddocregion initialclass import { RouteParams } from '../ajs-upgraded-providers'; // #docregion initialclass @Component({ selector: 'phone-detail', templateUrl: './phone-detail.template.html', // #enddocregion initialclass // #docregion initialclass }) export class PhoneDetailComponent { phone: PhoneData; mainImageUrl: string; constructor(routeParams: RouteParams, phone: Phone) { phone.get(routeParams['phoneId']).subscribe(phone => { this.phone = phone; this.setImage(phone.images[0]); }); } setImage(imageUrl: string) { this.mainImageUrl = imageUrl; } } // #enddocregion initialclass angular.module('phoneDetail') .directive( 'phoneDetail', downgradeComponent({component: PhoneDetailComponent}) as angular.IDirectiveFactory );
aio/content/examples/upgrade-phonecat-2-hybrid/app/phone-detail/phone-detail.component.ts
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.0001740726293064654, 0.0001709979842416942, 0.00016665483417455107, 0.00017148026381619275, 0.000002631370080052875 ]
{ "id": 1, "code_window": [ " checkTypeOfOutputEvents: false,\n", " checkTypeOfAnimationEvents: false,\n", " checkTypeOfDomEvents: false,\n", " checkTypeOfPipes: false,\n", " strictSafeNavigationTypes: false,\n", " };\n", " }\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " checkTypeOfReferences: false,\n" ], "file_path": "packages/compiler-cli/src/ngtsc/program.ts", "type": "add", "edit_start_line_idx": 451 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as ts from 'typescript'; import {METADATA_VERSION, ModuleMetadata} from '../metadata'; import {DTS} from './util'; export interface MetadataReaderHost { getSourceFileMetadata(filePath: string): ModuleMetadata|undefined; cacheMetadata?(fileName: string): boolean; fileExists(filePath: string): boolean; readFile(filePath: string): string; } export interface MetadataReaderCache { /** * @internal */ data: Map<string, ModuleMetadata[]|undefined>; } export function createMetadataReaderCache(): MetadataReaderCache { const data = new Map<string, ModuleMetadata[]|undefined>(); return {data}; } export function readMetadata( filePath: string, host: MetadataReaderHost, cache?: MetadataReaderCache): ModuleMetadata[]| undefined { let metadatas = cache && cache.data.get(filePath); if (metadatas) { return metadatas; } if (host.fileExists(filePath)) { // If the file doesn't exists then we cannot return metadata for the file. // This will occur if the user referenced a declared module for which no file // exists for the module (i.e. jQuery or angularjs). if (DTS.test(filePath)) { metadatas = readMetadataFile(host, filePath); if (!metadatas) { // If there is a .d.ts file but no metadata file we need to produce a // metadata from the .d.ts file as metadata files capture reexports // (starting with v3). metadatas = [upgradeMetadataWithDtsData( host, {'__symbolic': 'module', 'version': 1, 'metadata': {}}, filePath)]; } } else { const metadata = host.getSourceFileMetadata(filePath); metadatas = metadata ? [metadata] : []; } } if (cache && (!host.cacheMetadata || host.cacheMetadata(filePath))) { cache.data.set(filePath, metadatas); } return metadatas; } function readMetadataFile(host: MetadataReaderHost, dtsFilePath: string): ModuleMetadata[]| undefined { const metadataPath = dtsFilePath.replace(DTS, '.metadata.json'); if (!host.fileExists(metadataPath)) { return undefined; } try { const metadataOrMetadatas = JSON.parse(host.readFile(metadataPath)); const metadatas: ModuleMetadata[] = metadataOrMetadatas ? (Array.isArray(metadataOrMetadatas) ? metadataOrMetadatas : [metadataOrMetadatas]) : []; if (metadatas.length) { let maxMetadata = metadatas.reduce((p, c) => p.version > c.version ? p : c); if (maxMetadata.version < METADATA_VERSION) { metadatas.push(upgradeMetadataWithDtsData(host, maxMetadata, dtsFilePath)); } } return metadatas; } catch (e) { console.error(`Failed to read JSON file ${metadataPath}`); throw e; } } function upgradeMetadataWithDtsData( host: MetadataReaderHost, oldMetadata: ModuleMetadata, dtsFilePath: string): ModuleMetadata { // patch v1 to v3 by adding exports and the `extends` clause. // patch v3 to v4 by adding `interface` symbols for TypeAlias let newMetadata: ModuleMetadata = { '__symbolic': 'module', 'version': METADATA_VERSION, 'metadata': {...oldMetadata.metadata}, }; if (oldMetadata.exports) { newMetadata.exports = oldMetadata.exports; } if (oldMetadata.importAs) { newMetadata.importAs = oldMetadata.importAs; } if (oldMetadata.origins) { newMetadata.origins = oldMetadata.origins; } const dtsMetadata = host.getSourceFileMetadata(dtsFilePath); if (dtsMetadata) { for (let prop in dtsMetadata.metadata) { if (!newMetadata.metadata[prop]) { newMetadata.metadata[prop] = dtsMetadata.metadata[prop]; } } if (dtsMetadata['importAs']) newMetadata['importAs'] = dtsMetadata['importAs']; // Only copy exports from exports from metadata prior to version 3. // Starting with version 3 the collector began collecting exports and // this should be redundant. Also, with bundler will rewrite the exports // which will hoist the exports from modules referenced indirectly causing // the imports to be different than the .d.ts files and using the .d.ts file // exports would cause the StaticSymbolResolver to redirect symbols to the // incorrect location. if ((!oldMetadata.version || oldMetadata.version < 3) && dtsMetadata.exports) { newMetadata.exports = dtsMetadata.exports; } } return newMetadata; }
packages/compiler-cli/src/transformers/metadata_reader.ts
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.00017640672740526497, 0.00017227184434887022, 0.00016800624143797904, 0.00017217348795384169, 0.0000024745604605413973 ]
{ "id": 2, "code_window": [ " * `$event` variable will be of type `any`.\n", " */\n", " checkTypeOfDomEvents: boolean;\n", "\n", " /**\n", " * Whether to include type information from pipes in the type-checking operation.\n", " *\n", " * If this is `true`, then the pipe's type signature for `transform()` will be used to check the\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * Whether to infer the type of local references.\n", " *\n", " * If this is `true`, the type of any `#ref` variable in the template will be determined by the\n", " * referenced entity (either a directive or a DOM element). If set to `false`, the type of `ref`\n", " * will be `any`.\n", " */\n", " checkTypeOfReferences: boolean;\n", "\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/src/api.ts", "type": "add", "edit_start_line_idx": 135 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {AST, BindingPipe, BindingType, BoundTarget, DYNAMIC_TYPE, ImplicitReceiver, MethodCall, ParseSourceSpan, ParseSpan, ParsedEventType, PropertyRead, SchemaMetadata, TmplAstBoundAttribute, TmplAstBoundEvent, TmplAstBoundText, TmplAstElement, TmplAstNode, TmplAstReference, TmplAstTemplate, TmplAstTextAttribute, TmplAstVariable} from '@angular/compiler'; import * as ts from 'typescript'; import {Reference} from '../../imports'; import {ClassDeclaration} from '../../reflection'; import {TypeCheckBlockMetadata, TypeCheckableDirectiveMeta} from './api'; import {addParseSpanInfo, addSourceId, toAbsoluteSpan, wrapForDiagnostics} from './diagnostics'; import {DomSchemaChecker} from './dom'; import {Environment} from './environment'; import {NULL_AS_ANY, astToTypescript} from './expression'; import {checkIfClassIsExported, checkIfGenericTypesAreUnbound, tsCallMethod, tsCastToAny, tsCreateElement, tsCreateVariable, tsDeclareVariable} from './ts_util'; /** * Given a `ts.ClassDeclaration` for a component, and metadata regarding that component, compose a * "type check block" function. * * When passed through TypeScript's TypeChecker, type errors that arise within the type check block * function indicate issues in the template itself. * * @param node the TypeScript node for the component class. * @param meta metadata about the component's template and the function being generated. * @param importManager an `ImportManager` for the file into which the TCB will be written. */ export function generateTypeCheckBlock( env: Environment, ref: Reference<ClassDeclaration<ts.ClassDeclaration>>, name: ts.Identifier, meta: TypeCheckBlockMetadata, domSchemaChecker: DomSchemaChecker): ts.FunctionDeclaration { const tcb = new Context(env, domSchemaChecker, meta.id, meta.boundTarget, meta.pipes, meta.schemas); const scope = Scope.forNodes(tcb, null, tcb.boundTarget.target.template !); const ctxRawType = env.referenceType(ref); if (!ts.isTypeReferenceNode(ctxRawType)) { throw new Error( `Expected TypeReferenceNode when referencing the ctx param for ${ref.debugName}`); } const paramList = [tcbCtxParam(ref.node, ctxRawType.typeName)]; const scopeStatements = scope.render(); const innerBody = ts.createBlock([ ...env.getPreludeStatements(), ...scopeStatements, ]); // Wrap the body in an "if (true)" expression. This is unnecessary but has the effect of causing // the `ts.Printer` to format the type-check block nicely. const body = ts.createBlock([ts.createIf(ts.createTrue(), innerBody, undefined)]); const fnDecl = ts.createFunctionDeclaration( /* decorators */ undefined, /* modifiers */ undefined, /* asteriskToken */ undefined, /* name */ name, /* typeParameters */ ref.node.typeParameters, /* parameters */ paramList, /* type */ undefined, /* body */ body); addSourceId(fnDecl, meta.id); return fnDecl; } /** * A code generation operation that's involved in the construction of a Type Check Block. * * The generation of a TCB is non-linear. Bindings within a template may result in the need to * construct certain types earlier than they otherwise would be constructed. That is, if the * generation of a TCB for a template is broken down into specific operations (constructing a * directive, extracting a variable from a let- operation, etc), then it's possible for operations * earlier in the sequence to depend on operations which occur later in the sequence. * * `TcbOp` abstracts the different types of operations which are required to convert a template into * a TCB. This allows for two phases of processing for the template, where 1) a linear sequence of * `TcbOp`s is generated, and then 2) these operations are executed, not necessarily in linear * order. * * Each `TcbOp` may insert statements into the body of the TCB, and also optionally return a * `ts.Expression` which can be used to reference the operation's result. */ abstract class TcbOp { abstract execute(): ts.Expression|null; } /** * A `TcbOp` which creates an expression for a native DOM element (or web component) from a * `TmplAstElement`. * * Executing this operation returns a reference to the element variable. */ class TcbElementOp extends TcbOp { constructor(private tcb: Context, private scope: Scope, private element: TmplAstElement) { super(); } execute(): ts.Identifier { const id = this.tcb.allocateId(); // Add the declaration of the element using document.createElement. const initializer = tsCreateElement(this.element.name); addParseSpanInfo(initializer, this.element.startSourceSpan || this.element.sourceSpan); this.scope.addStatement(tsCreateVariable(id, initializer)); return id; } } /** * A `TcbOp` which creates an expression for particular let- `TmplAstVariable` on a * `TmplAstTemplate`'s context. * * Executing this operation returns a reference to the variable variable (lol). */ class TcbVariableOp extends TcbOp { constructor( private tcb: Context, private scope: Scope, private template: TmplAstTemplate, private variable: TmplAstVariable) { super(); } execute(): ts.Identifier { // Look for a context variable for the template. const ctx = this.scope.resolve(this.template); // Allocate an identifier for the TmplAstVariable, and initialize it to a read of the variable // on the template context. const id = this.tcb.allocateId(); const initializer = ts.createPropertyAccess( /* expression */ ctx, /* name */ this.variable.value || '$implicit'); addParseSpanInfo(initializer, this.variable.sourceSpan); // Declare the variable, and return its identifier. this.scope.addStatement(tsCreateVariable(id, initializer)); return id; } } /** * A `TcbOp` which generates a variable for a `TmplAstTemplate`'s context. * * Executing this operation returns a reference to the template's context variable. */ class TcbTemplateContextOp extends TcbOp { constructor(private tcb: Context, private scope: Scope) { super(); } execute(): ts.Identifier { // Allocate a template ctx variable and declare it with an 'any' type. The type of this variable // may be narrowed as a result of template guard conditions. const ctx = this.tcb.allocateId(); const type = ts.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword); this.scope.addStatement(tsDeclareVariable(ctx, type)); return ctx; } } /** * A `TcbOp` which descends into a `TmplAstTemplate`'s children and generates type-checking code for * them. * * This operation wraps the children's type-checking code in an `if` block, which may include one * or more type guard conditions that narrow types within the template body. */ class TcbTemplateBodyOp extends TcbOp { constructor(private tcb: Context, private scope: Scope, private template: TmplAstTemplate) { super(); } execute(): null { // Create a new Scope for the template. This constructs the list of operations for the template // children, as well as tracks bindings within the template. const tmplScope = Scope.forNodes(this.tcb, this.scope, this.template); // An `if` will be constructed, within which the template's children will be type checked. The // `if` is used for two reasons: it creates a new syntactic scope, isolating variables declared // in the template's TCB from the outer context, and it allows any directives on the templates // to perform type narrowing of either expressions or the template's context. // // The guard is the `if` block's condition. It's usually set to `true` but directives that exist // on the template can trigger extra guard expressions that serve to narrow types within the // `if`. `guard` is calculated by starting with `true` and adding other conditions as needed. // Collect these into `guards` by processing the directives. const directiveGuards: ts.Expression[] = []; const directives = this.tcb.boundTarget.getDirectivesOfNode(this.template); if (directives !== null) { for (const dir of directives) { const dirInstId = this.scope.resolve(this.template, dir); const dirId = this.tcb.env.reference(dir.ref as Reference<ClassDeclaration<ts.ClassDeclaration>>); // There are two kinds of guards. Template guards (ngTemplateGuards) allow type narrowing of // the expression passed to an @Input of the directive. Scan the directive to see if it has // any template guards, and generate them if needed. dir.ngTemplateGuards.forEach(guard => { // For each template guard function on the directive, look for a binding to that input. const boundInput = this.template.inputs.find(i => i.name === guard.inputName) || this.template.templateAttrs.find( (i: TmplAstTextAttribute | TmplAstBoundAttribute): i is TmplAstBoundAttribute => i instanceof TmplAstBoundAttribute && i.name === guard.inputName); if (boundInput !== undefined) { // If there is such a binding, generate an expression for it. const expr = tcbExpression( boundInput.value, this.tcb, this.scope, boundInput.valueSpan || boundInput.sourceSpan); if (guard.type === 'binding') { // Use the binding expression itself as guard. directiveGuards.push(expr); } else { // Call the guard function on the directive with the directive instance and that // expression. const guardInvoke = tsCallMethod(dirId, `ngTemplateGuard_${guard.inputName}`, [ dirInstId, expr, ]); addParseSpanInfo( guardInvoke, toAbsoluteSpan(boundInput.value.span, boundInput.sourceSpan)); directiveGuards.push(guardInvoke); } } }); // The second kind of guard is a template context guard. This guard narrows the template // rendering context variable `ctx`. if (dir.hasNgTemplateContextGuard && this.tcb.env.config.applyTemplateContextGuards) { const ctx = this.scope.resolve(this.template); const guardInvoke = tsCallMethod(dirId, 'ngTemplateContextGuard', [dirInstId, ctx]); addParseSpanInfo(guardInvoke, this.template.sourceSpan); directiveGuards.push(guardInvoke); } } } // By default the guard is simply `true`. let guard: ts.Expression = ts.createTrue(); // If there are any guards from directives, use them instead. if (directiveGuards.length > 0) { // Pop the first value and use it as the initializer to reduce(). This way, a single guard // will be used on its own, but two or more will be combined into binary AND expressions. guard = directiveGuards.reduce( (expr, dirGuard) => ts.createBinary(expr, ts.SyntaxKind.AmpersandAmpersandToken, dirGuard), directiveGuards.pop() !); } // Construct the `if` block for the template with the generated guard expression. The body of // the `if` block is created by rendering the template's `Scope. const tmplIf = ts.createIf( /* expression */ guard, /* thenStatement */ ts.createBlock(tmplScope.render())); this.scope.addStatement(tmplIf); return null; } } /** * A `TcbOp` which renders a text binding (interpolation) into the TCB. * * Executing this operation returns nothing. */ class TcbTextInterpolationOp extends TcbOp { constructor(private tcb: Context, private scope: Scope, private binding: TmplAstBoundText) { super(); } execute(): null { const expr = tcbExpression(this.binding.value, this.tcb, this.scope, this.binding.sourceSpan); this.scope.addStatement(ts.createExpressionStatement(expr)); return null; } } /** * A `TcbOp` which constructs an instance of a directive with types inferred from its inputs, which * also checks the bindings to the directive in the process. * * Executing this operation returns a reference to the directive instance variable with its inferred * type. */ class TcbDirectiveOp extends TcbOp { constructor( private tcb: Context, private scope: Scope, private node: TmplAstTemplate|TmplAstElement, private dir: TypeCheckableDirectiveMeta) { super(); } execute(): ts.Identifier { const id = this.tcb.allocateId(); // Process the directive and construct expressions for each of its bindings. const inputs = tcbGetDirectiveInputs(this.node, this.dir, this.tcb, this.scope); // Call the type constructor of the directive to infer a type, and assign the directive // instance. const typeCtor = tcbCallTypeCtor(this.dir, this.tcb, inputs); addParseSpanInfo(typeCtor, this.node.sourceSpan); this.scope.addStatement(tsCreateVariable(id, typeCtor)); return id; } } /** * A `TcbOp` which feeds elements and unclaimed properties to the `DomSchemaChecker`. * * The DOM schema is not checked via TCB code generation. Instead, the `DomSchemaChecker` ingests * elements and property bindings and accumulates synthetic `ts.Diagnostic`s out-of-band. These are * later merged with the diagnostics generated from the TCB. * * For convenience, the TCB iteration of the template is used to drive the `DomSchemaChecker` via * the `TcbDomSchemaCheckerOp`. */ class TcbDomSchemaCheckerOp extends TcbOp { constructor( private tcb: Context, private element: TmplAstElement, private checkElement: boolean, private claimedInputs: Set<string>) { super(); } execute(): ts.Expression|null { if (this.checkElement) { this.tcb.domSchemaChecker.checkElement(this.tcb.id, this.element, this.tcb.schemas); } // TODO(alxhub): this could be more efficient. for (const binding of this.element.inputs) { if (binding.type === BindingType.Property && this.claimedInputs.has(binding.name)) { // Skip this binding as it was claimed by a directive. continue; } if (binding.type === BindingType.Property) { if (binding.name !== 'style' && binding.name !== 'class') { // A direct binding to a property. const propertyName = ATTR_TO_PROP[binding.name] || binding.name; this.tcb.domSchemaChecker.checkProperty( this.tcb.id, this.element, propertyName, binding.sourceSpan, this.tcb.schemas); } } } return null; } } /** * Mapping between attributes names that don't correspond to their element property names. * Note: this mapping has to be kept in sync with the equally named mapping in the runtime. */ const ATTR_TO_PROP: {[name: string]: string} = { 'class': 'className', 'for': 'htmlFor', 'formaction': 'formAction', 'innerHtml': 'innerHTML', 'readonly': 'readOnly', 'tabindex': 'tabIndex', }; /** * A `TcbOp` which generates code to check "unclaimed inputs" - bindings on an element which were * not attributed to any directive or component, and are instead processed against the HTML element * itself. * * Currently, only the expressions of these bindings are checked. The targets of the bindings are * checked against the DOM schema via a `TcbDomSchemaCheckerOp`. * * Executing this operation returns nothing. */ class TcbUnclaimedInputsOp extends TcbOp { constructor( private tcb: Context, private scope: Scope, private element: TmplAstElement, private claimedInputs: Set<string>) { super(); } execute(): null { // `this.inputs` contains only those bindings not matched by any directive. These bindings go to // the element itself. const elId = this.scope.resolve(this.element); // TODO(alxhub): this could be more efficient. for (const binding of this.element.inputs) { if (binding.type === BindingType.Property && this.claimedInputs.has(binding.name)) { // Skip this binding as it was claimed by a directive. continue; } let expr = tcbExpression( binding.value, this.tcb, this.scope, binding.valueSpan || binding.sourceSpan); if (!this.tcb.env.config.checkTypeOfInputBindings) { // If checking the type of bindings is disabled, cast the resulting expression to 'any' // before the assignment. expr = tsCastToAny(expr); } else if (!this.tcb.env.config.strictNullInputBindings) { // If strict null checks are disabled, erase `null` and `undefined` from the type by // wrapping the expression in a non-null assertion. expr = ts.createNonNullExpression(expr); } if (this.tcb.env.config.checkTypeOfDomBindings && binding.type === BindingType.Property) { if (binding.name !== 'style' && binding.name !== 'class') { // A direct binding to a property. const propertyName = ATTR_TO_PROP[binding.name] || binding.name; const prop = ts.createPropertyAccess(elId, propertyName); const stmt = ts.createBinary(prop, ts.SyntaxKind.EqualsToken, wrapForDiagnostics(expr)); addParseSpanInfo(stmt, binding.sourceSpan); this.scope.addStatement(ts.createExpressionStatement(stmt)); } else { this.scope.addStatement(ts.createExpressionStatement(expr)); } } else { // A binding to an animation, attribute, class or style. For now, only validate the right- // hand side of the expression. // TODO: properly check class and style bindings. this.scope.addStatement(ts.createExpressionStatement(expr)); } } return null; } } /** * A `TcbOp` which generates code to check event bindings on an element that correspond with the * outputs of a directive. * * Executing this operation returns nothing. */ class TcbDirectiveOutputsOp extends TcbOp { constructor( private tcb: Context, private scope: Scope, private node: TmplAstTemplate|TmplAstElement, private dir: TypeCheckableDirectiveMeta) { super(); } execute(): null { const dirId = this.scope.resolve(this.node, this.dir); // `dir.outputs` is an object map of field names on the directive class to event names. // This is backwards from what's needed to match event handlers - a map of event names to field // names is desired. Invert `dir.outputs` into `fieldByEventName` to create this map. const fieldByEventName = new Map<string, string>(); const outputs = this.dir.outputs; for (const key of Object.keys(outputs)) { fieldByEventName.set(outputs[key], key); } for (const output of this.node.outputs) { if (output.type !== ParsedEventType.Regular || !fieldByEventName.has(output.name)) { continue; } const field = fieldByEventName.get(output.name) !; if (this.tcb.env.config.checkTypeOfOutputEvents) { // For strict checking of directive events, generate a call to the `subscribe` method // on the directive's output field to let type information flow into the handler function's // `$event` parameter. // // Note that the `EventEmitter<T>` type from '@angular/core' that is typically used for // outputs has a typings deficiency in its `subscribe` method. The generic type `T` is not // carried into the handler function, which is vital for inference of the type of `$event`. // As a workaround, the directive's field is passed into a helper function that has a // specially crafted set of signatures, to effectively cast `EventEmitter<T>` to something // that has a `subscribe` method that properly carries the `T` into the handler function. const handler = tcbCreateEventHandler(output, this.tcb, this.scope, EventParamType.Infer); const outputField = ts.createPropertyAccess(dirId, field); const outputHelper = ts.createCall(this.tcb.env.declareOutputHelper(), undefined, [outputField]); const subscribeFn = ts.createPropertyAccess(outputHelper, 'subscribe'); const call = ts.createCall(subscribeFn, /* typeArguments */ undefined, [handler]); addParseSpanInfo(call, output.sourceSpan); this.scope.addStatement(ts.createExpressionStatement(call)); } else { // If strict checking of directive events is disabled, emit a handler function where the // `$event` parameter has an explicit `any` type. const handler = tcbCreateEventHandler(output, this.tcb, this.scope, EventParamType.Any); this.scope.addStatement(ts.createExpressionStatement(handler)); } } return null; } } /** * A `TcbOp` which generates code to check "unclaimed outputs" - event bindings on an element which * were not attributed to any directive or component, and are instead processed against the HTML * element itself. * * Executing this operation returns nothing. */ class TcbUnclaimedOutputsOp extends TcbOp { constructor( private tcb: Context, private scope: Scope, private element: TmplAstElement, private claimedOutputs: Set<string>) { super(); } execute(): null { const elId = this.scope.resolve(this.element); // TODO(alxhub): this could be more efficient. for (const output of this.element.outputs) { if (this.claimedOutputs.has(output.name)) { // Skip this event handler as it was claimed by a directive. continue; } if (output.type === ParsedEventType.Animation) { // Animation output bindings always have an `$event` parameter of type `AnimationEvent`. const eventType = this.tcb.env.config.checkTypeOfAnimationEvents ? this.tcb.env.referenceExternalType('@angular/animations', 'AnimationEvent') : EventParamType.Any; const handler = tcbCreateEventHandler(output, this.tcb, this.scope, eventType); this.scope.addStatement(ts.createExpressionStatement(handler)); } else if (this.tcb.env.config.checkTypeOfDomEvents) { // If strict checking of DOM events is enabled, generate a call to `addEventListener` on // the element instance so that TypeScript's type inference for // `HTMLElement.addEventListener` using `HTMLElementEventMap` to infer an accurate type for // `$event` depending on the event name. For unknown event names, TypeScript resorts to the // base `Event` type. const handler = tcbCreateEventHandler(output, this.tcb, this.scope, EventParamType.Infer); const call = ts.createCall( /* expression */ ts.createPropertyAccess(elId, 'addEventListener'), /* typeArguments */ undefined, /* arguments */[ts.createStringLiteral(output.name), handler]); addParseSpanInfo(call, output.sourceSpan); this.scope.addStatement(ts.createExpressionStatement(call)); } else { // If strict checking of DOM inputs is disabled, emit a handler function where the `$event` // parameter has an explicit `any` type. const handler = tcbCreateEventHandler(output, this.tcb, this.scope, EventParamType.Any); this.scope.addStatement(ts.createExpressionStatement(handler)); } } return null; } } /** * Value used to break a circular reference between `TcbOp`s. * * This value is returned whenever `TcbOp`s have a circular dependency. The expression is a non-null * assertion of the null value (in TypeScript, the expression `null!`). This construction will infer * the least narrow type for whatever it's assigned to. */ const INFER_TYPE_FOR_CIRCULAR_OP_EXPR = ts.createNonNullExpression(ts.createNull()); /** * Overall generation context for the type check block. * * `Context` handles operations during code generation which are global with respect to the whole * block. It's responsible for variable name allocation and management of any imports needed. It * also contains the template metadata itself. */ export class Context { private nextId = 1; constructor( readonly env: Environment, readonly domSchemaChecker: DomSchemaChecker, readonly id: string, readonly boundTarget: BoundTarget<TypeCheckableDirectiveMeta>, private pipes: Map<string, Reference<ClassDeclaration<ts.ClassDeclaration>>>, readonly schemas: SchemaMetadata[]) {} /** * Allocate a new variable name for use within the `Context`. * * Currently this uses a monotonically increasing counter, but in the future the variable name * might change depending on the type of data being stored. */ allocateId(): ts.Identifier { return ts.createIdentifier(`_t${this.nextId++}`); } getPipeByName(name: string): ts.Expression { if (!this.pipes.has(name)) { throw new Error(`Missing pipe: ${name}`); } return this.env.pipeInst(this.pipes.get(name) !); } } /** * Local scope within the type check block for a particular template. * * The top-level template and each nested `<ng-template>` have their own `Scope`, which exist in a * hierarchy. The structure of this hierarchy mirrors the syntactic scopes in the generated type * check block, where each nested template is encased in an `if` structure. * * As a template's `TcbOp`s are executed in a given `Scope`, statements are added via * `addStatement()`. When this processing is complete, the `Scope` can be turned into a `ts.Block` * via `renderToBlock()`. * * If a `TcbOp` requires the output of another, it can call `resolve()`. */ class Scope { /** * A queue of operations which need to be performed to generate the TCB code for this scope. * * This array can contain either a `TcbOp` which has yet to be executed, or a `ts.Expression|null` * representing the memoized result of executing the operation. As operations are executed, their * results are written into the `opQueue`, overwriting the original operation. * * If an operation is in the process of being executed, it is temporarily overwritten here with * `INFER_TYPE_FOR_CIRCULAR_OP_EXPR`. This way, if a cycle is encountered where an operation * depends transitively on its own result, the inner operation will infer the least narrow type * that fits instead. This has the same semantics as TypeScript itself when types are referenced * circularly. */ private opQueue: (TcbOp|ts.Expression|null)[] = []; /** * A map of `TmplAstElement`s to the index of their `TcbElementOp` in the `opQueue` */ private elementOpMap = new Map<TmplAstElement, number>(); /** * A map of maps which tracks the index of `TcbDirectiveOp`s in the `opQueue` for each directive * on a `TmplAstElement` or `TmplAstTemplate` node. */ private directiveOpMap = new Map<TmplAstElement|TmplAstTemplate, Map<TypeCheckableDirectiveMeta, number>>(); /** * Map of immediately nested <ng-template>s (within this `Scope`) represented by `TmplAstTemplate` * nodes to the index of their `TcbTemplateContextOp`s in the `opQueue`. */ private templateCtxOpMap = new Map<TmplAstTemplate, number>(); /** * Map of variables declared on the template that created this `Scope` (represented by * `TmplAstVariable` nodes) to the index of their `TcbVariableOp`s in the `opQueue`. */ private varMap = new Map<TmplAstVariable, number>(); /** * Statements for this template. * * Executing the `TcbOp`s in the `opQueue` populates this array. */ private statements: ts.Statement[] = []; private constructor(private tcb: Context, private parent: Scope|null = null) {} /** * Constructs a `Scope` given either a `TmplAstTemplate` or a list of `TmplAstNode`s. * * @param tcb the overall context of TCB generation. * @param parent the `Scope` of the parent template (if any) or `null` if this is the root * `Scope`. * @param templateOrNodes either a `TmplAstTemplate` representing the template for which to * calculate the `Scope`, or a list of nodes if no outer template object is available. */ static forNodes( tcb: Context, parent: Scope|null, templateOrNodes: TmplAstTemplate|(TmplAstNode[])): Scope { const scope = new Scope(tcb, parent); let children: TmplAstNode[]; // If given an actual `TmplAstTemplate` instance, then process any additional information it // has. if (templateOrNodes instanceof TmplAstTemplate) { // The template's variable declarations need to be added as `TcbVariableOp`s. for (const v of templateOrNodes.variables) { const opIndex = scope.opQueue.push(new TcbVariableOp(tcb, scope, templateOrNodes, v)) - 1; scope.varMap.set(v, opIndex); } children = templateOrNodes.children; } else { children = templateOrNodes; } for (const node of children) { scope.appendNode(node); } return scope; } /** * Look up a `ts.Expression` representing the value of some operation in the current `Scope`, * including any parent scope(s). * * @param node a `TmplAstNode` of the operation in question. The lookup performed will depend on * the type of this node: * * Assuming `directive` is not present, then `resolve` will return: * * * `TmplAstElement` - retrieve the expression for the element DOM node * * `TmplAstTemplate` - retrieve the template context variable * * `TmplAstVariable` - retrieve a template let- variable * * @param directive if present, a directive type on a `TmplAstElement` or `TmplAstTemplate` to * look up instead of the default for an element or template node. */ resolve( node: TmplAstElement|TmplAstTemplate|TmplAstVariable, directive?: TypeCheckableDirectiveMeta): ts.Expression { // Attempt to resolve the operation locally. const res = this.resolveLocal(node, directive); if (res !== null) { return res; } else if (this.parent !== null) { // Check with the parent. return this.parent.resolve(node, directive); } else { throw new Error(`Could not resolve ${node} / ${directive}`); } } /** * Add a statement to this scope. */ addStatement(stmt: ts.Statement): void { this.statements.push(stmt); } /** * Get the statements. */ render(): ts.Statement[] { for (let i = 0; i < this.opQueue.length; i++) { this.executeOp(i); } return this.statements; } private resolveLocal( ref: TmplAstElement|TmplAstTemplate|TmplAstVariable, directive?: TypeCheckableDirectiveMeta): ts.Expression|null { if (ref instanceof TmplAstVariable && this.varMap.has(ref)) { // Resolving a context variable for this template. // Execute the `TcbVariableOp` associated with the `TmplAstVariable`. return this.resolveOp(this.varMap.get(ref) !); } else if ( ref instanceof TmplAstTemplate && directive === undefined && this.templateCtxOpMap.has(ref)) { // Resolving the context of the given sub-template. // Execute the `TcbTemplateContextOp` for the template. return this.resolveOp(this.templateCtxOpMap.get(ref) !); } else if ( (ref instanceof TmplAstElement || ref instanceof TmplAstTemplate) && directive !== undefined && this.directiveOpMap.has(ref)) { // Resolving a directive on an element or sub-template. const dirMap = this.directiveOpMap.get(ref) !; if (dirMap.has(directive)) { return this.resolveOp(dirMap.get(directive) !); } else { return null; } } else if (ref instanceof TmplAstElement && this.elementOpMap.has(ref)) { // Resolving the DOM node of an element in this template. return this.resolveOp(this.elementOpMap.get(ref) !); } else { return null; } } /** * Like `executeOp`, but assert that the operation actually returned `ts.Expression`. */ private resolveOp(opIndex: number): ts.Expression { const res = this.executeOp(opIndex); if (res === null) { throw new Error(`Error resolving operation, got null`); } return res; } /** * Execute a particular `TcbOp` in the `opQueue`. * * This method replaces the operation in the `opQueue` with the result of execution (once done) * and also protects against a circular dependency from the operation to itself by temporarily * setting the operation's result to a special expression. */ private executeOp(opIndex: number): ts.Expression|null { const op = this.opQueue[opIndex]; if (!(op instanceof TcbOp)) { return op; } // Set the result of the operation in the queue to a special expression. If executing this // operation results in a circular dependency, this will break the cycle and infer the least // narrow type where needed (which is how TypeScript deals with circular dependencies in types). this.opQueue[opIndex] = INFER_TYPE_FOR_CIRCULAR_OP_EXPR; const res = op.execute(); // Once the operation has finished executing, it's safe to cache the real result. this.opQueue[opIndex] = res; return res; } private appendNode(node: TmplAstNode): void { if (node instanceof TmplAstElement) { const opIndex = this.opQueue.push(new TcbElementOp(this.tcb, this, node)) - 1; this.elementOpMap.set(node, opIndex); this.appendDirectivesAndInputsOfNode(node); this.appendOutputsOfNode(node); for (const child of node.children) { this.appendNode(child); } } else if (node instanceof TmplAstTemplate) { // Template children are rendered in a child scope. this.appendDirectivesAndInputsOfNode(node); this.appendOutputsOfNode(node); if (this.tcb.env.config.checkTemplateBodies) { const ctxIndex = this.opQueue.push(new TcbTemplateContextOp(this.tcb, this)) - 1; this.templateCtxOpMap.set(node, ctxIndex); this.opQueue.push(new TcbTemplateBodyOp(this.tcb, this, node)); } } else if (node instanceof TmplAstBoundText) { this.opQueue.push(new TcbTextInterpolationOp(this.tcb, this, node)); } } private appendDirectivesAndInputsOfNode(node: TmplAstElement|TmplAstTemplate): void { // Collect all the inputs on the element. const claimedInputs = new Set<string>(); const directives = this.tcb.boundTarget.getDirectivesOfNode(node); if (directives === null || directives.length === 0) { // If there are no directives, then all inputs are unclaimed inputs, so queue an operation // to add them if needed. if (node instanceof TmplAstElement) { this.opQueue.push(new TcbUnclaimedInputsOp(this.tcb, this, node, claimedInputs)); this.opQueue.push( new TcbDomSchemaCheckerOp(this.tcb, node, /* checkElement */ true, claimedInputs)); } return; } const dirMap = new Map<TypeCheckableDirectiveMeta, number>(); for (const dir of directives) { const dirIndex = this.opQueue.push(new TcbDirectiveOp(this.tcb, this, node, dir)) - 1; dirMap.set(dir, dirIndex); } this.directiveOpMap.set(node, dirMap); // After expanding the directives, we might need to queue an operation to check any unclaimed // inputs. if (node instanceof TmplAstElement) { // Go through the directives and remove any inputs that it claims from `elementInputs`. for (const dir of directives) { for (const fieldName of Object.keys(dir.inputs)) { const value = dir.inputs[fieldName]; claimedInputs.add(Array.isArray(value) ? value[0] : value); } } this.opQueue.push(new TcbUnclaimedInputsOp(this.tcb, this, node, claimedInputs)); // If there are no directives which match this element, then it's a "plain" DOM element (or a // web component), and should be checked against the DOM schema. If any directives match, // we must assume that the element could be custom (either a component, or a directive like // <router-outlet>) and shouldn't validate the element name itself. const checkElement = directives.length === 0; this.opQueue.push(new TcbDomSchemaCheckerOp(this.tcb, node, checkElement, claimedInputs)); } } private appendOutputsOfNode(node: TmplAstElement|TmplAstTemplate): void { // Collect all the outputs on the element. const claimedOutputs = new Set<string>(); const directives = this.tcb.boundTarget.getDirectivesOfNode(node); if (directives === null || directives.length === 0) { // If there are no directives, then all outputs are unclaimed outputs, so queue an operation // to add them if needed. if (node instanceof TmplAstElement) { this.opQueue.push(new TcbUnclaimedOutputsOp(this.tcb, this, node, claimedOutputs)); } return; } // Queue operations for all directives to check the relevant outputs for a directive. for (const dir of directives) { this.opQueue.push(new TcbDirectiveOutputsOp(this.tcb, this, node, dir)); } // After expanding the directives, we might need to queue an operation to check any unclaimed // outputs. if (node instanceof TmplAstElement) { // Go through the directives and register any outputs that it claims in `claimedOutputs`. for (const dir of directives) { for (const outputField of Object.keys(dir.outputs)) { claimedOutputs.add(dir.outputs[outputField]); } } this.opQueue.push(new TcbUnclaimedOutputsOp(this.tcb, this, node, claimedOutputs)); } } } /** * Create the `ctx` parameter to the top-level TCB function. * * This is a parameter with a type equivalent to the component type, with all generic type * parameters listed (without their generic bounds). */ function tcbCtxParam( node: ClassDeclaration<ts.ClassDeclaration>, name: ts.EntityName): ts.ParameterDeclaration { let typeArguments: ts.TypeNode[]|undefined = undefined; // Check if the component is generic, and pass generic type parameters if so. if (node.typeParameters !== undefined) { typeArguments = node.typeParameters.map(param => ts.createTypeReferenceNode(param.name, undefined)); } const type = ts.createTypeReferenceNode(name, typeArguments); return ts.createParameter( /* decorators */ undefined, /* modifiers */ undefined, /* dotDotDotToken */ undefined, /* name */ 'ctx', /* questionToken */ undefined, /* type */ type, /* initializer */ undefined); } /** * Process an `AST` expression and convert it into a `ts.Expression`, generating references to the * correct identifiers in the current scope. */ function tcbExpression( ast: AST, tcb: Context, scope: Scope, sourceSpan: ParseSourceSpan): ts.Expression { const translator = new TcbExpressionTranslator(tcb, scope, sourceSpan); return translator.translate(ast); } class TcbExpressionTranslator { constructor( protected tcb: Context, protected scope: Scope, protected sourceSpan: ParseSourceSpan) {} translate(ast: AST): ts.Expression { // `astToTypescript` actually does the conversion. A special resolver `tcbResolve` is passed // which interprets specific expression nodes that interact with the `ImplicitReceiver`. These // nodes actually refer to identifiers within the current scope. return astToTypescript( ast, ast => this.resolve(ast), this.tcb.env.config, (span: ParseSpan) => toAbsoluteSpan(span, this.sourceSpan)); } /** * Resolve an `AST` expression within the given scope. * * Some `AST` expressions refer to top-level concepts (references, variables, the component * context). This method assists in resolving those. */ protected resolve(ast: AST): ts.Expression|null { if (ast instanceof PropertyRead && ast.receiver instanceof ImplicitReceiver) { // Check whether the template metadata has bound a target for this expression. If so, then // resolve that target. If not, then the expression is referencing the top-level component // context. const binding = this.tcb.boundTarget.getExpressionTarget(ast); if (binding !== null) { // This expression has a binding to some variable or reference in the template. Resolve it. if (binding instanceof TmplAstVariable) { const expr = ts.getMutableClone(this.scope.resolve(binding)); addParseSpanInfo(expr, toAbsoluteSpan(ast.span, this.sourceSpan)); return expr; } else if (binding instanceof TmplAstReference) { const target = this.tcb.boundTarget.getReferenceTarget(binding); if (target === null) { throw new Error(`Unbound reference? ${binding.name}`); } // The reference is either to an element, an <ng-template> node, or to a directive on an // element or template. if (target instanceof TmplAstElement) { const expr = ts.getMutableClone(this.scope.resolve(target)); addParseSpanInfo(expr, toAbsoluteSpan(ast.span, this.sourceSpan)); return expr; } else if (target instanceof TmplAstTemplate) { // Direct references to an <ng-template> node simply require a value of type // `TemplateRef<any>`. To get this, an expression of the form // `(null as any as TemplateRef<any>)` is constructed. let value: ts.Expression = ts.createNull(); value = ts.createAsExpression(value, ts.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword)); value = ts.createAsExpression( value, this.tcb.env.referenceExternalType('@angular/core', 'TemplateRef', [DYNAMIC_TYPE])); value = ts.createParen(value); addParseSpanInfo(value, toAbsoluteSpan(ast.span, this.sourceSpan)); return value; } else { const expr = ts.getMutableClone(this.scope.resolve(target.node, target.directive)); addParseSpanInfo(expr, toAbsoluteSpan(ast.span, this.sourceSpan)); return expr; } } else { throw new Error(`Unreachable: ${binding}`); } } else { // This is a PropertyRead(ImplicitReceiver) and probably refers to a property access on the // component context. Let it fall through resolution here so it will be caught when the // ImplicitReceiver is resolved in the branch below. return null; } } else if (ast instanceof ImplicitReceiver) { // AST instances representing variables and references look very similar to property reads // from the component context: both have the shape // PropertyRead(ImplicitReceiver, 'propertyName'). // // `tcbExpression` will first try to `tcbResolve` the outer PropertyRead. If this works, it's // because the `BoundTarget` found an expression target for the whole expression, and // therefore `tcbExpression` will never attempt to `tcbResolve` the ImplicitReceiver of that // PropertyRead. // // Therefore if `tcbResolve` is called on an `ImplicitReceiver`, it's because no outer // PropertyRead resolved to a variable or reference, and therefore this is a property read on // the component context itself. return ts.createIdentifier('ctx'); } else if (ast instanceof BindingPipe) { const expr = this.translate(ast.exp); let pipe: ts.Expression; if (this.tcb.env.config.checkTypeOfPipes) { pipe = this.tcb.getPipeByName(ast.name); } else { pipe = ts.createParen(ts.createAsExpression( ts.createNull(), ts.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword))); } const args = ast.args.map(arg => this.translate(arg)); const result = tsCallMethod(pipe, 'transform', [expr, ...args]); addParseSpanInfo(result, toAbsoluteSpan(ast.span, this.sourceSpan)); return result; } else if ( ast instanceof MethodCall && ast.receiver instanceof ImplicitReceiver && ast.name === '$any' && ast.args.length === 1) { const expr = this.translate(ast.args[0]); const exprAsAny = ts.createAsExpression(expr, ts.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword)); const result = ts.createParen(exprAsAny); addParseSpanInfo(result, toAbsoluteSpan(ast.span, this.sourceSpan)); return result; } else { // This AST isn't special after all. return null; } } } /** * Call the type constructor of a directive instance on a given template node, inferring a type for * the directive instance from any bound inputs. */ function tcbCallTypeCtor( dir: TypeCheckableDirectiveMeta, tcb: Context, inputs: TcbDirectiveInput[]): ts.Expression { const typeCtor = tcb.env.typeCtorFor(dir); // Construct an array of `ts.PropertyAssignment`s for each of the directive's inputs. const members = inputs.map(input => { if (input.type === 'binding') { // For bound inputs, the property is assigned the binding expression. let expr = input.expression; if (!tcb.env.config.checkTypeOfInputBindings) { // If checking the type of bindings is disabled, cast the resulting expression to 'any' // before the assignment. expr = tsCastToAny(expr); } else if (!tcb.env.config.strictNullInputBindings) { // If strict null checks are disabled, erase `null` and `undefined` from the type by // wrapping the expression in a non-null assertion. expr = ts.createNonNullExpression(expr); } const assignment = ts.createPropertyAssignment(input.field, wrapForDiagnostics(expr)); addParseSpanInfo(assignment, input.sourceSpan); return assignment; } else { // A type constructor is required to be called with all input properties, so any unset // inputs are simply assigned a value of type `any` to ignore them. return ts.createPropertyAssignment(input.field, NULL_AS_ANY); } }); // Call the `ngTypeCtor` method on the directive class, with an object literal argument created // from the matched inputs. return ts.createCall( /* expression */ typeCtor, /* typeArguments */ undefined, /* argumentsArray */[ts.createObjectLiteral(members)]); } type TcbDirectiveInput = { type: 'binding'; field: string; expression: ts.Expression; sourceSpan: ParseSourceSpan; } | { type: 'unset'; field: string; }; function tcbGetDirectiveInputs( el: TmplAstElement | TmplAstTemplate, dir: TypeCheckableDirectiveMeta, tcb: Context, scope: Scope): TcbDirectiveInput[] { const directiveInputs: TcbDirectiveInput[] = []; // `dir.inputs` is an object map of field names on the directive class to property names. // This is backwards from what's needed to match bindings - a map of properties to field names // is desired. Invert `dir.inputs` into `propMatch` to create this map. const propMatch = new Map<string, string>(); const inputs = dir.inputs; Object.keys(inputs).forEach(key => { Array.isArray(inputs[key]) ? propMatch.set(inputs[key][0], key) : propMatch.set(inputs[key] as string, key); }); // To determine which of directive's inputs are unset, we keep track of the set of field names // that have not been seen yet. A field is removed from this set once a binding to it is found. const unsetFields = new Set(propMatch.values()); el.inputs.forEach(processAttribute); el.attributes.forEach(processAttribute); if (el instanceof TmplAstTemplate) { el.templateAttrs.forEach(processAttribute); } // Add unset directive inputs for each of the remaining unset fields. for (const field of unsetFields) { directiveInputs.push({type: 'unset', field}); } return directiveInputs; /** * Add a binding expression to the map for each input/template attribute of the directive that has * a matching binding. */ function processAttribute(attr: TmplAstBoundAttribute | TmplAstTextAttribute): void { // Skip non-property bindings. if (attr instanceof TmplAstBoundAttribute && attr.type !== BindingType.Property) { return; } // Skip the attribute if the directive does not have an input for it. if (!propMatch.has(attr.name)) { return; } const field = propMatch.get(attr.name) !; // Remove the field from the set of unseen fields, now that it's been assigned to. unsetFields.delete(field); let expr: ts.Expression; if (attr instanceof TmplAstBoundAttribute) { // Produce an expression representing the value of the binding. expr = tcbExpression(attr.value, tcb, scope, attr.valueSpan || attr.sourceSpan); } else { // For regular attributes with a static string value, use the represented string literal. expr = ts.createStringLiteral(attr.value); } directiveInputs.push({ type: 'binding', field: field, expression: expr, sourceSpan: attr.sourceSpan, }); } } const EVENT_PARAMETER = '$event'; const enum EventParamType { /* Generates code to infer the type of `$event` based on how the listener is registered. */ Infer, /* Declares the type of the `$event` parameter as `any`. */ Any, } /** * Creates an arrow function to be used as handler function for event bindings. The handler * function has a single parameter `$event` and the bound event's handler `AST` represented as a * TypeScript expression as its body. * * When `eventType` is set to `Infer`, the `$event` parameter will not have an explicit type. This * allows for the created handler function to have its `$event` parameter's type inferred based on * how it's used, to enable strict type checking of event bindings. When set to `Any`, the `$event` * parameter will have an explicit `any` type, effectively disabling strict type checking of event * bindings. Alternatively, an explicit type can be passed for the `$event` parameter. */ function tcbCreateEventHandler( event: TmplAstBoundEvent, tcb: Context, scope: Scope, eventType: EventParamType | ts.TypeNode): ts.ArrowFunction { const handler = tcbEventHandlerExpression(event.handler, tcb, scope, event.handlerSpan); let eventParamType: ts.TypeNode|undefined; if (eventType === EventParamType.Infer) { eventParamType = undefined; } else if (eventType === EventParamType.Any) { eventParamType = ts.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword); } else { eventParamType = eventType; } const eventParam = ts.createParameter( /* decorators */ undefined, /* modifiers */ undefined, /* dotDotDotToken */ undefined, /* name */ EVENT_PARAMETER, /* questionToken */ undefined, /* type */ eventParamType); return ts.createArrowFunction( /* modifier */ undefined, /* typeParameters */ undefined, /* parameters */[eventParam], /* type */ undefined, /* equalsGreaterThanToken*/ undefined, /* body */ handler); } /** * Similar to `tcbExpression`, this function converts the provided `AST` expression into a * `ts.Expression`, with special handling of the `$event` variable that can be used within event * bindings. */ function tcbEventHandlerExpression( ast: AST, tcb: Context, scope: Scope, sourceSpan: ParseSourceSpan): ts.Expression { const translator = new TcbEventHandlerTranslator(tcb, scope, sourceSpan); return translator.translate(ast); } class TcbEventHandlerTranslator extends TcbExpressionTranslator { protected resolve(ast: AST): ts.Expression|null { // Recognize a property read on the implicit receiver corresponding with the event parameter // that is available in event bindings. Since this variable is a parameter of the handler // function that the converted expression becomes a child of, just create a reference to the // parameter by its name. if (ast instanceof PropertyRead && ast.receiver instanceof ImplicitReceiver && ast.name === EVENT_PARAMETER) { const event = ts.createIdentifier(EVENT_PARAMETER); addParseSpanInfo(event, toAbsoluteSpan(ast.span, this.sourceSpan)); return event; } return super.resolve(ast); } } export function requiresInlineTypeCheckBlock(node: ClassDeclaration<ts.ClassDeclaration>): boolean { // In order to qualify for a declared TCB (not inline) two conditions must be met: // 1) the class must be exported // 2) it must not have constrained generic types if (!checkIfClassIsExported(node)) { // Condition 1 is false, the class is not exported. return true; } else if (!checkIfGenericTypesAreUnbound(node)) { // Condition 2 is false, the class has constrained generic types return true; } else { return false; } }
packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts
1
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.7154819369316101, 0.005925043951719999, 0.0001627122110221535, 0.00016823771875351667, 0.06372019648551941 ]
{ "id": 2, "code_window": [ " * `$event` variable will be of type `any`.\n", " */\n", " checkTypeOfDomEvents: boolean;\n", "\n", " /**\n", " * Whether to include type information from pipes in the type-checking operation.\n", " *\n", " * If this is `true`, then the pipe's type signature for `transform()` will be used to check the\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * Whether to infer the type of local references.\n", " *\n", " * If this is `true`, the type of any `#ref` variable in the template will be determined by the\n", " * referenced entity (either a directive or a DOM element). If set to `false`, the type of `ref`\n", " * will be `any`.\n", " */\n", " checkTypeOfReferences: boolean;\n", "\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/src/api.ts", "type": "add", "edit_start_line_idx": 135 }
import { Component, CUSTOM_ELEMENTS_SCHEMA, DebugElement } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { asapScheduler, BehaviorSubject } from 'rxjs'; import { ScrollService } from 'app/shared/scroll.service'; import { TocItem, TocService } from 'app/shared/toc.service'; import { TocComponent } from './toc.component'; describe('TocComponent', () => { let tocComponentDe: DebugElement; let tocComponent: TocComponent; let tocService: TestTocService; let page: { listItems: DebugElement[]; tocHeading: DebugElement; tocHeadingButtonEmbedded: DebugElement; tocH1Heading: DebugElement; tocMoreButton: DebugElement; }; function setPage(): typeof page { return { listItems: tocComponentDe.queryAll(By.css('ul.toc-list>li')), tocHeading: tocComponentDe.query(By.css('.toc-heading')), tocHeadingButtonEmbedded: tocComponentDe.query(By.css('button.toc-heading.embedded')), tocH1Heading: tocComponentDe.query(By.css('.h1')), tocMoreButton: tocComponentDe.query(By.css('button.toc-more-items')), }; } beforeEach(() => { TestBed.configureTestingModule({ declarations: [ HostEmbeddedTocComponent, HostNotEmbeddedTocComponent, TocComponent ], providers: [ { provide: ScrollService, useClass: TestScrollService }, { provide: TocService, useClass: TestTocService } ], schemas: [CUSTOM_ELEMENTS_SCHEMA] }); }); describe('when embedded in doc body', () => { let fixture: ComponentFixture<HostEmbeddedTocComponent>; beforeEach(() => { fixture = TestBed.createComponent(HostEmbeddedTocComponent); tocComponentDe = fixture.debugElement.children[0]; tocComponent = tocComponentDe.componentInstance; tocService = TestBed.inject(TocService) as unknown as TestTocService; }); it('should create tocComponent', () => { expect(tocComponent).toBeTruthy(); }); it('should be in embedded state', () => { expect(tocComponent.isEmbedded).toEqual(true); }); it('should not display a ToC initially', () => { expect(tocComponent.type).toEqual('None'); }); describe('(once the lifecycle hooks have run)', () => { beforeEach(() => fixture.detectChanges()); it('should not display anything when no h2 or h3 TocItems', () => { tocService.tocList.next([tocItem('H1', 'h1')]); fixture.detectChanges(); expect(tocComponentDe.children.length).toEqual(0); }); it('should update when the TocItems are updated', () => { tocService.tocList.next([tocItem('Heading A')]); fixture.detectChanges(); expect(tocComponentDe.queryAll(By.css('li')).length).toBe(1); tocService.tocList.next([tocItem('Heading A'), tocItem('Heading B'), tocItem('Heading C')]); fixture.detectChanges(); expect(tocComponentDe.queryAll(By.css('li')).length).toBe(3); }); it('should only display H2 and H3 TocItems', () => { tocService.tocList.next([tocItem('Heading A', 'h1'), tocItem('Heading B'), tocItem('Heading C', 'h3')]); fixture.detectChanges(); const tocItems = tocComponentDe.queryAll(By.css('li')); const textContents = tocItems.map(item => item.nativeNode.textContent.trim()); expect(tocItems.length).toBe(2); expect(textContents.find(text => text === 'Heading A')).toBeFalsy(); expect(textContents.find(text => text === 'Heading B')).toBeTruthy(); expect(textContents.find(text => text === 'Heading C')).toBeTruthy(); expect(setPage().tocH1Heading).toBeFalsy(); }); it('should stop listening for TocItems once destroyed', () => { tocService.tocList.next([tocItem('Heading A')]); fixture.detectChanges(); expect(tocComponentDe.queryAll(By.css('li')).length).toBe(1); tocComponent.ngOnDestroy(); tocService.tocList.next([tocItem('Heading A', 'h1'), tocItem('Heading B'), tocItem('Heading C')]); fixture.detectChanges(); expect(tocComponentDe.queryAll(By.css('li')).length).toBe(1); }); describe('when fewer than `maxPrimary` TocItems', () => { beforeEach(() => { tocService.tocList.next([tocItem('Heading A'), tocItem('Heading B'), tocItem('Heading C'), tocItem('Heading D')]); fixture.detectChanges(); page = setPage(); }); it('should have four displayed items', () => { expect(page.listItems.length).toEqual(4); }); it('should not have secondary items', () => { expect(tocComponent.type).toEqual('EmbeddedSimple'); const aSecond = page.listItems.find(item => item.classes.secondary); expect(aSecond).toBeFalsy('should not find a secondary'); }); it('should not display expando buttons', () => { expect(page.tocHeadingButtonEmbedded).toBeFalsy('top expand/collapse button'); expect(page.tocMoreButton).toBeFalsy('bottom more button'); }); }); describe('when many TocItems', () => { let scrollToTopSpy: jasmine.Spy; beforeEach(() => { fixture.detectChanges(); page = setPage(); scrollToTopSpy = (TestBed.inject(ScrollService) as unknown as TestScrollService).scrollToTop; }); it('should have more than 4 displayed items', () => { expect(page.listItems.length).toBeGreaterThan(4); }); it('should not display the h1 item', () => { expect(page.listItems.find(item => item.classes.h1)).toBeFalsy('should not find h1 item'); }); it('should be in "collapsed" (not expanded) state at the start', () => { expect(tocComponent.isCollapsed).toBeTruthy(); }); it('should have "collapsed" class at the start', () => { expect(tocComponentDe.children[0].classes.collapsed).toEqual(true); }); it('should display expando buttons', () => { expect(page.tocHeadingButtonEmbedded).toBeTruthy('top expand/collapse button'); expect(page.tocMoreButton).toBeTruthy('bottom more button'); }); it('should have secondary items', () => { expect(tocComponent.type).toEqual('EmbeddedExpandable'); }); // CSS will hide items with the secondary class when collapsed it('should have secondary item with a secondary class', () => { const aSecondary = page.listItems.find(item => item.classes.secondary); expect(aSecondary).toBeTruthy('should find a secondary'); }); describe('after click tocHeading button', () => { beforeEach(() => { page.tocHeadingButtonEmbedded.nativeElement.click(); fixture.detectChanges(); }); it('should not be "collapsed"', () => { expect(tocComponent.isCollapsed).toEqual(false); }); it('should not have "collapsed" class', () => { expect(tocComponentDe.children[0].classes.collapsed).toBeFalsy(); }); it('should not scroll', () => { expect(scrollToTopSpy).not.toHaveBeenCalled(); }); it('should be "collapsed" after clicking again', () => { page.tocHeadingButtonEmbedded.nativeElement.click(); fixture.detectChanges(); expect(tocComponent.isCollapsed).toEqual(true); }); it('should not scroll after clicking again', () => { page.tocHeadingButtonEmbedded.nativeElement.click(); fixture.detectChanges(); expect(scrollToTopSpy).not.toHaveBeenCalled(); }); }); describe('after click tocMore button', () => { beforeEach(() => { page.tocMoreButton.nativeElement.click(); fixture.detectChanges(); }); it('should not be "collapsed"', () => { expect(tocComponent.isCollapsed).toEqual(false); }); it('should not have "collapsed" class', () => { expect(tocComponentDe.children[0].classes.collapsed).toBeFalsy(); }); it('should not scroll', () => { expect(scrollToTopSpy).not.toHaveBeenCalled(); }); it('should be "collapsed" after clicking again', () => { page.tocMoreButton.nativeElement.click(); fixture.detectChanges(); expect(tocComponent.isCollapsed).toEqual(true); }); it('should be "collapsed" after clicking tocHeadingButton', () => { page.tocMoreButton.nativeElement.click(); fixture.detectChanges(); expect(tocComponent.isCollapsed).toEqual(true); }); it('should scroll after clicking again', () => { page.tocMoreButton.nativeElement.click(); fixture.detectChanges(); expect(scrollToTopSpy).toHaveBeenCalled(); }); }); }); }); }); describe('when in side panel (not embedded)', () => { let fixture: ComponentFixture<HostNotEmbeddedTocComponent>; beforeEach(() => { fixture = TestBed.createComponent(HostNotEmbeddedTocComponent); tocComponentDe = fixture.debugElement.children[0]; tocComponent = tocComponentDe.componentInstance; tocService = TestBed.inject(TocService) as unknown as TestTocService; fixture.detectChanges(); page = setPage(); }); it('should not be in embedded state', () => { expect(tocComponent.isEmbedded).toEqual(false); expect(tocComponent.type).toEqual('Floating'); }); it('should display all items (including h1s)', () => { expect(page.listItems.length).toEqual(getTestTocList().length); }); it('should not have secondary items', () => { expect(tocComponent.type).toEqual('Floating'); const aSecond = page.listItems.find(item => item.classes.secondary); expect(aSecond).toBeFalsy('should not find a secondary'); }); it('should not display expando buttons', () => { expect(page.tocHeadingButtonEmbedded).toBeFalsy('top expand/collapse button'); expect(page.tocMoreButton).toBeFalsy('bottom more button'); }); it('should display H1 title', () => { expect(page.tocH1Heading).toBeTruthy(); }); describe('#activeIndex', () => { it('should keep track of `TocService`\'s `activeItemIndex`', () => { expect(tocComponent.activeIndex).toBeNull(); tocService.setActiveIndex(42); expect(tocComponent.activeIndex).toBe(42); tocService.setActiveIndex(null); expect(tocComponent.activeIndex).toBeNull(); }); it('should stop tracking `activeItemIndex` once destroyed', () => { tocService.setActiveIndex(42); expect(tocComponent.activeIndex).toBe(42); tocComponent.ngOnDestroy(); tocService.setActiveIndex(43); expect(tocComponent.activeIndex).toBe(42); tocService.setActiveIndex(null); expect(tocComponent.activeIndex).toBe(42); }); it('should set the `active` class to the active anchor (and only that)', () => { expect(page.listItems.findIndex(By.css('.active'))).toBe(-1); tocComponent.activeIndex = 1; fixture.detectChanges(); expect(page.listItems.filter(By.css('.active')).length).toBe(1); expect(page.listItems.findIndex(By.css('.active'))).toBe(1); tocComponent.activeIndex = null; fixture.detectChanges(); expect(page.listItems.filter(By.css('.active')).length).toBe(0); expect(page.listItems.findIndex(By.css('.active'))).toBe(-1); tocComponent.activeIndex = 0; fixture.detectChanges(); expect(page.listItems.filter(By.css('.active')).length).toBe(1); expect(page.listItems.findIndex(By.css('.active'))).toBe(0); tocComponent.activeIndex = 1337; fixture.detectChanges(); expect(page.listItems.filter(By.css('.active')).length).toBe(0); expect(page.listItems.findIndex(By.css('.active'))).toBe(-1); tocComponent.activeIndex = page.listItems.length - 1; fixture.detectChanges(); expect(page.listItems.filter(By.css('.active')).length).toBe(1); expect(page.listItems.findIndex(By.css('.active'))).toBe(page.listItems.length - 1); }); it('should re-apply the `active` class when the list elements change', () => { const getActiveTextContent = () => page.listItems.find(By.css('.active'))!.nativeElement.textContent.trim(); tocComponent.activeIndex = 1; fixture.detectChanges(); expect(getActiveTextContent()).toBe('Heading one'); tocComponent.tocList = [tocItem('New 1'), tocItem('New 2')]; fixture.detectChanges(); page = setPage(); expect(getActiveTextContent()).toBe('New 2'); tocComponent.tocList.unshift(tocItem('New 0')); fixture.detectChanges(); page = setPage(); expect(getActiveTextContent()).toBe('New 1'); tocComponent.tocList = [tocItem('Very New 1')]; fixture.detectChanges(); page = setPage(); expect(page.listItems.findIndex(By.css('.active'))).toBe(-1); tocComponent.activeIndex = 0; fixture.detectChanges(); expect(getActiveTextContent()).toBe('Very New 1'); }); describe('should scroll the active ToC item into viewport (if not already visible)', () => { let parentScrollTop: number; beforeEach(() => { const hostElem = fixture.nativeElement; const firstItem = page.listItems[0].nativeElement; Object.assign(hostElem.style, { display: 'block', maxHeight: `${hostElem.clientHeight - firstItem.clientHeight}px`, overflow: 'auto', position: 'relative', }); Object.defineProperty(hostElem, 'scrollTop', { get: () => parentScrollTop, set: v => parentScrollTop = v, }); parentScrollTop = 0; }); it('when the `activeIndex` changes', () => { tocService.setActiveIndex(0); fixture.detectChanges(); expect(parentScrollTop).toBe(0); tocService.setActiveIndex(1); fixture.detectChanges(); expect(parentScrollTop).toBe(0); tocService.setActiveIndex(page.listItems.length - 1); fixture.detectChanges(); expect(parentScrollTop).toBeGreaterThan(0); }); it('when the `tocList` changes', () => { const tocList = tocComponent.tocList; tocComponent.tocList = []; fixture.detectChanges(); expect(parentScrollTop).toBe(0); tocService.setActiveIndex(tocList.length - 1); fixture.detectChanges(); expect(parentScrollTop).toBe(0); tocComponent.tocList = tocList; fixture.detectChanges(); expect(parentScrollTop).toBeGreaterThan(0); }); it('not after it has been destroyed', () => { const tocList = tocComponent.tocList; tocComponent.ngOnDestroy(); tocService.setActiveIndex(page.listItems.length - 1); fixture.detectChanges(); expect(parentScrollTop).toBe(0); tocComponent.tocList = []; fixture.detectChanges(); expect(parentScrollTop).toBe(0); tocComponent.tocList = tocList; fixture.detectChanges(); expect(parentScrollTop).toBe(0); }); }); }); }); }); //// helpers //// @Component({ selector: 'aio-embedded-host', template: '<aio-toc class="embedded"></aio-toc>' }) class HostEmbeddedTocComponent {} @Component({ selector: 'aio-not-embedded-host', template: '<aio-toc></aio-toc>' }) class HostNotEmbeddedTocComponent {} class TestScrollService { scrollToTop = jasmine.createSpy('scrollToTop'); } class TestTocService { tocList = new BehaviorSubject<TocItem[]>(getTestTocList()); activeItemIndex = new BehaviorSubject<number | null>(null); setActiveIndex(index: number|null) { this.activeItemIndex.next(index); if (asapScheduler.actions.length > 0) { asapScheduler.flush(); } } } function tocItem(title: string, level = 'h2', href = '', content = title) { return { title, href, level, content }; } function getTestTocList() { return [ tocItem('Title', 'h1', 'fizz/buzz#title', 'Title'), tocItem('Heading one', 'h2', 'fizz/buzz#heading-one-special-id', 'Heading one'), tocItem('H2 Two', 'h2', 'fizz/buzz#h2-two', 'H2 Two'), tocItem('H2 Three', 'h2', 'fizz/buzz#h2-three', 'H2 <b>Three</b>'), tocItem('H3 3a', 'h3', 'fizz/buzz#h3-3a', 'H3 3a'), tocItem('H3 3b', 'h3', 'fizz/buzz#h3-3b', 'H3 3b'), tocItem('H2 4', 'h2', 'fizz/buzz#h2-four', '<i>H2 <b>four</b></i>'), ]; }
aio/src/app/custom-elements/toc/toc.component.spec.ts
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.00021137321891728789, 0.00017134530935436487, 0.00016591613530181348, 0.000170317041920498, 0.000006052948720025597 ]
{ "id": 2, "code_window": [ " * `$event` variable will be of type `any`.\n", " */\n", " checkTypeOfDomEvents: boolean;\n", "\n", " /**\n", " * Whether to include type information from pipes in the type-checking operation.\n", " *\n", " * If this is `true`, then the pipe's type signature for `transform()` will be used to check the\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * Whether to infer the type of local references.\n", " *\n", " * If this is `true`, the type of any `#ref` variable in the template will be determined by the\n", " * referenced entity (either a directive or a DOM element). If set to `false`, the type of `ref`\n", " * will be `any`.\n", " */\n", " checkTypeOfReferences: boolean;\n", "\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/src/api.ts", "type": "add", "edit_start_line_idx": 135 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {enableProdMode} from '@angular/core'; import {bindAction, profile} from '../../util'; import {buildTree, emptyTree} from '../util'; import {AppModule, TreeComponent} from './tree'; let tree: TreeComponent; let appMod: AppModule; let detectChangesRuns = 0; function destroyDom() { tree.data = emptyTree; appMod.tick(); } function createDom() { tree.data = buildTree(); appMod.tick(); } function detectChanges() { for (let i = 0; i < 10; i++) { appMod.tick(); } detectChangesRuns += 10; numberOfChecksEl.textContent = `${detectChangesRuns}`; } function noop() {} const numberOfChecksEl = document.getElementById('numberOfChecks'); enableProdMode(); appMod = new AppModule(); appMod.bootstrap(); tree = appMod.componentRef.instance; bindAction('#destroyDom', destroyDom); bindAction('#createDom', createDom); bindAction('#detectChanges', detectChanges); bindAction('#detectChangesProfile', profile(detectChanges, noop, 'detectChanges')); bindAction('#updateDomProfile', profile(createDom, noop, 'update')); bindAction('#createDomProfile', profile(createDom, destroyDom, 'create'));
modules/benchmarks/src/tree/ng2_next/index.ts
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.00017150102939922363, 0.0001696687686489895, 0.00016724687884561718, 0.00016984247486107051, 0.0000013488318018062273 ]
{ "id": 2, "code_window": [ " * `$event` variable will be of type `any`.\n", " */\n", " checkTypeOfDomEvents: boolean;\n", "\n", " /**\n", " * Whether to include type information from pipes in the type-checking operation.\n", " *\n", " * If this is `true`, then the pipe's type signature for `transform()` will be used to check the\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " /**\n", " * Whether to infer the type of local references.\n", " *\n", " * If this is `true`, the type of any `#ref` variable in the template will be determined by the\n", " * referenced entity (either a directive or a DOM element). If set to `false`, the type of `ref`\n", " * will be `any`.\n", " */\n", " checkTypeOfReferences: boolean;\n", "\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/src/api.ts", "type": "add", "edit_start_line_idx": 135 }
const disambiguateByDeprecated = require('./disambiguateByDeprecated')(); const docs = [ { id: 'doc1' }, { id: 'doc2', deprecated: true }, { id: 'doc3', deprecated: '' }, { id: 'doc4' }, { id: 'doc5', deprecated: 'Some text' }, ]; describe('disambiguateByDeprecated', () => { it('should filter out docs whose `deprecated` property is defined', () => { expect(disambiguateByDeprecated('alias', {}, docs)).toEqual([ { id: 'doc1' }, { id: 'doc4' }, ]); }); });
aio/tools/transforms/links-package/services/disambiguators/disambiguateByDeprecated.spec.js
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.00017062562983483076, 0.00017013780598063022, 0.00016964998212642968, 0.00017013780598063022, 4.87823854200542e-7 ]
{ "id": 3, "code_window": [ " addParseSpanInfo(expr, toAbsoluteSpan(ast.span, this.sourceSpan));\n", " return expr;\n", " } else if (binding instanceof TmplAstReference) {\n", " const target = this.tcb.boundTarget.getReferenceTarget(binding);\n", " if (target === null) {\n", " throw new Error(`Unbound reference? ${binding.name}`);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (!this.tcb.env.config.checkTypeOfReferences) {\n", " // References are pinned to 'any'.\n", " return NULL_AS_ANY;\n", " }\n", "\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts", "type": "add", "edit_start_line_idx": 956 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {CssSelector, ParseSourceFile, ParseSourceSpan, R3TargetBinder, SchemaMetadata, SelectorMatcher, TmplAstElement, Type, parseTemplate} from '@angular/compiler'; import * as ts from 'typescript'; import {AbsoluteFsPath, LogicalFileSystem, absoluteFrom} from '../../file_system'; import {TestFile} from '../../file_system/testing'; import {AbsoluteModuleStrategy, LocalIdentifierStrategy, LogicalProjectStrategy, Reference, ReferenceEmitter} from '../../imports'; import {ClassDeclaration, TypeScriptReflectionHost, isNamedClassDeclaration} from '../../reflection'; import {makeProgram} from '../../testing'; import {getRootDirs} from '../../util/src/typescript'; import {TemplateSourceMapping, TypeCheckBlockMetadata, TypeCheckableDirectiveMeta, TypeCheckingConfig} from '../src/api'; import {TypeCheckContext} from '../src/context'; import {DomSchemaChecker} from '../src/dom'; import {Environment} from '../src/environment'; import {generateTypeCheckBlock} from '../src/type_check_block'; export function typescriptLibDts(): TestFile { return { name: absoluteFrom('/lib.d.ts'), contents: ` type Partial<T> = { [P in keyof T]?: T[P]; }; type Pick<T, K extends keyof T> = { [P in K]: T[P]; }; type NonNullable<T> = T extends null | undefined ? never : T; // The following native type declarations are required for proper type inference declare interface Function { call(...args: any[]): any; } declare interface Array<T> { length: number; } declare interface String { length: number; } declare interface Event { preventDefault(): void; } declare interface MouseEvent extends Event { readonly x: number; readonly y: number; } declare interface HTMLElementEventMap { "click": MouseEvent; } declare interface HTMLElement { addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any): void; addEventListener(type: string, listener: (evt: Event): void;): void; } declare interface HTMLDivElement extends HTMLElement {} declare interface HTMLImageElement extends HTMLElement { src: string; alt: string; width: number; height: number; } declare interface HTMLQuoteElement extends HTMLElement { cite: string; } declare interface HTMLElementTagNameMap { "blockquote": HTMLQuoteElement; "div": HTMLDivElement; "img": HTMLImageElement; } declare interface Document { createElement<K extends keyof HTMLElementTagNameMap>(tagName: K): HTMLElementTagNameMap[K]; createElement(tagName: string): HTMLElement; } declare const document: Document; ` }; } export function angularCoreDts(): TestFile { return { name: absoluteFrom('/node_modules/@angular/core/index.d.ts'), contents: ` export declare class TemplateRef<C> { abstract readonly elementRef: unknown; abstract createEmbeddedView(context: C): unknown; } export declare class EventEmitter<T> { subscribe(generatorOrNext?: any, error?: any, complete?: any): unknown; } ` }; } export function angularAnimationsDts(): TestFile { return { name: absoluteFrom('/node_modules/@angular/animations/index.d.ts'), contents: ` export declare class AnimationEvent { element: any; } ` }; } export function ngForDeclaration(): TestDeclaration { return { type: 'directive', file: absoluteFrom('/ngfor.d.ts'), selector: '[ngForOf]', name: 'NgForOf', inputs: {ngForOf: 'ngForOf'}, hasNgTemplateContextGuard: true, }; } export function ngForDts(): TestFile { return { name: absoluteFrom('/ngfor.d.ts'), contents: ` export declare class NgForOf<T> { ngForOf: T[]; ngForTrackBy: TrackByFunction<T>; static ngTemplateContextGuard<T>(dir: NgForOf<T>, ctx: any): ctx is NgForOfContext<T>; } export interface TrackByFunction<T> { (index: number, item: T): any; } export declare class NgForOfContext<T> { $implicit: T; index: number; count: number; readonly odd: boolean; readonly even: boolean; readonly first: boolean; readonly last: boolean; }`, }; } export const ALL_ENABLED_CONFIG: TypeCheckingConfig = { applyTemplateContextGuards: true, checkQueries: false, checkTemplateBodies: true, checkTypeOfInputBindings: true, strictNullInputBindings: true, // Feature is still in development. // TODO(alxhub): enable when DOM checking via lib.dom.d.ts is further along. checkTypeOfDomBindings: false, checkTypeOfOutputEvents: true, checkTypeOfAnimationEvents: true, checkTypeOfDomEvents: true, checkTypeOfPipes: true, strictSafeNavigationTypes: true, }; // Remove 'ref' from TypeCheckableDirectiveMeta and add a 'selector' instead. export type TestDirective = Partial<Pick<TypeCheckableDirectiveMeta, Exclude<keyof TypeCheckableDirectiveMeta, 'ref'>>>& {selector: string, name: string, file?: AbsoluteFsPath, type: 'directive'}; export type TestPipe = { name: string, file?: AbsoluteFsPath, pipeName: string, type: 'pipe', }; export type TestDeclaration = TestDirective | TestPipe; export function tcb( template: string, declarations: TestDeclaration[] = [], config?: TypeCheckingConfig, options?: {emitSpans?: boolean}): string { const classes = ['Test', ...declarations.map(decl => decl.name)]; const code = classes.map(name => `class ${name}<T extends string> {}`).join('\n'); const sf = ts.createSourceFile('synthetic.ts', code, ts.ScriptTarget.Latest, true); const clazz = getClass(sf, 'Test'); const templateUrl = 'synthetic.html'; const {nodes} = parseTemplate(template, templateUrl); const {matcher, pipes} = prepareDeclarations(declarations, decl => getClass(sf, decl.name)); const binder = new R3TargetBinder(matcher); const boundTarget = binder.bind({template: nodes}); const meta: TypeCheckBlockMetadata = {boundTarget, pipes, id: 'tcb', schemas: []}; config = config || { applyTemplateContextGuards: true, checkQueries: false, checkTypeOfInputBindings: true, strictNullInputBindings: true, checkTypeOfDomBindings: false, checkTypeOfOutputEvents: true, checkTypeOfAnimationEvents: true, checkTypeOfDomEvents: true, checkTypeOfPipes: true, checkTemplateBodies: true, strictSafeNavigationTypes: true, }; options = options || { emitSpans: false, }; const tcb = generateTypeCheckBlock( FakeEnvironment.newFake(config), new Reference(clazz), ts.createIdentifier('Test_TCB'), meta, new NoopSchemaChecker()); const removeComments = !options.emitSpans; const res = ts.createPrinter({removeComments}).printNode(ts.EmitHint.Unspecified, tcb, sf); return res.replace(/\s+/g, ' '); } export function typecheck( template: string, source: string, declarations: TestDeclaration[] = [], additionalSources: {name: AbsoluteFsPath; contents: string}[] = []): ts.Diagnostic[] { const typeCheckFilePath = absoluteFrom('/_typecheck_.ts'); const files = [ typescriptLibDts(), angularCoreDts(), angularAnimationsDts(), // Add the typecheck file to the program, as the typecheck program is created with the // assumption that the typecheck file was already a root file in the original program. {name: typeCheckFilePath, contents: 'export const TYPECHECK = true;'}, {name: absoluteFrom('/main.ts'), contents: source}, ...additionalSources, ]; const {program, host, options} = makeProgram(files, {strictNullChecks: true, noImplicitAny: true}, undefined, false); const sf = program.getSourceFile(absoluteFrom('/main.ts')) !; const checker = program.getTypeChecker(); const logicalFs = new LogicalFileSystem(getRootDirs(host, options)); const reflectionHost = new TypeScriptReflectionHost(checker); const emitter = new ReferenceEmitter([ new LocalIdentifierStrategy(), new AbsoluteModuleStrategy( program, checker, options, host, new TypeScriptReflectionHost(checker)), new LogicalProjectStrategy(reflectionHost, logicalFs), ]); const ctx = new TypeCheckContext(ALL_ENABLED_CONFIG, emitter, typeCheckFilePath); const templateUrl = 'synthetic.html'; const templateFile = new ParseSourceFile(template, templateUrl); const {nodes, errors} = parseTemplate(template, templateUrl); if (errors !== undefined) { throw new Error('Template parse errors: \n' + errors.join('\n')); } const {matcher, pipes} = prepareDeclarations(declarations, decl => { let declFile = sf; if (decl.file !== undefined) { declFile = program.getSourceFile(decl.file) !; if (declFile === undefined) { throw new Error(`Unable to locate ${decl.file} for ${decl.type} ${decl.name}`); } } return getClass(declFile, decl.name); }); const binder = new R3TargetBinder(matcher); const boundTarget = binder.bind({template: nodes}); const clazz = new Reference(getClass(sf, 'TestComponent')); const sourceMapping: TemplateSourceMapping = { type: 'external', template, templateUrl, componentClass: clazz.node, // Use the class's name for error mappings. node: clazz.node.name, }; ctx.addTemplate(clazz, boundTarget, pipes, [], sourceMapping, templateFile); return ctx.calculateTemplateDiagnostics(program, host, options).diagnostics; } function prepareDeclarations( declarations: TestDeclaration[], resolveDeclaration: (decl: TestDeclaration) => ClassDeclaration<ts.ClassDeclaration>) { const matcher = new SelectorMatcher(); for (const decl of declarations) { if (decl.type !== 'directive') { continue; } const selector = CssSelector.parse(decl.selector); const meta: TypeCheckableDirectiveMeta = { name: decl.name, ref: new Reference(resolveDeclaration(decl)), exportAs: decl.exportAs || null, hasNgTemplateContextGuard: decl.hasNgTemplateContextGuard || false, inputs: decl.inputs || {}, isComponent: decl.isComponent || false, ngTemplateGuards: decl.ngTemplateGuards || [], outputs: decl.outputs || {}, queries: decl.queries || [], }; matcher.addSelectables(selector, meta); } const pipes = new Map<string, Reference<ClassDeclaration<ts.ClassDeclaration>>>(); for (const decl of declarations) { if (decl.type === 'pipe') { pipes.set(decl.pipeName, new Reference(resolveDeclaration(decl))); } } return {matcher, pipes}; } export function getClass(sf: ts.SourceFile, name: string): ClassDeclaration<ts.ClassDeclaration> { for (const stmt of sf.statements) { if (isNamedClassDeclaration(stmt) && stmt.name.text === name) { return stmt; } } throw new Error(`Class ${name} not found in file`); } class FakeEnvironment /* implements Environment */ { constructor(readonly config: TypeCheckingConfig) {} typeCtorFor(dir: TypeCheckableDirectiveMeta): ts.Expression { return ts.createPropertyAccess(ts.createIdentifier(dir.name), 'ngTypeCtor'); } pipeInst(ref: Reference<ClassDeclaration<ts.ClassDeclaration>>): ts.Expression { return ts.createParen(ts.createAsExpression(ts.createNull(), this.referenceType(ref))); } declareOutputHelper(): ts.Expression { return ts.createIdentifier('_outputHelper'); } reference(ref: Reference<ClassDeclaration<ts.ClassDeclaration>>): ts.Expression { return ref.node.name; } referenceType(ref: Reference<ClassDeclaration<ts.ClassDeclaration>>): ts.TypeNode { return ts.createTypeReferenceNode(ref.node.name, /* typeArguments */ undefined); } referenceExternalType(moduleName: string, name: string, typeParams?: Type[]): ts.TypeNode { const typeArgs: ts.TypeNode[] = []; if (typeParams !== undefined) { for (let i = 0; i < typeParams.length; i++) { typeArgs.push(ts.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword)); } } const ns = ts.createIdentifier(moduleName.replace('@angular/', '')); const qName = ts.createQualifiedName(ns, name); return ts.createTypeReferenceNode(qName, typeArgs.length > 0 ? typeArgs : undefined); } getPreludeStatements(): ts.Statement[] { return []; } static newFake(config: TypeCheckingConfig): Environment { return new FakeEnvironment(config) as Environment; } } export class NoopSchemaChecker implements DomSchemaChecker { get diagnostics(): ReadonlyArray<ts.Diagnostic> { return []; } checkElement(id: string, element: TmplAstElement, schemas: SchemaMetadata[]): void {} checkProperty( id: string, element: TmplAstElement, name: string, span: ParseSourceSpan, schemas: SchemaMetadata[]): void {} }
packages/compiler-cli/src/ngtsc/typecheck/test/test_utils.ts
1
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.002953498624265194, 0.0003107184311375022, 0.00016420830797869712, 0.00017168752674479038, 0.0004888057010248303 ]
{ "id": 3, "code_window": [ " addParseSpanInfo(expr, toAbsoluteSpan(ast.span, this.sourceSpan));\n", " return expr;\n", " } else if (binding instanceof TmplAstReference) {\n", " const target = this.tcb.boundTarget.getReferenceTarget(binding);\n", " if (target === null) {\n", " throw new Error(`Unbound reference? ${binding.name}`);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (!this.tcb.env.config.checkTypeOfReferences) {\n", " // References are pinned to 'any'.\n", " return NULL_AS_ANY;\n", " }\n", "\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts", "type": "add", "edit_start_line_idx": 956 }
// #docplaster import { Component } from '@angular/core'; import { trigger, transition, animate, style } from '@angular/animations'; @Component({ selector: 'app-insert-remove', animations: [ // #docregion enter-leave-trigger trigger('myInsertRemoveTrigger', [ transition(':enter', [ style({ opacity: 0 }), animate('5s', style({ opacity: 1 })), ]), transition(':leave', [ animate('5s', style({ opacity: 0 })) ]) ]), // #enddocregion enter-leave-trigger ], templateUrl: 'insert-remove.component.html', styleUrls: ['insert-remove.component.css'] }) export class InsertRemoveComponent { isShown = false; toggle() { this.isShown = !this.isShown; } }
aio/content/examples/animations/src/app/insert-remove.component.ts
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.00017414767353329808, 0.00017376738833263516, 0.0001735378464218229, 0.00017361663049086928, 2.708223689751321e-7 ]
{ "id": 3, "code_window": [ " addParseSpanInfo(expr, toAbsoluteSpan(ast.span, this.sourceSpan));\n", " return expr;\n", " } else if (binding instanceof TmplAstReference) {\n", " const target = this.tcb.boundTarget.getReferenceTarget(binding);\n", " if (target === null) {\n", " throw new Error(`Unbound reference? ${binding.name}`);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (!this.tcb.env.config.checkTypeOfReferences) {\n", " // References are pinned to 'any'.\n", " return NULL_AS_ANY;\n", " }\n", "\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts", "type": "add", "edit_start_line_idx": 956 }
{ "extends": "./tsconfig.app.json", "compilerOptions": { "outDir": "./out-tsc/app-server", "module": "commonjs", "types": ["node"] }, "files": [ "src/main.server.ts", "server.ts" ], "angularCompilerOptions": { "entryModule": "./src/app/app.server.module#AppServerModule" } }
aio/content/examples/universal/tsconfig.server.json
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.00017428872524760664, 0.0001741189626045525, 0.00017394919996149838, 0.0001741189626045525, 1.697626430541277e-7 ]
{ "id": 3, "code_window": [ " addParseSpanInfo(expr, toAbsoluteSpan(ast.span, this.sourceSpan));\n", " return expr;\n", " } else if (binding instanceof TmplAstReference) {\n", " const target = this.tcb.boundTarget.getReferenceTarget(binding);\n", " if (target === null) {\n", " throw new Error(`Unbound reference? ${binding.name}`);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " if (!this.tcb.env.config.checkTypeOfReferences) {\n", " // References are pinned to 'any'.\n", " return NULL_AS_ANY;\n", " }\n", "\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/src/type_check_block.ts", "type": "add", "edit_start_line_idx": 956 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {getSystemPath, normalize, virtualFs} from '@angular-devkit/core'; import {TempScopedNodeJsSyncHost} from '@angular-devkit/core/node/testing'; import {HostTree} from '@angular-devkit/schematics'; import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing'; import * as shx from 'shelljs'; describe('template variable assignment migration', () => { let runner: SchematicTestRunner; let host: TempScopedNodeJsSyncHost; let tree: UnitTestTree; let tmpDirPath: string; let previousWorkingDir: string; let warnOutput: string[]; beforeEach(() => { runner = new SchematicTestRunner('test', require.resolve('../migrations.json')); host = new TempScopedNodeJsSyncHost(); tree = new UnitTestTree(new HostTree(host)); writeFile('/tsconfig.json', JSON.stringify({ compilerOptions: { lib: ['es2015'], }, })); writeFile('/angular.json', JSON.stringify({ projects: {t: {architect: {build: {options: {tsConfig: './tsconfig.json'}}}}} })); warnOutput = []; runner.logger.subscribe(logEntry => { if (logEntry.level === 'warn') { warnOutput.push(logEntry.message); } }); previousWorkingDir = shx.pwd(); tmpDirPath = getSystemPath(host.root); // Switch into the temporary directory path. This allows us to run // the schematic against our custom unit test tree. shx.cd(tmpDirPath); }); afterEach(() => { shx.cd(previousWorkingDir); shx.rm('-r', tmpDirPath); }); function writeFile(filePath: string, contents: string) { host.sync.write(normalize(filePath), virtualFs.stringToFileBuffer(contents)); } function runMigration() { return runner.runSchematicAsync('migration-v8-template-local-variables', {}, tree).toPromise(); } it('should warn for two-way data binding variable assignment', async() => { writeFile('/index.ts', ` import {Component} from '@angular/core'; @Component({ template: '<cmp *ngFor="let optionName of options" [(opt)]="optionName"></cmp>', }) export class MyComp {} `); await runMigration(); expect(warnOutput.length).toBe(1); expect(warnOutput[0]).toMatch(/^⮑ {3}index.ts@5:69: Found assignment/); }); it('should warn for two-way data binding assigning to "as" variable', async() => { writeFile('/index.ts', ` import {Component} from '@angular/core'; @Component({ templateUrl: './tmpl.html', }) export class MyComp {} `); writeFile('/tmpl.html', ` <div *ngIf="somePartner() | async as partner"> <some-comp [(value)]="partner"></some-comp> </div> `); await runMigration(); expect(warnOutput.length).toBe(1); expect(warnOutput).toMatch(/^⮑ {3}tmpl.html@3:31: Found assignment/); }); it('should warn for bound event assignments to "as" variable', async() => { writeFile('/index.ts', ` import {Component} from '@angular/core'; @Component({ templateUrl: './sub_dir/tmpl.html', }) export class MyComp {} `); writeFile('/sub_dir/tmpl.html', ` <div *ngIf="true as visible"> <div (click)="visible=false">Hide</div> <div (click)="visible=true">Show</div> </div> `); await runMigration(); expect(warnOutput.length).toBe(2); expect(warnOutput[0]).toMatch(/^⮑ {3}sub_dir\/tmpl.html@3:25: Found assignment/); expect(warnOutput[1]).toMatch(/^⮑ {3}sub_dir\/tmpl.html@4:25: Found assignment/); }); it('should warn for bound event assignments to template "let" variables', async() => { writeFile('/index.ts', ` import {Component} from '@angular/core'; @Component({ templateUrl: './sub_dir/tmpl.html', }) export class MyComp {} `); writeFile('/sub_dir/tmpl.html', ` <ng-template let-visible="false"> <div (click)="visible=false">Hide</div> <div (click)="visible=true">Show</div> </ng-template> `); await runMigration(); expect(warnOutput.length).toBe(2); expect(warnOutput[0]).toMatch(/^⮑ {3}sub_dir\/tmpl.html@3:25: Found assignment/); expect(warnOutput[1]).toMatch(/^⮑ {3}sub_dir\/tmpl.html@4:25: Found assignment/); }); it('should not warn for bound event assignments to component property', async() => { writeFile('/index.ts', ` import {Component} from '@angular/core'; @Component({ templateUrl: './sub_dir/tmpl.html', }) export class MyComp {} `); writeFile('/sub_dir/tmpl.html', `<button (click)="myProp = true"></button>`); await runMigration(); expect(warnOutput.length).toBe(0); }); it('should not warn for bound event assignments to template variable object property', async() => { writeFile('/index.ts', ` import {Component} from '@angular/core'; @Component({ templateUrl: './sub_dir/tmpl.html', }) export class MyComp {} `); writeFile('/sub_dir/tmpl.html', ` <button *ngFor="let element of list" (click)="element.value = null">Reset</button> `); await runMigration(); expect(warnOutput.length).toBe(0); }); it('should not warn for property writes with template variable name but different receiver', async() => { writeFile('/index.ts', ` import {Component} from '@angular/core'; @Component({ templateUrl: './sub_dir/tmpl.html', }) export class MyComp { someProp = { element: 'someValue', }; } `); writeFile('/sub_dir/tmpl.html', ` <button *ngFor="let element of list" (click)="someProp.element = null"> Reset </button> `); await runMigration(); expect(warnOutput.length).toBe(0); }); it('should warn for template variable assignments in expression conditional', async() => { writeFile('/index.ts', ` import {Component} from '@angular/core'; @Component({ templateUrl: './sub_dir/tmpl.html', }) export class MyComp { otherVar = false; } `); writeFile('/sub_dir/tmpl.html', ` <ng-template let-tmplVar> <p (click)="enabled ? tmplVar = true : otherVar = true"></p> </ng-template> `); await runMigration(); expect(warnOutput.length).toBe(1); expect(warnOutput[0]).toMatch(/^⮑ {3}sub_dir\/tmpl.html@3:31: Found assignment/); }); it('should not warn for property writes with template variable name but different scope', async() => { writeFile('/index.ts', ` import {Component} from '@angular/core'; @Component({ templateUrl: './sub_dir/tmpl.html', }) export class MyComp { element = 'someValue'; } `); writeFile('/sub_dir/tmpl.html', ` <button *ngFor="let element of list">{{element}}</button> <button (click)="element = null"></button> `); await runMigration(); expect(warnOutput.length).toBe(0); }); it('should not throw an error if a detected template fails parsing', async() => { writeFile('/index.ts', ` import {Component} from '@angular/core'; @Component({ templateUrl: './sub_dir/tmpl.html', }) export class MyComp {} `); writeFile('/sub_dir/tmpl.html', `<x (click)="<invalid-syntax>"></x>`); await runMigration(); expect(warnOutput.length).toBe(0); }); it('should be able to report multiple templates within the same source file', async() => { writeFile('/index.ts', ` import {Component} from '@angular/core'; @Component({ template: '<ng-template let-one><a (sayHello)="one=true"></a></ng-template>', }) export class MyComp {} @Component({ template: '<ng-template let-two><b (greet)="two=true"></b></ng-template>', }) export class MyComp2 {} `); await runMigration(); expect(warnOutput.length).toBe(2); expect(warnOutput[0]).toMatch(/^⮑ {3}index.ts@5:56: Found assignment/); expect(warnOutput[1]).toMatch(/^⮑ {3}index.ts@10:53: Found assignment/); }); });
packages/core/schematics/test/template_var_assignment_migration_spec.ts
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.0001786969369277358, 0.00017301108164247125, 0.0001656510285101831, 0.00017327793466392905, 0.0000030280025384854525 ]
{ "id": 4, "code_window": [ " checkTypeOfOutputEvents: true,\n", " checkTypeOfAnimationEvents: true,\n", " checkTypeOfDomEvents: true,\n", " checkTypeOfPipes: true,\n", " strictSafeNavigationTypes: true,\n", "};\n", "\n", "// Remove 'ref' from TypeCheckableDirectiveMeta and add a 'selector' instead.\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " checkTypeOfReferences: true,\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/test/test_utils.ts", "type": "add", "edit_start_line_idx": 157 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {TypeCheckingConfig} from '../src/api'; import {ALL_ENABLED_CONFIG, TestDeclaration, TestDirective, tcb} from './test_utils'; describe('type check blocks', () => { it('should generate a basic block for a binding', () => { expect(tcb('{{hello}} {{world}}')).toContain('"" + (ctx).hello + (ctx).world;'); }); it('should generate literal map expressions', () => { const TEMPLATE = '{{ method({foo: a, bar: b}) }}'; expect(tcb(TEMPLATE)).toContain('(ctx).method({ "foo": (ctx).a, "bar": (ctx).b });'); }); it('should generate literal array expressions', () => { const TEMPLATE = '{{ method([a, b]) }}'; expect(tcb(TEMPLATE)).toContain('(ctx).method([(ctx).a, (ctx).b]);'); }); it('should handle non-null assertions', () => { const TEMPLATE = `{{a!}}`; expect(tcb(TEMPLATE)).toContain('(((ctx).a)!);'); }); it('should handle keyed property access', () => { const TEMPLATE = `{{a[b]}}`; expect(tcb(TEMPLATE)).toContain('((ctx).a)[(ctx).b];'); }); it('should handle attribute values for directive inputs', () => { const TEMPLATE = `<div dir inputA="value"></div>`; const DIRECTIVES: TestDeclaration[] = [{ type: 'directive', name: 'DirA', selector: '[dir]', inputs: {inputA: 'inputA'}, }]; expect(tcb(TEMPLATE, DIRECTIVES)).toContain('inputA: ("value")'); }); it('should handle empty bindings', () => { const TEMPLATE = `<div dir-a [inputA]=""></div>`; const DIRECTIVES: TestDeclaration[] = [{ type: 'directive', name: 'DirA', selector: '[dir-a]', inputs: {inputA: 'inputA'}, }]; expect(tcb(TEMPLATE, DIRECTIVES)).toContain('inputA: (undefined)'); }); it('should handle bindings without value', () => { const TEMPLATE = `<div dir-a [inputA]></div>`; const DIRECTIVES: TestDeclaration[] = [{ type: 'directive', name: 'DirA', selector: '[dir-a]', inputs: {inputA: 'inputA'}, }]; expect(tcb(TEMPLATE, DIRECTIVES)).toContain('inputA: (undefined)'); }); it('should handle implicit vars on ng-template', () => { const TEMPLATE = `<ng-template let-a></ng-template>`; expect(tcb(TEMPLATE)).toContain('var _t2 = _t1.$implicit;'); }); it('should handle implicit vars when using microsyntax', () => { const TEMPLATE = `<div *ngFor="let user of users"></div>`; expect(tcb(TEMPLATE)).toContain('var _t2 = _t1.$implicit;'); }); it('should handle missing property bindings', () => { const TEMPLATE = `<div dir [inputA]="foo"></div>`; const DIRECTIVES: TestDeclaration[] = [{ type: 'directive', name: 'Dir', selector: '[dir]', inputs: { fieldA: 'inputA', fieldB: 'inputB', }, }]; expect(tcb(TEMPLATE, DIRECTIVES)) .toContain('var _t2 = Dir.ngTypeCtor({ fieldA: ((ctx).foo), fieldB: (null as any) });'); }); it('should generate a forward element reference correctly', () => { const TEMPLATE = ` {{ i.value }} <input #i> `; expect(tcb(TEMPLATE)).toContain('var _t1 = document.createElement("input"); "" + (_t1).value;'); }); it('should generate a forward directive reference correctly', () => { const TEMPLATE = ` {{d.value}} <div dir #d="dir"></div> `; const DIRECTIVES: TestDeclaration[] = [{ type: 'directive', name: 'Dir', selector: '[dir]', exportAs: ['dir'], }]; expect(tcb(TEMPLATE, DIRECTIVES)) .toContain( 'var _t1 = Dir.ngTypeCtor({}); "" + (_t1).value; var _t2 = document.createElement("div");'); }); it('should handle style and class bindings specially', () => { const TEMPLATE = ` <div [style]="a" [class]="b"></div> `; const block = tcb(TEMPLATE); expect(block).toContain('(ctx).a; (ctx).b;'); // There should be no assignments to the class or style properties. expect(block).not.toContain('.class = '); expect(block).not.toContain('.style = '); }); it('should only apply property bindings to directives', () => { const TEMPLATE = ` <div dir [style.color]="'blue'" [class.strong]="false" [attr.enabled]="true"></div> `; const DIRECTIVES: TestDeclaration[] = [{ type: 'directive', name: 'Dir', selector: '[dir]', inputs: {'color': 'color', 'strong': 'strong', 'enabled': 'enabled'}, }]; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain( 'var _t2 = Dir.ngTypeCtor({ color: (null as any), strong: (null as any), enabled: (null as any) });'); expect(block).toContain('"blue"; false; true;'); }); it('should generate a circular directive reference correctly', () => { const TEMPLATE = ` <div dir #d="dir" [input]="d"></div> `; const DIRECTIVES: TestDirective[] = [{ type: 'directive', name: 'Dir', selector: '[dir]', exportAs: ['dir'], inputs: {input: 'input'}, }]; expect(tcb(TEMPLATE, DIRECTIVES)).toContain('var _t2 = Dir.ngTypeCtor({ input: (null!) });'); }); it('should generate circular references between two directives correctly', () => { const TEMPLATE = ` <div #a="dirA" dir-a [inputA]="b">A</div> <div #b="dirB" dir-b [inputB]="a">B</div> `; const DIRECTIVES: TestDirective[] = [ { type: 'directive', name: 'DirA', selector: '[dir-a]', exportAs: ['dirA'], inputs: {inputA: 'inputA'}, }, { type: 'directive', name: 'DirB', selector: '[dir-b]', exportAs: ['dirB'], inputs: {inputA: 'inputB'}, } ]; expect(tcb(TEMPLATE, DIRECTIVES)) .toContain( 'var _t3 = DirB.ngTypeCtor({ inputA: (null!) }); ' + 'var _t2 = DirA.ngTypeCtor({ inputA: (_t3) });'); }); it('should handle $any casts', () => { const TEMPLATE = `{{$any(a)}}`; const block = tcb(TEMPLATE); expect(block).toContain('((ctx).a as any);'); }); describe('experimental DOM checking via lib.dom.d.ts', () => { it('should translate unclaimed bindings to their property equivalent', () => { const TEMPLATE = `<label [for]="'test'"></label>`; const CONFIG = {...ALL_ENABLED_CONFIG, checkTypeOfDomBindings: true}; expect(tcb(TEMPLATE, /* declarations */ undefined, CONFIG)) .toContain('_t1.htmlFor = ("test");'); }); }); describe('template guards', () => { it('should emit invocation guards', () => { const DIRECTIVES: TestDeclaration[] = [{ type: 'directive', name: 'NgIf', selector: '[ngIf]', inputs: {'ngIf': 'ngIf'}, ngTemplateGuards: [{ inputName: 'ngIf', type: 'invocation', }] }]; const TEMPLATE = `<div *ngIf="person"></div>`; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('if (NgIf.ngTemplateGuard_ngIf(_t1, (ctx).person))'); }); it('should emit binding guards', () => { const DIRECTIVES: TestDeclaration[] = [{ type: 'directive', name: 'NgIf', selector: '[ngIf]', inputs: {'ngIf': 'ngIf'}, ngTemplateGuards: [{ inputName: 'ngIf', type: 'binding', }] }]; const TEMPLATE = `<div *ngIf="person !== null"></div>`; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('if (((ctx).person) !== (null))'); }); }); describe('outputs', () => { it('should emit subscribe calls for directive outputs', () => { const DIRECTIVES: TestDeclaration[] = [{ type: 'directive', name: 'Dir', selector: '[dir]', outputs: {'outputField': 'dirOutput'}, }]; const TEMPLATE = `<div dir (dirOutput)="foo($event)"></div>`; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain( '_outputHelper(_t2.outputField).subscribe($event => (ctx).foo($event));'); }); it('should emit a listener function with AnimationEvent for animation events', () => { const TEMPLATE = `<div (@animation.done)="foo($event)"></div>`; const block = tcb(TEMPLATE); expect(block).toContain('($event: animations.AnimationEvent) => (ctx).foo($event);'); }); it('should emit addEventListener calls for unclaimed outputs', () => { const TEMPLATE = `<div (event)="foo($event)"></div>`; const block = tcb(TEMPLATE); expect(block).toContain('_t1.addEventListener("event", $event => (ctx).foo($event));'); }); it('should allow to cast $event using $any', () => { const TEMPLATE = `<div (event)="foo($any($event))"></div>`; const block = tcb(TEMPLATE); expect(block).toContain( '_t1.addEventListener("event", $event => (ctx).foo(($event as any)));'); }); }); describe('config', () => { const DIRECTIVES: TestDeclaration[] = [{ type: 'directive', name: 'Dir', selector: '[dir]', exportAs: ['dir'], inputs: {'dirInput': 'dirInput'}, outputs: {'outputField': 'dirOutput'}, hasNgTemplateContextGuard: true, }]; const BASE_CONFIG: TypeCheckingConfig = { applyTemplateContextGuards: true, checkQueries: false, checkTemplateBodies: true, checkTypeOfInputBindings: true, strictNullInputBindings: true, checkTypeOfDomBindings: false, checkTypeOfOutputEvents: true, checkTypeOfAnimationEvents: true, checkTypeOfDomEvents: true, checkTypeOfPipes: true, strictSafeNavigationTypes: true, }; describe('config.applyTemplateContextGuards', () => { const TEMPLATE = `<div *dir></div>`; const GUARD_APPLIED = 'if (Dir.ngTemplateContextGuard('; it('should apply template context guards when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain(GUARD_APPLIED); }); it('should not apply template context guards when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, applyTemplateContextGuards: false}; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).not.toContain(GUARD_APPLIED); }); }); describe('config.checkTemplateBodies', () => { const TEMPLATE = `<ng-template>{{a}}</ng-template>`; it('should descend into template bodies when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('(ctx).a;'); }); it('should not descend into template bodies when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTemplateBodies: false}; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).not.toContain('(ctx).a;'); }); }); describe('config.strictNullInputBindings', () => { const TEMPLATE = `<div dir [dirInput]="a" [nonDirInput]="b"></div>`; it('should include null and undefined when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('Dir.ngTypeCtor({ dirInput: ((ctx).a) })'); expect(block).toContain('(ctx).b;'); }); it('should use the non-null assertion operator when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, strictNullInputBindings: false}; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).toContain('Dir.ngTypeCtor({ dirInput: ((ctx).a!) })'); expect(block).toContain('(ctx).b!;'); }); }); describe('config.checkTypeOfBindings', () => { const TEMPLATE = `<div dir [dirInput]="a" [nonDirInput]="b"></div>`; it('should check types of bindings when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('Dir.ngTypeCtor({ dirInput: ((ctx).a) })'); expect(block).toContain('(ctx).b;'); }); it('should not check types of bindings when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfInputBindings: false}; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).toContain('Dir.ngTypeCtor({ dirInput: (((ctx).a as any)) })'); expect(block).toContain('((ctx).b as any);'); }); }); describe('config.checkTypeOfOutputEvents', () => { const TEMPLATE = `<div dir (dirOutput)="foo($event)" (nonDirOutput)="foo($event)"></div>`; it('should check types of directive outputs when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain( '_outputHelper(_t2.outputField).subscribe($event => (ctx).foo($event));'); expect(block).toContain( '_t1.addEventListener("nonDirOutput", $event => (ctx).foo($event));'); }); it('should not check types of directive outputs when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfOutputEvents: false}; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).toContain('($event: any) => (ctx).foo($event);'); // Note that DOM events are still checked, that is controlled by `checkTypeOfDomEvents` expect(block).toContain( '_t1.addEventListener("nonDirOutput", $event => (ctx).foo($event));'); }); }); describe('config.checkTypeOfAnimationEvents', () => { const TEMPLATE = `<div (@animation.done)="foo($event)"></div>`; it('should check types of animation events when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('($event: animations.AnimationEvent) => (ctx).foo($event);'); }); it('should not check types of animation events when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfAnimationEvents: false}; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).toContain('($event: any) => (ctx).foo($event);'); }); }); describe('config.checkTypeOfDomEvents', () => { const TEMPLATE = `<div dir (dirOutput)="foo($event)" (nonDirOutput)="foo($event)"></div>`; it('should check types of DOM events when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain( '_outputHelper(_t2.outputField).subscribe($event => (ctx).foo($event));'); expect(block).toContain( '_t1.addEventListener("nonDirOutput", $event => (ctx).foo($event));'); }); it('should not check types of DOM events when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfDomEvents: false}; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); // Note that directive outputs are still checked, that is controlled by // `checkTypeOfOutputEvents` expect(block).toContain( '_outputHelper(_t2.outputField).subscribe($event => (ctx).foo($event));'); expect(block).toContain('($event: any) => (ctx).foo($event);'); }); }); describe('config.checkTypeOfPipes', () => { const TEMPLATE = `{{a | test:b:c}}`; const PIPES: TestDeclaration[] = [{ type: 'pipe', name: 'TestPipe', pipeName: 'test', }]; it('should check types of pipes when enabled', () => { const block = tcb(TEMPLATE, PIPES); expect(block).toContain('(null as TestPipe).transform((ctx).a, (ctx).b, (ctx).c);'); }); it('should not check types of pipes when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfPipes: false}; const block = tcb(TEMPLATE, PIPES, DISABLED_CONFIG); expect(block).toContain('(null as any).transform((ctx).a, (ctx).b, (ctx).c);'); }); }); describe('config.strictSafeNavigationTypes', () => { const TEMPLATE = `{{a?.b}} {{a?.method()}}`; it('should use undefined for safe navigation operations when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('(((ctx).a) != null ? ((ctx).a)!.method() : undefined)'); expect(block).toContain('(((ctx).a) != null ? ((ctx).a)!.b : undefined)'); }); it('should use an \'any\' type for safe navigation operations when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, strictSafeNavigationTypes: false}; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).toContain('(((ctx).a) != null ? ((ctx).a)!.method() : null as any)'); expect(block).toContain('(((ctx).a) != null ? ((ctx).a)!.b : null as any)'); }); }); }); });
packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts
1
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.005339635536074638, 0.0004464441444724798, 0.00016525441606063396, 0.0001726703194435686, 0.0008291820413433015 ]
{ "id": 4, "code_window": [ " checkTypeOfOutputEvents: true,\n", " checkTypeOfAnimationEvents: true,\n", " checkTypeOfDomEvents: true,\n", " checkTypeOfPipes: true,\n", " strictSafeNavigationTypes: true,\n", "};\n", "\n", "// Remove 'ref' from TypeCheckableDirectiveMeta and add a 'selector' instead.\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " checkTypeOfReferences: true,\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/test/test_utils.ts", "type": "add", "edit_start_line_idx": 157 }
import { Component, NgModule, ViewChild } from '@angular/core'; import { Title, Meta } from '@angular/platform-browser'; import { Observable } from 'rxjs'; import { DocumentContents } from 'app/documents/document.service'; import { DocViewerComponent } from 'app/layout/doc-viewer/doc-viewer.component'; import { Logger } from 'app/shared/logger.service'; import { TocService } from 'app/shared/toc.service'; import { MockLogger } from 'testing/logger.service'; import { ElementsLoader } from 'app/custom-elements/elements-loader'; //////////////////////////////////////////////////////////////////////////////////////////////////// /// `TestDocViewerComponent` (for exposing internal `DocViewerComponent` methods as public). /// /// Only used for type-casting; the actual implementation is irrelevant. /// //////////////////////////////////////////////////////////////////////////////////////////////////// export class TestDocViewerComponent extends DocViewerComponent { currViewContainer: HTMLElement; nextViewContainer: HTMLElement; // Only used for type-casting; the actual implementation is irrelevant. prepareTitleAndToc(_targetElem: HTMLElement, _docId: string): () => void { return null as any; } // Only used for type-casting; the actual implementation is irrelevant. render(_doc: DocumentContents): Observable<void> { return null as any; } // Only used for type-casting; the actual implementation is irrelevant. swapViews(_onInsertedCb?: () => void): Observable<void> { return null as any; } } //////////////////////////////////////////////////////////////////////////////////////////////////// /// `TestModule` and `TestParentComponent`. /// //////////////////////////////////////////////////////////////////////////////////////////////////// // Test parent component. @Component({ selector: 'aio-test', template: '<aio-doc-viewer [doc]="currentDoc">Test Component</aio-doc-viewer>', }) export class TestParentComponent { currentDoc?: DocumentContents|null; @ViewChild(DocViewerComponent, {static: true}) docViewer: DocViewerComponent; } // Mock services. export class MockTitle { setTitle = jasmine.createSpy('Title#reset'); } export class MockMeta { addTag = jasmine.createSpy('Meta#addTag'); removeTag = jasmine.createSpy('Meta#removeTag'); } export class MockTocService { genToc = jasmine.createSpy('TocService#genToc'); reset = jasmine.createSpy('TocService#reset'); } export class MockElementsLoader { loadContainedCustomElements = jasmine.createSpy('MockElementsLoader#loadContainedCustomElements'); } @NgModule({ declarations: [ DocViewerComponent, TestParentComponent, ], providers: [ { provide: Logger, useClass: MockLogger }, { provide: Title, useClass: MockTitle }, { provide: Meta, useClass: MockMeta }, { provide: TocService, useClass: MockTocService }, { provide: ElementsLoader, useClass: MockElementsLoader }, ], }) export class TestModule { } //////////////////////////////////////////////////////////////////////////////////////////////////// /// An observable with spies to test subscribing/unsubscribing. /// //////////////////////////////////////////////////////////////////////////////////////////////////// export class ObservableWithSubscriptionSpies<T = void> extends Observable<T> { unsubscribeSpies: jasmine.Spy[] = []; subscribeSpy = spyOn(this as Observable<T>, 'subscribe').and.callFake((...args: any[]) => { const subscription = super.subscribe(...args); const unsubscribeSpy = spyOn(subscription, 'unsubscribe').and.callThrough(); this.unsubscribeSpies.push(unsubscribeSpy); return subscription; }); constructor(subscriber = () => undefined) { super(subscriber); } }
aio/src/testing/doc-viewer-utils.ts
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.0001756082201609388, 0.00017052944167517126, 0.00016544897516723722, 0.0001700813154457137, 0.0000031246395337802824 ]
{ "id": 4, "code_window": [ " checkTypeOfOutputEvents: true,\n", " checkTypeOfAnimationEvents: true,\n", " checkTypeOfDomEvents: true,\n", " checkTypeOfPipes: true,\n", " strictSafeNavigationTypes: true,\n", "};\n", "\n", "// Remove 'ref' from TypeCheckableDirectiveMeta and add a 'selector' instead.\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " checkTypeOfReferences: true,\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/test/test_utils.ts", "type": "add", "edit_start_line_idx": 157 }
import { Component } from '@angular/core'; // #docregion example @Component({ selector: 'toh-hero-button', templateUrl: './hero-button.component.html' }) export class HeroButtonComponent {} // #enddocregion example
aio/content/examples/styleguide/src/05-03/app/heroes/shared/hero-button/hero-button.component.ts
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.00017409620340913534, 0.00017409620340913534, 0.00017409620340913534, 0.00017409620340913534, 0 ]
{ "id": 4, "code_window": [ " checkTypeOfOutputEvents: true,\n", " checkTypeOfAnimationEvents: true,\n", " checkTypeOfDomEvents: true,\n", " checkTypeOfPipes: true,\n", " strictSafeNavigationTypes: true,\n", "};\n", "\n", "// Remove 'ref' from TypeCheckableDirectiveMeta and add a 'selector' instead.\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " checkTypeOfReferences: true,\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/test/test_utils.ts", "type": "add", "edit_start_line_idx": 157 }
import { FirebaseRedirect } from './FirebaseRedirect'; describe('FirebaseRedirect', () => { describe('replace', () => { it('should return undefined if the redirect does not match the url', () => { const redirect = new FirebaseRedirect('/a/b/c', '/x/y/z'); expect(redirect.replace('/1/2/3')).toBe(undefined); }); it('should return the destination if there is a match', () => { const redirect = new FirebaseRedirect('/a/b/c', '/x/y/z'); expect(redirect.replace('/a/b/c')).toBe('/x/y/z'); }); it('should inject name params into the destination', () => { const redirect = new FirebaseRedirect('/api/:package/:api-*', '<:package><:api>'); expect(redirect.replace('/api/common/NgClass-directive')).toEqual('<common><NgClass>'); }); it('should inject rest params into the destination', () => { const redirect = new FirebaseRedirect('/a/:rest*', '/x/:rest*/y'); expect(redirect.replace('/a/b/c')).toEqual('/x/b/c/y'); }); it('should inject both named and rest parameters into the destination', () => { const redirect = new FirebaseRedirect('/:a/:rest*', '/x/:a/y/:rest*/z'); expect(redirect.replace('/a/b/c')).toEqual('/x/a/y/b/c/z'); }); }); });
aio/tools/firebase-test-utils/FirebaseRedirect.spec.ts
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.00017507304437458515, 0.00017435495101381093, 0.00017405604012310505, 0.00017414535977877676, 4.186127000593842e-7 ]
{ "id": 5, "code_window": [ " strictNullInputBindings: true,\n", " checkTypeOfDomBindings: false,\n", " checkTypeOfOutputEvents: true,\n", " checkTypeOfAnimationEvents: true,\n", " checkTypeOfDomEvents: true,\n", " checkTypeOfPipes: true,\n", " checkTemplateBodies: true,\n", " strictSafeNavigationTypes: true,\n", " };\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " checkTypeOfReferences: true,\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/test/test_utils.ts", "type": "add", "edit_start_line_idx": 200 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {CssSelector, ParseSourceFile, ParseSourceSpan, R3TargetBinder, SchemaMetadata, SelectorMatcher, TmplAstElement, Type, parseTemplate} from '@angular/compiler'; import * as ts from 'typescript'; import {AbsoluteFsPath, LogicalFileSystem, absoluteFrom} from '../../file_system'; import {TestFile} from '../../file_system/testing'; import {AbsoluteModuleStrategy, LocalIdentifierStrategy, LogicalProjectStrategy, Reference, ReferenceEmitter} from '../../imports'; import {ClassDeclaration, TypeScriptReflectionHost, isNamedClassDeclaration} from '../../reflection'; import {makeProgram} from '../../testing'; import {getRootDirs} from '../../util/src/typescript'; import {TemplateSourceMapping, TypeCheckBlockMetadata, TypeCheckableDirectiveMeta, TypeCheckingConfig} from '../src/api'; import {TypeCheckContext} from '../src/context'; import {DomSchemaChecker} from '../src/dom'; import {Environment} from '../src/environment'; import {generateTypeCheckBlock} from '../src/type_check_block'; export function typescriptLibDts(): TestFile { return { name: absoluteFrom('/lib.d.ts'), contents: ` type Partial<T> = { [P in keyof T]?: T[P]; }; type Pick<T, K extends keyof T> = { [P in K]: T[P]; }; type NonNullable<T> = T extends null | undefined ? never : T; // The following native type declarations are required for proper type inference declare interface Function { call(...args: any[]): any; } declare interface Array<T> { length: number; } declare interface String { length: number; } declare interface Event { preventDefault(): void; } declare interface MouseEvent extends Event { readonly x: number; readonly y: number; } declare interface HTMLElementEventMap { "click": MouseEvent; } declare interface HTMLElement { addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any): void; addEventListener(type: string, listener: (evt: Event): void;): void; } declare interface HTMLDivElement extends HTMLElement {} declare interface HTMLImageElement extends HTMLElement { src: string; alt: string; width: number; height: number; } declare interface HTMLQuoteElement extends HTMLElement { cite: string; } declare interface HTMLElementTagNameMap { "blockquote": HTMLQuoteElement; "div": HTMLDivElement; "img": HTMLImageElement; } declare interface Document { createElement<K extends keyof HTMLElementTagNameMap>(tagName: K): HTMLElementTagNameMap[K]; createElement(tagName: string): HTMLElement; } declare const document: Document; ` }; } export function angularCoreDts(): TestFile { return { name: absoluteFrom('/node_modules/@angular/core/index.d.ts'), contents: ` export declare class TemplateRef<C> { abstract readonly elementRef: unknown; abstract createEmbeddedView(context: C): unknown; } export declare class EventEmitter<T> { subscribe(generatorOrNext?: any, error?: any, complete?: any): unknown; } ` }; } export function angularAnimationsDts(): TestFile { return { name: absoluteFrom('/node_modules/@angular/animations/index.d.ts'), contents: ` export declare class AnimationEvent { element: any; } ` }; } export function ngForDeclaration(): TestDeclaration { return { type: 'directive', file: absoluteFrom('/ngfor.d.ts'), selector: '[ngForOf]', name: 'NgForOf', inputs: {ngForOf: 'ngForOf'}, hasNgTemplateContextGuard: true, }; } export function ngForDts(): TestFile { return { name: absoluteFrom('/ngfor.d.ts'), contents: ` export declare class NgForOf<T> { ngForOf: T[]; ngForTrackBy: TrackByFunction<T>; static ngTemplateContextGuard<T>(dir: NgForOf<T>, ctx: any): ctx is NgForOfContext<T>; } export interface TrackByFunction<T> { (index: number, item: T): any; } export declare class NgForOfContext<T> { $implicit: T; index: number; count: number; readonly odd: boolean; readonly even: boolean; readonly first: boolean; readonly last: boolean; }`, }; } export const ALL_ENABLED_CONFIG: TypeCheckingConfig = { applyTemplateContextGuards: true, checkQueries: false, checkTemplateBodies: true, checkTypeOfInputBindings: true, strictNullInputBindings: true, // Feature is still in development. // TODO(alxhub): enable when DOM checking via lib.dom.d.ts is further along. checkTypeOfDomBindings: false, checkTypeOfOutputEvents: true, checkTypeOfAnimationEvents: true, checkTypeOfDomEvents: true, checkTypeOfPipes: true, strictSafeNavigationTypes: true, }; // Remove 'ref' from TypeCheckableDirectiveMeta and add a 'selector' instead. export type TestDirective = Partial<Pick<TypeCheckableDirectiveMeta, Exclude<keyof TypeCheckableDirectiveMeta, 'ref'>>>& {selector: string, name: string, file?: AbsoluteFsPath, type: 'directive'}; export type TestPipe = { name: string, file?: AbsoluteFsPath, pipeName: string, type: 'pipe', }; export type TestDeclaration = TestDirective | TestPipe; export function tcb( template: string, declarations: TestDeclaration[] = [], config?: TypeCheckingConfig, options?: {emitSpans?: boolean}): string { const classes = ['Test', ...declarations.map(decl => decl.name)]; const code = classes.map(name => `class ${name}<T extends string> {}`).join('\n'); const sf = ts.createSourceFile('synthetic.ts', code, ts.ScriptTarget.Latest, true); const clazz = getClass(sf, 'Test'); const templateUrl = 'synthetic.html'; const {nodes} = parseTemplate(template, templateUrl); const {matcher, pipes} = prepareDeclarations(declarations, decl => getClass(sf, decl.name)); const binder = new R3TargetBinder(matcher); const boundTarget = binder.bind({template: nodes}); const meta: TypeCheckBlockMetadata = {boundTarget, pipes, id: 'tcb', schemas: []}; config = config || { applyTemplateContextGuards: true, checkQueries: false, checkTypeOfInputBindings: true, strictNullInputBindings: true, checkTypeOfDomBindings: false, checkTypeOfOutputEvents: true, checkTypeOfAnimationEvents: true, checkTypeOfDomEvents: true, checkTypeOfPipes: true, checkTemplateBodies: true, strictSafeNavigationTypes: true, }; options = options || { emitSpans: false, }; const tcb = generateTypeCheckBlock( FakeEnvironment.newFake(config), new Reference(clazz), ts.createIdentifier('Test_TCB'), meta, new NoopSchemaChecker()); const removeComments = !options.emitSpans; const res = ts.createPrinter({removeComments}).printNode(ts.EmitHint.Unspecified, tcb, sf); return res.replace(/\s+/g, ' '); } export function typecheck( template: string, source: string, declarations: TestDeclaration[] = [], additionalSources: {name: AbsoluteFsPath; contents: string}[] = []): ts.Diagnostic[] { const typeCheckFilePath = absoluteFrom('/_typecheck_.ts'); const files = [ typescriptLibDts(), angularCoreDts(), angularAnimationsDts(), // Add the typecheck file to the program, as the typecheck program is created with the // assumption that the typecheck file was already a root file in the original program. {name: typeCheckFilePath, contents: 'export const TYPECHECK = true;'}, {name: absoluteFrom('/main.ts'), contents: source}, ...additionalSources, ]; const {program, host, options} = makeProgram(files, {strictNullChecks: true, noImplicitAny: true}, undefined, false); const sf = program.getSourceFile(absoluteFrom('/main.ts')) !; const checker = program.getTypeChecker(); const logicalFs = new LogicalFileSystem(getRootDirs(host, options)); const reflectionHost = new TypeScriptReflectionHost(checker); const emitter = new ReferenceEmitter([ new LocalIdentifierStrategy(), new AbsoluteModuleStrategy( program, checker, options, host, new TypeScriptReflectionHost(checker)), new LogicalProjectStrategy(reflectionHost, logicalFs), ]); const ctx = new TypeCheckContext(ALL_ENABLED_CONFIG, emitter, typeCheckFilePath); const templateUrl = 'synthetic.html'; const templateFile = new ParseSourceFile(template, templateUrl); const {nodes, errors} = parseTemplate(template, templateUrl); if (errors !== undefined) { throw new Error('Template parse errors: \n' + errors.join('\n')); } const {matcher, pipes} = prepareDeclarations(declarations, decl => { let declFile = sf; if (decl.file !== undefined) { declFile = program.getSourceFile(decl.file) !; if (declFile === undefined) { throw new Error(`Unable to locate ${decl.file} for ${decl.type} ${decl.name}`); } } return getClass(declFile, decl.name); }); const binder = new R3TargetBinder(matcher); const boundTarget = binder.bind({template: nodes}); const clazz = new Reference(getClass(sf, 'TestComponent')); const sourceMapping: TemplateSourceMapping = { type: 'external', template, templateUrl, componentClass: clazz.node, // Use the class's name for error mappings. node: clazz.node.name, }; ctx.addTemplate(clazz, boundTarget, pipes, [], sourceMapping, templateFile); return ctx.calculateTemplateDiagnostics(program, host, options).diagnostics; } function prepareDeclarations( declarations: TestDeclaration[], resolveDeclaration: (decl: TestDeclaration) => ClassDeclaration<ts.ClassDeclaration>) { const matcher = new SelectorMatcher(); for (const decl of declarations) { if (decl.type !== 'directive') { continue; } const selector = CssSelector.parse(decl.selector); const meta: TypeCheckableDirectiveMeta = { name: decl.name, ref: new Reference(resolveDeclaration(decl)), exportAs: decl.exportAs || null, hasNgTemplateContextGuard: decl.hasNgTemplateContextGuard || false, inputs: decl.inputs || {}, isComponent: decl.isComponent || false, ngTemplateGuards: decl.ngTemplateGuards || [], outputs: decl.outputs || {}, queries: decl.queries || [], }; matcher.addSelectables(selector, meta); } const pipes = new Map<string, Reference<ClassDeclaration<ts.ClassDeclaration>>>(); for (const decl of declarations) { if (decl.type === 'pipe') { pipes.set(decl.pipeName, new Reference(resolveDeclaration(decl))); } } return {matcher, pipes}; } export function getClass(sf: ts.SourceFile, name: string): ClassDeclaration<ts.ClassDeclaration> { for (const stmt of sf.statements) { if (isNamedClassDeclaration(stmt) && stmt.name.text === name) { return stmt; } } throw new Error(`Class ${name} not found in file`); } class FakeEnvironment /* implements Environment */ { constructor(readonly config: TypeCheckingConfig) {} typeCtorFor(dir: TypeCheckableDirectiveMeta): ts.Expression { return ts.createPropertyAccess(ts.createIdentifier(dir.name), 'ngTypeCtor'); } pipeInst(ref: Reference<ClassDeclaration<ts.ClassDeclaration>>): ts.Expression { return ts.createParen(ts.createAsExpression(ts.createNull(), this.referenceType(ref))); } declareOutputHelper(): ts.Expression { return ts.createIdentifier('_outputHelper'); } reference(ref: Reference<ClassDeclaration<ts.ClassDeclaration>>): ts.Expression { return ref.node.name; } referenceType(ref: Reference<ClassDeclaration<ts.ClassDeclaration>>): ts.TypeNode { return ts.createTypeReferenceNode(ref.node.name, /* typeArguments */ undefined); } referenceExternalType(moduleName: string, name: string, typeParams?: Type[]): ts.TypeNode { const typeArgs: ts.TypeNode[] = []; if (typeParams !== undefined) { for (let i = 0; i < typeParams.length; i++) { typeArgs.push(ts.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword)); } } const ns = ts.createIdentifier(moduleName.replace('@angular/', '')); const qName = ts.createQualifiedName(ns, name); return ts.createTypeReferenceNode(qName, typeArgs.length > 0 ? typeArgs : undefined); } getPreludeStatements(): ts.Statement[] { return []; } static newFake(config: TypeCheckingConfig): Environment { return new FakeEnvironment(config) as Environment; } } export class NoopSchemaChecker implements DomSchemaChecker { get diagnostics(): ReadonlyArray<ts.Diagnostic> { return []; } checkElement(id: string, element: TmplAstElement, schemas: SchemaMetadata[]): void {} checkProperty( id: string, element: TmplAstElement, name: string, span: ParseSourceSpan, schemas: SchemaMetadata[]): void {} }
packages/compiler-cli/src/ngtsc/typecheck/test/test_utils.ts
1
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.09442025423049927, 0.004978541284799576, 0.00016421974578406662, 0.0001724899047985673, 0.019435890018939972 ]
{ "id": 5, "code_window": [ " strictNullInputBindings: true,\n", " checkTypeOfDomBindings: false,\n", " checkTypeOfOutputEvents: true,\n", " checkTypeOfAnimationEvents: true,\n", " checkTypeOfDomEvents: true,\n", " checkTypeOfPipes: true,\n", " checkTemplateBodies: true,\n", " strictSafeNavigationTypes: true,\n", " };\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " checkTypeOfReferences: true,\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/test/test_utils.ts", "type": "add", "edit_start_line_idx": 200 }
.filetree { background: $white; border: 4px solid $lightgray; border-radius: 4px; margin: 0 0 24px 0; padding: 16px 32px; .file { display: block; font-family: $main-font; @include letter-spacing(0.3); @include line-height(32); color: $darkgray; } .children { padding-left: 24px; position: relative; overflow: hidden; .file { position: relative; &:before { content: ''; left: -18px; bottom: 16px; width: 16px; height: 9999px; position: absolute; border-width: 0 0 1px 1px; border-style: solid; border-color: $lightgray; border-radius: 0 0 0 3px; } } } }
aio/src/styles/2-modules/_filetree.scss
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.0001776753197191283, 0.00017607085464987904, 0.00017398320778738707, 0.00017631244554650038, 0.0000013691842468688264 ]
{ "id": 5, "code_window": [ " strictNullInputBindings: true,\n", " checkTypeOfDomBindings: false,\n", " checkTypeOfOutputEvents: true,\n", " checkTypeOfAnimationEvents: true,\n", " checkTypeOfDomEvents: true,\n", " checkTypeOfPipes: true,\n", " checkTemplateBodies: true,\n", " strictSafeNavigationTypes: true,\n", " };\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " checkTypeOfReferences: true,\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/test/test_utils.ts", "type": "add", "edit_start_line_idx": 200 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as ts from 'typescript'; import {createLanguageService} from '../src/language_service'; import {LanguageService} from '../src/types'; import {TypeScriptServiceHost} from '../src/typescript_host'; import {MockTypescriptHost} from './test_utils'; describe('references', () => { const mockHost = new MockTypescriptHost(['/app/main.ts']); const service = ts.createLanguageService(mockHost); const ngHost = new TypeScriptServiceHost(mockHost, service); const ngService = createLanguageService(ngHost); beforeEach(() => { mockHost.reset(); }); it('should be able to get template references', () => { expect(() => ngService.getTemplateReferences()).not.toThrow(); }); it('should be able to determine that test.ng is a template reference', () => { expect(ngService.getTemplateReferences()).toContain('/app/test.ng'); }); it('should be able to get template references for an invalid project', () => { const moduleCode = ` import {NgModule} from '@angular/core'; import {NewClass} from './test.component'; @NgModule({declarations: [NewClass]}) export class TestModule {}`; const classCode = ` export class NewClass {} @Component({}) export class SomeComponent {} `; mockHost.addScript('/app/test.module.ts', moduleCode); mockHost.addScript('/app/test.component.ts', classCode); expect(() => { ngService.getTemplateReferences(); }).not.toThrow(); }); });
packages/language-service/test/template_references_spec.ts
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.00017625321925152093, 0.00017204080359078944, 0.0001671972859185189, 0.0001738923165248707, 0.0000038499861148011405 ]
{ "id": 5, "code_window": [ " strictNullInputBindings: true,\n", " checkTypeOfDomBindings: false,\n", " checkTypeOfOutputEvents: true,\n", " checkTypeOfAnimationEvents: true,\n", " checkTypeOfDomEvents: true,\n", " checkTypeOfPipes: true,\n", " checkTemplateBodies: true,\n", " strictSafeNavigationTypes: true,\n", " };\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " checkTypeOfReferences: true,\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/test/test_utils.ts", "type": "add", "edit_start_line_idx": 200 }
const fs = require('fs'); const path = require('path'); const angularRoot = path.resolve('./node_modules/@angular'); const angularModules = fs.readdirSync(angularRoot).map(function (name) { const content = fs.readFileSync(path.join(angularRoot, name, 'package.json'), 'utf-8').toString(); return JSON.parse(content); }).reduce(function (acc, packageJson) { acc[packageJson.name] = packageJson; return acc; }, Object.create(null)); var error = false; Object.keys(angularModules).forEach(function (name) { packageJson = angularModules[name]; const ngUpdate = packageJson['ng-update']; if (!ngUpdate) { console.error('Package ' + JSON.stringify(name) + ' does not have an "ng-update" key.'); error = true; return; } const packageGroup = ngUpdate['packageGroup']; if (!packageGroup) { console.error('Package ' + JSON.stringify(name) + ' does not have a "packageGroup" key.'); error = true; return; } // Verify that every packageGroup is represented in the list of modules. Object.keys(angularModules).forEach(function (groupEntry) { if (packageGroup.indexOf(groupEntry) == -1) { console.error('Package ' + JSON.stringify(name) + ' is missing ' + JSON.stringify(groupEntry) + ' as a packageGroup entry.'); error = true; return; } }); }); process.exit(error ? 1 : 0);
integration/ng_update/check.js
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.00017629876674618572, 0.00017442657554056495, 0.00017127372848335654, 0.00017459561058785766, 0.0000017087191963582882 ]
{ "id": 6, "code_window": [ " strictNullInputBindings: true,\n", " checkTypeOfDomBindings: false,\n", " checkTypeOfOutputEvents: true,\n", " checkTypeOfAnimationEvents: true,\n", " checkTypeOfDomEvents: true,\n", " checkTypeOfPipes: true,\n", " strictSafeNavigationTypes: true,\n", " };\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " checkTypeOfReferences: true,\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts", "type": "add", "edit_start_line_idx": 293 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {TypeCheckingConfig} from '../src/api'; import {ALL_ENABLED_CONFIG, TestDeclaration, TestDirective, tcb} from './test_utils'; describe('type check blocks', () => { it('should generate a basic block for a binding', () => { expect(tcb('{{hello}} {{world}}')).toContain('"" + (ctx).hello + (ctx).world;'); }); it('should generate literal map expressions', () => { const TEMPLATE = '{{ method({foo: a, bar: b}) }}'; expect(tcb(TEMPLATE)).toContain('(ctx).method({ "foo": (ctx).a, "bar": (ctx).b });'); }); it('should generate literal array expressions', () => { const TEMPLATE = '{{ method([a, b]) }}'; expect(tcb(TEMPLATE)).toContain('(ctx).method([(ctx).a, (ctx).b]);'); }); it('should handle non-null assertions', () => { const TEMPLATE = `{{a!}}`; expect(tcb(TEMPLATE)).toContain('(((ctx).a)!);'); }); it('should handle keyed property access', () => { const TEMPLATE = `{{a[b]}}`; expect(tcb(TEMPLATE)).toContain('((ctx).a)[(ctx).b];'); }); it('should handle attribute values for directive inputs', () => { const TEMPLATE = `<div dir inputA="value"></div>`; const DIRECTIVES: TestDeclaration[] = [{ type: 'directive', name: 'DirA', selector: '[dir]', inputs: {inputA: 'inputA'}, }]; expect(tcb(TEMPLATE, DIRECTIVES)).toContain('inputA: ("value")'); }); it('should handle empty bindings', () => { const TEMPLATE = `<div dir-a [inputA]=""></div>`; const DIRECTIVES: TestDeclaration[] = [{ type: 'directive', name: 'DirA', selector: '[dir-a]', inputs: {inputA: 'inputA'}, }]; expect(tcb(TEMPLATE, DIRECTIVES)).toContain('inputA: (undefined)'); }); it('should handle bindings without value', () => { const TEMPLATE = `<div dir-a [inputA]></div>`; const DIRECTIVES: TestDeclaration[] = [{ type: 'directive', name: 'DirA', selector: '[dir-a]', inputs: {inputA: 'inputA'}, }]; expect(tcb(TEMPLATE, DIRECTIVES)).toContain('inputA: (undefined)'); }); it('should handle implicit vars on ng-template', () => { const TEMPLATE = `<ng-template let-a></ng-template>`; expect(tcb(TEMPLATE)).toContain('var _t2 = _t1.$implicit;'); }); it('should handle implicit vars when using microsyntax', () => { const TEMPLATE = `<div *ngFor="let user of users"></div>`; expect(tcb(TEMPLATE)).toContain('var _t2 = _t1.$implicit;'); }); it('should handle missing property bindings', () => { const TEMPLATE = `<div dir [inputA]="foo"></div>`; const DIRECTIVES: TestDeclaration[] = [{ type: 'directive', name: 'Dir', selector: '[dir]', inputs: { fieldA: 'inputA', fieldB: 'inputB', }, }]; expect(tcb(TEMPLATE, DIRECTIVES)) .toContain('var _t2 = Dir.ngTypeCtor({ fieldA: ((ctx).foo), fieldB: (null as any) });'); }); it('should generate a forward element reference correctly', () => { const TEMPLATE = ` {{ i.value }} <input #i> `; expect(tcb(TEMPLATE)).toContain('var _t1 = document.createElement("input"); "" + (_t1).value;'); }); it('should generate a forward directive reference correctly', () => { const TEMPLATE = ` {{d.value}} <div dir #d="dir"></div> `; const DIRECTIVES: TestDeclaration[] = [{ type: 'directive', name: 'Dir', selector: '[dir]', exportAs: ['dir'], }]; expect(tcb(TEMPLATE, DIRECTIVES)) .toContain( 'var _t1 = Dir.ngTypeCtor({}); "" + (_t1).value; var _t2 = document.createElement("div");'); }); it('should handle style and class bindings specially', () => { const TEMPLATE = ` <div [style]="a" [class]="b"></div> `; const block = tcb(TEMPLATE); expect(block).toContain('(ctx).a; (ctx).b;'); // There should be no assignments to the class or style properties. expect(block).not.toContain('.class = '); expect(block).not.toContain('.style = '); }); it('should only apply property bindings to directives', () => { const TEMPLATE = ` <div dir [style.color]="'blue'" [class.strong]="false" [attr.enabled]="true"></div> `; const DIRECTIVES: TestDeclaration[] = [{ type: 'directive', name: 'Dir', selector: '[dir]', inputs: {'color': 'color', 'strong': 'strong', 'enabled': 'enabled'}, }]; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain( 'var _t2 = Dir.ngTypeCtor({ color: (null as any), strong: (null as any), enabled: (null as any) });'); expect(block).toContain('"blue"; false; true;'); }); it('should generate a circular directive reference correctly', () => { const TEMPLATE = ` <div dir #d="dir" [input]="d"></div> `; const DIRECTIVES: TestDirective[] = [{ type: 'directive', name: 'Dir', selector: '[dir]', exportAs: ['dir'], inputs: {input: 'input'}, }]; expect(tcb(TEMPLATE, DIRECTIVES)).toContain('var _t2 = Dir.ngTypeCtor({ input: (null!) });'); }); it('should generate circular references between two directives correctly', () => { const TEMPLATE = ` <div #a="dirA" dir-a [inputA]="b">A</div> <div #b="dirB" dir-b [inputB]="a">B</div> `; const DIRECTIVES: TestDirective[] = [ { type: 'directive', name: 'DirA', selector: '[dir-a]', exportAs: ['dirA'], inputs: {inputA: 'inputA'}, }, { type: 'directive', name: 'DirB', selector: '[dir-b]', exportAs: ['dirB'], inputs: {inputA: 'inputB'}, } ]; expect(tcb(TEMPLATE, DIRECTIVES)) .toContain( 'var _t3 = DirB.ngTypeCtor({ inputA: (null!) }); ' + 'var _t2 = DirA.ngTypeCtor({ inputA: (_t3) });'); }); it('should handle $any casts', () => { const TEMPLATE = `{{$any(a)}}`; const block = tcb(TEMPLATE); expect(block).toContain('((ctx).a as any);'); }); describe('experimental DOM checking via lib.dom.d.ts', () => { it('should translate unclaimed bindings to their property equivalent', () => { const TEMPLATE = `<label [for]="'test'"></label>`; const CONFIG = {...ALL_ENABLED_CONFIG, checkTypeOfDomBindings: true}; expect(tcb(TEMPLATE, /* declarations */ undefined, CONFIG)) .toContain('_t1.htmlFor = ("test");'); }); }); describe('template guards', () => { it('should emit invocation guards', () => { const DIRECTIVES: TestDeclaration[] = [{ type: 'directive', name: 'NgIf', selector: '[ngIf]', inputs: {'ngIf': 'ngIf'}, ngTemplateGuards: [{ inputName: 'ngIf', type: 'invocation', }] }]; const TEMPLATE = `<div *ngIf="person"></div>`; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('if (NgIf.ngTemplateGuard_ngIf(_t1, (ctx).person))'); }); it('should emit binding guards', () => { const DIRECTIVES: TestDeclaration[] = [{ type: 'directive', name: 'NgIf', selector: '[ngIf]', inputs: {'ngIf': 'ngIf'}, ngTemplateGuards: [{ inputName: 'ngIf', type: 'binding', }] }]; const TEMPLATE = `<div *ngIf="person !== null"></div>`; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('if (((ctx).person) !== (null))'); }); }); describe('outputs', () => { it('should emit subscribe calls for directive outputs', () => { const DIRECTIVES: TestDeclaration[] = [{ type: 'directive', name: 'Dir', selector: '[dir]', outputs: {'outputField': 'dirOutput'}, }]; const TEMPLATE = `<div dir (dirOutput)="foo($event)"></div>`; const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain( '_outputHelper(_t2.outputField).subscribe($event => (ctx).foo($event));'); }); it('should emit a listener function with AnimationEvent for animation events', () => { const TEMPLATE = `<div (@animation.done)="foo($event)"></div>`; const block = tcb(TEMPLATE); expect(block).toContain('($event: animations.AnimationEvent) => (ctx).foo($event);'); }); it('should emit addEventListener calls for unclaimed outputs', () => { const TEMPLATE = `<div (event)="foo($event)"></div>`; const block = tcb(TEMPLATE); expect(block).toContain('_t1.addEventListener("event", $event => (ctx).foo($event));'); }); it('should allow to cast $event using $any', () => { const TEMPLATE = `<div (event)="foo($any($event))"></div>`; const block = tcb(TEMPLATE); expect(block).toContain( '_t1.addEventListener("event", $event => (ctx).foo(($event as any)));'); }); }); describe('config', () => { const DIRECTIVES: TestDeclaration[] = [{ type: 'directive', name: 'Dir', selector: '[dir]', exportAs: ['dir'], inputs: {'dirInput': 'dirInput'}, outputs: {'outputField': 'dirOutput'}, hasNgTemplateContextGuard: true, }]; const BASE_CONFIG: TypeCheckingConfig = { applyTemplateContextGuards: true, checkQueries: false, checkTemplateBodies: true, checkTypeOfInputBindings: true, strictNullInputBindings: true, checkTypeOfDomBindings: false, checkTypeOfOutputEvents: true, checkTypeOfAnimationEvents: true, checkTypeOfDomEvents: true, checkTypeOfPipes: true, strictSafeNavigationTypes: true, }; describe('config.applyTemplateContextGuards', () => { const TEMPLATE = `<div *dir></div>`; const GUARD_APPLIED = 'if (Dir.ngTemplateContextGuard('; it('should apply template context guards when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain(GUARD_APPLIED); }); it('should not apply template context guards when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, applyTemplateContextGuards: false}; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).not.toContain(GUARD_APPLIED); }); }); describe('config.checkTemplateBodies', () => { const TEMPLATE = `<ng-template>{{a}}</ng-template>`; it('should descend into template bodies when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('(ctx).a;'); }); it('should not descend into template bodies when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTemplateBodies: false}; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).not.toContain('(ctx).a;'); }); }); describe('config.strictNullInputBindings', () => { const TEMPLATE = `<div dir [dirInput]="a" [nonDirInput]="b"></div>`; it('should include null and undefined when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('Dir.ngTypeCtor({ dirInput: ((ctx).a) })'); expect(block).toContain('(ctx).b;'); }); it('should use the non-null assertion operator when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, strictNullInputBindings: false}; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).toContain('Dir.ngTypeCtor({ dirInput: ((ctx).a!) })'); expect(block).toContain('(ctx).b!;'); }); }); describe('config.checkTypeOfBindings', () => { const TEMPLATE = `<div dir [dirInput]="a" [nonDirInput]="b"></div>`; it('should check types of bindings when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('Dir.ngTypeCtor({ dirInput: ((ctx).a) })'); expect(block).toContain('(ctx).b;'); }); it('should not check types of bindings when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfInputBindings: false}; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).toContain('Dir.ngTypeCtor({ dirInput: (((ctx).a as any)) })'); expect(block).toContain('((ctx).b as any);'); }); }); describe('config.checkTypeOfOutputEvents', () => { const TEMPLATE = `<div dir (dirOutput)="foo($event)" (nonDirOutput)="foo($event)"></div>`; it('should check types of directive outputs when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain( '_outputHelper(_t2.outputField).subscribe($event => (ctx).foo($event));'); expect(block).toContain( '_t1.addEventListener("nonDirOutput", $event => (ctx).foo($event));'); }); it('should not check types of directive outputs when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfOutputEvents: false}; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).toContain('($event: any) => (ctx).foo($event);'); // Note that DOM events are still checked, that is controlled by `checkTypeOfDomEvents` expect(block).toContain( '_t1.addEventListener("nonDirOutput", $event => (ctx).foo($event));'); }); }); describe('config.checkTypeOfAnimationEvents', () => { const TEMPLATE = `<div (@animation.done)="foo($event)"></div>`; it('should check types of animation events when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('($event: animations.AnimationEvent) => (ctx).foo($event);'); }); it('should not check types of animation events when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfAnimationEvents: false}; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).toContain('($event: any) => (ctx).foo($event);'); }); }); describe('config.checkTypeOfDomEvents', () => { const TEMPLATE = `<div dir (dirOutput)="foo($event)" (nonDirOutput)="foo($event)"></div>`; it('should check types of DOM events when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain( '_outputHelper(_t2.outputField).subscribe($event => (ctx).foo($event));'); expect(block).toContain( '_t1.addEventListener("nonDirOutput", $event => (ctx).foo($event));'); }); it('should not check types of DOM events when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfDomEvents: false}; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); // Note that directive outputs are still checked, that is controlled by // `checkTypeOfOutputEvents` expect(block).toContain( '_outputHelper(_t2.outputField).subscribe($event => (ctx).foo($event));'); expect(block).toContain('($event: any) => (ctx).foo($event);'); }); }); describe('config.checkTypeOfPipes', () => { const TEMPLATE = `{{a | test:b:c}}`; const PIPES: TestDeclaration[] = [{ type: 'pipe', name: 'TestPipe', pipeName: 'test', }]; it('should check types of pipes when enabled', () => { const block = tcb(TEMPLATE, PIPES); expect(block).toContain('(null as TestPipe).transform((ctx).a, (ctx).b, (ctx).c);'); }); it('should not check types of pipes when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfPipes: false}; const block = tcb(TEMPLATE, PIPES, DISABLED_CONFIG); expect(block).toContain('(null as any).transform((ctx).a, (ctx).b, (ctx).c);'); }); }); describe('config.strictSafeNavigationTypes', () => { const TEMPLATE = `{{a?.b}} {{a?.method()}}`; it('should use undefined for safe navigation operations when enabled', () => { const block = tcb(TEMPLATE, DIRECTIVES); expect(block).toContain('(((ctx).a) != null ? ((ctx).a)!.method() : undefined)'); expect(block).toContain('(((ctx).a) != null ? ((ctx).a)!.b : undefined)'); }); it('should use an \'any\' type for safe navigation operations when disabled', () => { const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, strictSafeNavigationTypes: false}; const block = tcb(TEMPLATE, DIRECTIVES, DISABLED_CONFIG); expect(block).toContain('(((ctx).a) != null ? ((ctx).a)!.method() : null as any)'); expect(block).toContain('(((ctx).a) != null ? ((ctx).a)!.b : null as any)'); }); }); }); });
packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts
1
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.023630987852811813, 0.0018598176538944244, 0.00016531761502847075, 0.00017329280672129244, 0.004528529942035675 ]
{ "id": 6, "code_window": [ " strictNullInputBindings: true,\n", " checkTypeOfDomBindings: false,\n", " checkTypeOfOutputEvents: true,\n", " checkTypeOfAnimationEvents: true,\n", " checkTypeOfDomEvents: true,\n", " checkTypeOfPipes: true,\n", " strictSafeNavigationTypes: true,\n", " };\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " checkTypeOfReferences: true,\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts", "type": "add", "edit_start_line_idx": 293 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; export default [];
packages/common/locales/extra/ksh.ts
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.000174994274857454, 0.00017311726696789265, 0.00017124024452641606, 0.00017311726696789265, 0.0000018770151655189693 ]
{ "id": 6, "code_window": [ " strictNullInputBindings: true,\n", " checkTypeOfDomBindings: false,\n", " checkTypeOfOutputEvents: true,\n", " checkTypeOfAnimationEvents: true,\n", " checkTypeOfDomEvents: true,\n", " checkTypeOfPipes: true,\n", " strictSafeNavigationTypes: true,\n", " };\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " checkTypeOfReferences: true,\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts", "type": "add", "edit_start_line_idx": 293 }
integration/cli-hello-world-ivy-minimal/src/environments/environment.prod.ts
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.00017232162645086646, 0.00017232162645086646, 0.00017232162645086646, 0.00017232162645086646, 0 ]
{ "id": 6, "code_window": [ " strictNullInputBindings: true,\n", " checkTypeOfDomBindings: false,\n", " checkTypeOfOutputEvents: true,\n", " checkTypeOfAnimationEvents: true,\n", " checkTypeOfDomEvents: true,\n", " checkTypeOfPipes: true,\n", " strictSafeNavigationTypes: true,\n", " };\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " checkTypeOfReferences: true,\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts", "type": "add", "edit_start_line_idx": 293 }
# Encryption Based on https://github.com/circleci/encrypted-files In the CircleCI web UI, we have a secret variable called `KEY` https://circleci.com/gh/angular/angular/edit#env-vars which is only exposed to non-fork builds (see "Pass secrets to builds from forked pull requests" under https://circleci.com/gh/angular/angular/edit#advanced-settings) We use this as a symmetric AES encryption key to encrypt tokens like a GitHub token that enables publishing snapshots. To create the github_token file, we take this approach: - Find the angular-builds:token in http://valentine - Go inside the CircleCI default docker image so you use the same version of openssl as we will at runtime: `docker run --rm -it circleci/node:10.12` - echo "https://[token]:@github.com" > credentials - openssl aes-256-cbc -e -in credentials -out .circleci/github_token -k $KEY - If needed, base64-encode the result so you can copy-paste it out of docker: `base64 github_token`
.circleci/README.md
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.00016770661750342697, 0.00016656328807584941, 0.00016541995864827186, 0.00016656328807584941, 0.0000011433294275775552 ]
{ "id": 7, "code_window": [ " });\n", " });\n", "\n", "\n", " describe('config.checkTypeOfPipes', () => {\n", " const TEMPLATE = `{{a | test:b:c}}`;\n", " const PIPES: TestDeclaration[] = [{\n", " type: 'pipe',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " describe('config.checkTypeOfReferences', () => {\n", " const TEMPLATE = `<input #ref>{{ref.value}}`;\n", "\n", " it('should trace references when enabled', () => {\n", " const block = tcb(TEMPLATE);\n", " expect(block).toContain('(_t1).value');\n", " });\n", "\n", " it('should use any for reference types when disabled', () => {\n", " const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfReferences: false};\n", " const block = tcb(TEMPLATE, [], DISABLED_CONFIG);\n", " expect(block).toContain('(null as any).value');\n", " });\n", " });\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts", "type": "add", "edit_start_line_idx": 418 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {BoundTarget, DirectiveMeta, SchemaMetadata} from '@angular/compiler'; import * as ts from 'typescript'; import {Reference} from '../../imports'; import {TemplateGuardMeta} from '../../metadata'; import {ClassDeclaration} from '../../reflection'; /** * Extension of `DirectiveMeta` that includes additional information required to type-check the * usage of a particular directive. */ export interface TypeCheckableDirectiveMeta extends DirectiveMeta { ref: Reference<ClassDeclaration>; queries: string[]; ngTemplateGuards: TemplateGuardMeta[]; hasNgTemplateContextGuard: boolean; } /** * Metadata required in addition to a component class in order to generate a type check block (TCB) * for that component. */ export interface TypeCheckBlockMetadata { /** * A unique identifier for the class which gave rise to this TCB. * * This can be used to map errors back to the `ts.ClassDeclaration` for the component. */ id: string; /** * Semantic information about the template of the component. */ boundTarget: BoundTarget<TypeCheckableDirectiveMeta>; /* * Pipes used in the template of the component. */ pipes: Map<string, Reference<ClassDeclaration<ts.ClassDeclaration>>>; /** * Schemas that apply to this template. */ schemas: SchemaMetadata[]; } export interface TypeCtorMetadata { /** * The name of the requested type constructor function. */ fnName: string; /** * Whether to generate a body for the function or not. */ body: boolean; /** * Input, output, and query field names in the type which should be included as constructor input. */ fields: {inputs: string[]; outputs: string[]; queries: string[];}; } export interface TypeCheckingConfig { /** * Whether to check the left-hand side type of binding operations. * * For example, if this is `false` then the expression `[input]="expr"` will have `expr` type- * checked, but not the assignment of the resulting type to the `input` property of whichever * directive or component is receiving the binding. If set to `true`, both sides of the assignment * are checked. * * This flag only affects bindings to components/directives. Bindings to the DOM are checked if * `checkTypeOfDomBindings` is set. */ checkTypeOfInputBindings: boolean; /** * Whether to use strict null types for input bindings for directives. * * If this is `true`, applications that are compiled with TypeScript's `strictNullChecks` enabled * will produce type errors for bindings which can evaluate to `undefined` or `null` where the * inputs's type does not include `undefined` or `null` in its type. If set to `false`, all * binding expressions are wrapped in a non-null assertion operator to effectively disable strict * null checks. This may be particularly useful when the directive is from a library that is not * compiled with `strictNullChecks` enabled. */ strictNullInputBindings: boolean; /** * Whether to check the left-hand side type of binding operations to DOM properties. * * As `checkTypeOfBindings`, but only applies to bindings to DOM properties. * * This does not affect the use of the `DomSchemaChecker` to validate the template against the DOM * schema. Rather, this flag is an experimental, not yet complete feature which uses the * lib.dom.d.ts DOM typings in TypeScript to validate that DOM bindings are of the correct type * for assignability to the underlying DOM element properties. */ checkTypeOfDomBindings: boolean; /** * Whether to infer the type of the `$event` variable in event bindings for directive outputs. * * If this is `true`, the type of `$event` will be inferred based on the generic type of * `EventEmitter`/`Subject` of the output. If set to `false`, the `$event` variable will be of * type `any`. */ checkTypeOfOutputEvents: boolean; /** * Whether to infer the type of the `$event` variable in event bindings for animations. * * If this is `true`, the type of `$event` will be `AnimationEvent` from `@angular/animations`. * If set to `false`, the `$event` variable will be of type `any`. */ checkTypeOfAnimationEvents: boolean; /** * Whether to infer the type of the `$event` variable in event bindings to DOM events. * * If this is `true`, the type of `$event` will be inferred based on TypeScript's * `HTMLElementEventMap`, with a fallback to the native `Event` type. If set to `false`, the * `$event` variable will be of type `any`. */ checkTypeOfDomEvents: boolean; /** * Whether to include type information from pipes in the type-checking operation. * * If this is `true`, then the pipe's type signature for `transform()` will be used to check the * usage of the pipe. If this is `false`, then the result of applying a pipe will be `any`, and * the types of the pipe's value and arguments will not be matched against the `transform()` * method. */ checkTypeOfPipes: boolean; /** * Whether to narrow the types of template contexts. */ applyTemplateContextGuards: boolean; /** * Whether to use a strict type for null-safe navigation operations. * * If this is `false`, then the return type of `a?.b` or `a?()` will be `any`. If set to `true`, * then the return type of `a?.b` for example will be the same as the type of the ternary * expression `a != null ? a.b : a`. */ strictSafeNavigationTypes: boolean; /** * Whether to descend into template bodies and check any bindings there. */ checkTemplateBodies: boolean; /** * Whether to check resolvable queries. * * This is currently an unsupported feature. */ checkQueries: false; } export type TemplateSourceMapping = DirectTemplateSourceMapping | IndirectTemplateSourceMapping | ExternalTemplateSourceMapping; /** * A mapping to an inline template in a TS file. * * `ParseSourceSpan`s for this template should be accurate for direct reporting in a TS error * message. */ export interface DirectTemplateSourceMapping { type: 'direct'; node: ts.StringLiteral|ts.NoSubstitutionTemplateLiteral; } /** * A mapping to a template which is still in a TS file, but where the node positions in any * `ParseSourceSpan`s are not accurate for one reason or another. * * This can occur if the template expression was interpolated in a way where the compiler could not * construct a contiguous mapping for the template string. The `node` refers to the `template` * expression. */ export interface IndirectTemplateSourceMapping { type: 'indirect'; componentClass: ClassDeclaration; node: ts.Expression; template: string; } /** * A mapping to a template declared in an external HTML file, where node positions in * `ParseSourceSpan`s represent accurate offsets into the external file. * * In this case, the given `node` refers to the `templateUrl` expression. */ export interface ExternalTemplateSourceMapping { type: 'external'; componentClass: ClassDeclaration; node: ts.Expression; template: string; templateUrl: string; }
packages/compiler-cli/src/ngtsc/typecheck/src/api.ts
1
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.0032390530686825514, 0.0005014883354306221, 0.0001672971120569855, 0.00021755756461061537, 0.0006807156023569405 ]
{ "id": 7, "code_window": [ " });\n", " });\n", "\n", "\n", " describe('config.checkTypeOfPipes', () => {\n", " const TEMPLATE = `{{a | test:b:c}}`;\n", " const PIPES: TestDeclaration[] = [{\n", " type: 'pipe',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " describe('config.checkTypeOfReferences', () => {\n", " const TEMPLATE = `<input #ref>{{ref.value}}`;\n", "\n", " it('should trace references when enabled', () => {\n", " const block = tcb(TEMPLATE);\n", " expect(block).toContain('(_t1).value');\n", " });\n", "\n", " it('should use any for reference types when disabled', () => {\n", " const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfReferences: false};\n", " const block = tcb(TEMPLATE, [], DISABLED_CONFIG);\n", " expect(block).toContain('(null as any).value');\n", " });\n", " });\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts", "type": "add", "edit_start_line_idx": 418 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; function plural(n: number): number { if (n === 1) return 1; if (n === 2) return 2; return 5; } export default [ 'smn', [['ip.', 'ep.'], u, u], u, [ ['p', 'V', 'M', 'K', 'T', 'V', 'L'], ['pas', 'vuo', 'maj', 'kos', 'tuo', 'vás', 'láv'], [ 'pasepeeivi', 'vuossaargâ', 'majebaargâ', 'koskoho', 'tuorâstuv', 'vástuppeeivi', 'lávurduv' ], ['pa', 'vu', 'ma', 'ko', 'tu', 'vá', 'lá'] ], [ ['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['pas', 'vuo', 'maj', 'kos', 'tuo', 'vás', 'láv'], [ 'pasepeivi', 'vuossargâ', 'majebargâ', 'koskokko', 'tuorâstâh', 'vástuppeivi', 'lávurdâh' ], ['pa', 'vu', 'ma', 'ko', 'tu', 'vá', 'lá'] ], [ ['U', 'K', 'NJ', 'C', 'V', 'K', 'S', 'P', 'Č', 'R', 'S', 'J'], [ 'uđiv', 'kuovâ', 'njuhčâ', 'cuáŋui', 'vyesi', 'kesi', 'syeini', 'porge', 'čohčâ', 'roovvâd', 'skammâ', 'juovlâ' ], [ 'uđđâivemáánu', 'kuovâmáánu', 'njuhčâmáánu', 'cuáŋuimáánu', 'vyesimáánu', 'kesimáánu', 'syeinimáánu', 'porgemáánu', 'čohčâmáánu', 'roovvâdmáánu', 'skammâmáánu', 'juovlâmáánu' ] ], u, [['oKr.', 'mKr.'], u, ['Ovdil Kristus šoddâm', 'maŋa Kristus šoddâm']], 1, [6, 0], ['d.M.y', 'MMM d. y', 'MMMM d. y', 'cccc, MMMM d. y'], ['H.mm', 'H.mm.ss', 'H.mm.ss z', 'H.mm.ss zzzz'], ['{1} {0}', '{1} \'tme\' {0}', u, u], [',', ' ', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'epiloho', '.'], ['#,##0.###', '#,##0 %', '#,##0.00 ¤', '#E0'], '€', 'euro', {'JPY': ['JP¥', '¥'], 'USD': ['US$', '$']}, plural ];
packages/common/locales/smn.ts
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.00017686332284938544, 0.00017375872994307429, 0.00016974432219285518, 0.0001743246102705598, 0.0000022758169961889507 ]
{ "id": 7, "code_window": [ " });\n", " });\n", "\n", "\n", " describe('config.checkTypeOfPipes', () => {\n", " const TEMPLATE = `{{a | test:b:c}}`;\n", " const PIPES: TestDeclaration[] = [{\n", " type: 'pipe',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " describe('config.checkTypeOfReferences', () => {\n", " const TEMPLATE = `<input #ref>{{ref.value}}`;\n", "\n", " it('should trace references when enabled', () => {\n", " const block = tcb(TEMPLATE);\n", " expect(block).toContain('(_t1).value');\n", " });\n", "\n", " it('should use any for reference types when disabled', () => {\n", " const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfReferences: false};\n", " const block = tcb(TEMPLATE, [], DISABLED_CONFIG);\n", " expect(block).toContain('(null as any).value');\n", " });\n", " });\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts", "type": "add", "edit_start_line_idx": 418 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; function plural(n: number): number { let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length; if (i === 1 && v === 0) return 1; return 5; } export default [ 'en-GG', [['a', 'p'], ['AM', 'PM'], u], [['AM', 'PM'], u, u], [ ['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'] ], u, [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] ], u, [['B', 'A'], ['BC', 'AD'], ['Before Christ', 'Anno Domini']], 1, [6, 0], ['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE, d MMMM y'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1}, {0}', u, '{1} \'at\' {0}', u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], '£', 'UK Pound', {'JPY': ['JP¥', '¥'], 'USD': ['US$', '$']}, plural ];
packages/common/locales/en-GG.ts
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.00017686348292045295, 0.00017275582649745047, 0.0001669664343353361, 0.00017411961744073778, 0.000003495780447337893 ]
{ "id": 7, "code_window": [ " });\n", " });\n", "\n", "\n", " describe('config.checkTypeOfPipes', () => {\n", " const TEMPLATE = `{{a | test:b:c}}`;\n", " const PIPES: TestDeclaration[] = [{\n", " type: 'pipe',\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " describe('config.checkTypeOfReferences', () => {\n", " const TEMPLATE = `<input #ref>{{ref.value}}`;\n", "\n", " it('should trace references when enabled', () => {\n", " const block = tcb(TEMPLATE);\n", " expect(block).toContain('(_t1).value');\n", " });\n", "\n", " it('should use any for reference types when disabled', () => {\n", " const DISABLED_CONFIG: TypeCheckingConfig = {...BASE_CONFIG, checkTypeOfReferences: false};\n", " const block = tcb(TEMPLATE, [], DISABLED_CONFIG);\n", " expect(block).toContain('(null as any).value');\n", " });\n", " });\n" ], "file_path": "packages/compiler-cli/src/ngtsc/typecheck/test/type_check_block_spec.ts", "type": "add", "edit_start_line_idx": 418 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // Only needed to satisfy the check in core/src/util/decorators.ts // TODO(alexeagle): maybe remove that check? require('reflect-metadata'); require('zone.js/dist/zone-node.js'); require('zone.js/dist/long-stack-trace-zone.js'); require('zone.js/dist/sync-test.js'); require('zone.js/dist/proxy.js'); require('zone.js/dist/jasmine-patch.js');
packages/compiler-cli/integrationtest/test/init.ts
0
https://github.com/angular/angular/commit/77240e1b602335a6cf39d3f6573ca7446da70c6b
[ 0.00017621894949115813, 0.0001753827091306448, 0.0001745464833220467, 0.0001753827091306448, 8.362330845557153e-7 ]
{ "id": 0, "code_window": [ "\n", " _.forEach(doc.decorators, function(decorator) {\n", "\n", " if (decoratorTypes.indexOf(decorator.name) !== -1) {\n", " doc.docType = decorator.name.toLowerCase();\n", " doc[doc.docType + 'Options'] = decorator.argumentInfo[0];\n", " }\n", " });\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " // Directives do not always have an argument (i.e. abstract directives).\n", " // We still create options for those, as an empty object literal is equal\n", " // to just having an empty object literal as decorator argument.\n", " doc[doc.docType + 'Options'] = decorator.argumentInfo[0] || {};\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/extractDecoratedClasses.js", "type": "replace", "edit_start_line_idx": 20 }
const testPackage = require('../../helpers/test-package'); const Dgeni = require('dgeni'); describe('processNgModuleDocs processor', () => { let processor; let injector; beforeEach(() => { const dgeni = new Dgeni([testPackage('angular-api-package')]); injector = dgeni.configureInjector(); processor = injector.get('processNgModuleDocs'); }); it('should be available on the injector', () => { expect(processor.$process).toBeDefined(); }); it('should run before the correct processor', () => { expect(processor.$runBefore).toEqual(['createSitemap']); }); it('should run after the correct processor', () => { expect(processor.$runAfter).toEqual(['extractDecoratedClassesProcessor', 'computeIdsProcessor']); }); it('should non-arrayNgModule options to arrays', () => { const docs = [{ docType: 'ngmodule', ngmoduleOptions: { a: ['AAA'], b: 'BBB', c: 42 } }]; processor.$process(docs); expect(docs[0].ngmoduleOptions.a).toEqual(['AAA']); expect(docs[0].ngmoduleOptions.b).toEqual(['BBB']); expect(docs[0].ngmoduleOptions.c).toEqual([42]); }); it('should link directive/pipe docs with their NgModule docs (sorted by id)', () => { const aliasMap = injector.get('aliasMap'); const ngModule1 = { docType: 'ngmodule', id: 'NgModule1', aliases: ['NgModule1'], ngmoduleOptions: {}}; const ngModule2 = { docType: 'ngmodule', id: 'NgModule2', aliases: ['NgModule2'], ngmoduleOptions: {}}; const directive1 = { docType: 'directive', id: 'Directive1', ngModules: ['NgModule1']}; const directive2 = { docType: 'directive', id: 'Directive2', ngModules: ['NgModule2']}; const directive3 = { docType: 'directive', id: 'Directive3', ngModules: ['NgModule1', 'NgModule2']}; const pipe1 = { docType: 'pipe', id: 'Pipe1', ngModules: ['NgModule1']}; const pipe2 = { docType: 'pipe', id: 'Pipe2', ngModules: ['NgModule2']}; const pipe3 = { docType: 'pipe', id: 'Pipe3', ngModules: ['NgModule1', 'NgModule2']}; aliasMap.addDoc(ngModule1); aliasMap.addDoc(ngModule2); processor.$process([ngModule1, pipe2, directive2, directive3, pipe1, ngModule2, directive1, pipe3]); expect(ngModule1.directives).toEqual([directive1, directive3]); expect(ngModule1.pipes).toEqual([pipe1, pipe3]); expect(ngModule2.directives).toEqual([directive2, directive3]); expect(ngModule2.pipes).toEqual([pipe2, pipe3]); expect(directive1.ngModules).toEqual([ngModule1]); expect(directive2.ngModules).toEqual([ngModule2]); expect(directive3.ngModules).toEqual([ngModule1, ngModule2]); expect(pipe1.ngModules).toEqual([ngModule1]); expect(pipe2.ngModules).toEqual([ngModule2]); expect(pipe3.ngModules).toEqual([ngModule1, ngModule2]); }); it('should error if a pipe/directive does not have a `@ngModule` tag', () => { const log = injector.get('log'); expect(() => { processor.$process([{ docType: 'directive', id: 'Directive1' }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"Directive1" has no @ngModule tag. Docs of type "directive" must have this tag. - doc "Directive1" (directive) '); expect(() => { processor.$process([{ docType: 'pipe', id: 'Pipe1' }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"Pipe1" has no @ngModule tag. Docs of type "pipe" must have this tag. - doc "Pipe1" (pipe) '); }); it('should error if a pipe/directive has an @ngModule tag that does not match an NgModule doc', () => { const log = injector.get('log'); expect(() => { processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['MissingNgModule'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule MissingNgModule" does not match a public NgModule - doc "Directive1" (directive) '); expect(() => { processor.$process([{ docType: 'pipe', id: 'Pipe1', ngModules: ['MissingNgModule'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule MissingNgModule" does not match a public NgModule - doc "Pipe1" (pipe) '); }); it('should error if a pipe/directive has an @ngModule tag that matches more than one NgModule doc', () => { const aliasMap = injector.get('aliasMap'); const log = injector.get('log'); const ngModule1 = { docType: 'ngmodule', id: 'NgModule1', aliases: ['NgModuleAlias'], ngmoduleOptions: {}}; const ngModule2 = { docType: 'ngmodule', id: 'NgModule2', aliases: ['NgModuleAlias'], ngmoduleOptions: {}}; aliasMap.addDoc(ngModule1); aliasMap.addDoc(ngModule2); expect(() => { processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['NgModuleAlias'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule NgModuleAlias" is ambiguous. Matches: NgModule1, NgModule2 - doc "Directive1" (directive) '); expect(() => { processor.$process([{ docType: 'pipe', id: 'Pipe1', ngModules: ['NgModuleAlias'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule NgModuleAlias" is ambiguous. Matches: NgModule1, NgModule2 - doc "Pipe1" (pipe) '); }); });
aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js
1
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.0002787656558211893, 0.00018246431136503816, 0.00016685566515661776, 0.0001756999990902841, 0.00002919259168265853 ]
{ "id": 0, "code_window": [ "\n", " _.forEach(doc.decorators, function(decorator) {\n", "\n", " if (decoratorTypes.indexOf(decorator.name) !== -1) {\n", " doc.docType = decorator.name.toLowerCase();\n", " doc[doc.docType + 'Options'] = decorator.argumentInfo[0];\n", " }\n", " });\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " // Directives do not always have an argument (i.e. abstract directives).\n", " // We still create options for those, as an empty object literal is equal\n", " // to just having an empty object literal as decorator argument.\n", " doc[doc.docType + 'Options'] = decorator.argumentInfo[0] || {};\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/extractDecoratedClasses.js", "type": "replace", "edit_start_line_idx": 20 }
'use strict'; // necessary for es6 output in node import { browser, element, by } from 'protractor'; describe('Structural Directives', function () { beforeAll(function () { browser.get(''); }); it('first div should show hero name with *ngIf', function () { const allDivs = element.all(by.tagName('div')); expect(allDivs.get(0).getText()).toEqual('Dr Nice'); }); it('first li should show hero name with *ngFor', function () { const allLis = element.all(by.tagName('li')); expect(allLis.get(0).getText()).toEqual('Dr Nice'); }); it('ngSwitch have two <happy-hero> instances', function () { const happyHeroEls = element.all(by.tagName('app-happy-hero')); expect(happyHeroEls.count()).toEqual(2); }); it('should toggle *ngIf="hero" with a button', function () { const toggleHeroButton = element.all(by.cssContainingText('button', 'Toggle hero')).get(0); const paragraph = element.all(by.cssContainingText('p', 'I turned the corner')); expect(paragraph.get(0).getText()).toContain('I waved'); toggleHeroButton.click().then(() => { expect(paragraph.get(0).getText()).not.toContain('I waved'); }); }); it('should have only one "Hip!" (the other is erased)', function () { const paragraph = element.all(by.cssContainingText('p', 'Hip!')); expect(paragraph.count()).toEqual(1); }); it('appUnless should show 3 paragraph (A)s and (B)s at the start', function () { const paragraph = element.all(by.css('p.unless')); expect(paragraph.count()).toEqual(3); for (let i = 0; i < 3; i++) { expect(paragraph.get(i).getText()).toContain('(A)'); } }); it('appUnless should show 1 paragraph (B) after toggling condition', function () { const toggleConditionButton = element.all(by.cssContainingText('button', 'Toggle condition')).get(0); const paragraph = element.all(by.css('p.unless')); toggleConditionButton.click().then(() => { expect(paragraph.count()).toEqual(1); expect(paragraph.get(0).getText()).toContain('(B)'); }); }); });
aio/content/examples/structural-directives/e2e/src/app.e2e-spec.ts
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.0001761178282322362, 0.00017517358355689794, 0.00017324356304015964, 0.00017561156710144132, 0.000001040740016833297 ]
{ "id": 0, "code_window": [ "\n", " _.forEach(doc.decorators, function(decorator) {\n", "\n", " if (decoratorTypes.indexOf(decorator.name) !== -1) {\n", " doc.docType = decorator.name.toLowerCase();\n", " doc[doc.docType + 'Options'] = decorator.argumentInfo[0];\n", " }\n", " });\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " // Directives do not always have an argument (i.e. abstract directives).\n", " // We still create options for those, as an empty object literal is equal\n", " // to just having an empty object literal as decorator argument.\n", " doc[doc.docType + 'Options'] = decorator.argumentInfo[0] || {};\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/extractDecoratedClasses.js", "type": "replace", "edit_start_line_idx": 20 }
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
third_party/fonts.google.com/open-sans/LICENSE.txt
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.0001778378791641444, 0.00017576180107425898, 0.00017317617312073708, 0.0001759256556397304, 0.0000012841376246797154 ]
{ "id": 0, "code_window": [ "\n", " _.forEach(doc.decorators, function(decorator) {\n", "\n", " if (decoratorTypes.indexOf(decorator.name) !== -1) {\n", " doc.docType = decorator.name.toLowerCase();\n", " doc[doc.docType + 'Options'] = decorator.argumentInfo[0];\n", " }\n", " });\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " // Directives do not always have an argument (i.e. abstract directives).\n", " // We still create options for those, as an empty object literal is equal\n", " // to just having an empty object literal as decorator argument.\n", " doc[doc.docType + 'Options'] = decorator.argumentInfo[0] || {};\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/extractDecoratedClasses.js", "type": "replace", "edit_start_line_idx": 20 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; function plural(n: number): number { if (n === 1) return 1; return 5; } export default [ 'ee-TG', [['ŋ', 'ɣ'], ['ŋdi', 'ɣetrɔ'], u], u, [ ['k', 'd', 'b', 'k', 'y', 'f', 'm'], ['kɔs', 'dzo', 'bla', 'kuɖ', 'yaw', 'fiɖ', 'mem'], ['kɔsiɖa', 'dzoɖa', 'blaɖa', 'kuɖa', 'yawoɖa', 'fiɖa', 'memleɖa'], ['kɔs', 'dzo', 'bla', 'kuɖ', 'yaw', 'fiɖ', 'mem'] ], u, [ ['d', 'd', 't', 'a', 'd', 'm', 's', 'd', 'a', 'k', 'a', 'd'], ['dzv', 'dzd', 'ted', 'afɔ', 'dam', 'mas', 'sia', 'dea', 'any', 'kel', 'ade', 'dzm'], [ 'dzove', 'dzodze', 'tedoxe', 'afɔfĩe', 'dama', 'masa', 'siamlɔm', 'deasiamime', 'anyɔnyɔ', 'kele', 'adeɛmekpɔxe', 'dzome' ] ], u, [['HYV', 'Yŋ'], u, ['Hafi Yesu Va', 'Yesu ŋɔli']], 1, [6, 0], ['M/d/yy', 'MMM d \'lia\', y', 'MMMM d \'lia\' y', 'EEEE, MMMM d \'lia\' y'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{0} {1}', u, u, u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'mnn', ':'], ['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], 'XOF', 'CFA', 'ɣetoɖofe afrikaga CFA franc BCEAO', { 'AUD': ['AU$', '$'], 'GHS': ['GH₵'], 'JPY': ['JP¥', '¥'], 'THB': ['฿'], 'USD': ['US$', '$'] }, 'ltr', plural ];
packages/common/locales/ee-TG.ts
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.00017752392159309238, 0.0001739676808938384, 0.00016981555381789804, 0.00017415662296116352, 0.0000022666044969810173 ]
{ "id": 1, "code_window": [ " $runAfter: ['extractDecoratedClassesProcessor', 'computeIdsProcessor'],\n", " $runBefore: ['createSitemap'],\n", " exportDocTypes: ['directive', 'pipe'],\n", " $process(docs) {\n", " // Match all the directives/pipes to their module\n", " const errors = [];\n", " docs.forEach(doc => {\n", " if (this.exportDocTypes.indexOf(doc.docType) !== -1) {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " skipAbstractDirectives: true,\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.js", "type": "add", "edit_start_line_idx": 5 }
module.exports = function processNgModuleDocs(getDocFromAlias, createDocMessage, log) { return { $runAfter: ['extractDecoratedClassesProcessor', 'computeIdsProcessor'], $runBefore: ['createSitemap'], exportDocTypes: ['directive', 'pipe'], $process(docs) { // Match all the directives/pipes to their module const errors = []; docs.forEach(doc => { if (this.exportDocTypes.indexOf(doc.docType) !== -1) { if (!doc.ngModules || doc.ngModules.length === 0) { errors.push(createDocMessage(`"${doc.id}" has no @ngModule tag. Docs of type "${doc.docType}" must have this tag.`, doc)); return; } doc.ngModules.forEach((ngModule, index) => { const ngModuleDocs = getDocFromAlias(ngModule, doc); if (ngModuleDocs.length === 0) { errors.push(createDocMessage(`"@ngModule ${ngModule}" does not match a public NgModule`, doc)); return; } if (ngModuleDocs.length > 1) { errors.push(createDocMessage(`"@ngModule ${ngModule}" is ambiguous. Matches: ${ngModuleDocs.map(d => d.id).join(', ')}`, doc)); return; } const ngModuleDoc = ngModuleDocs[0]; const containerName = getContainerName(doc.docType); const container = ngModuleDoc[containerName] = ngModuleDoc[containerName] || []; container.push(doc); doc.ngModules[index] = ngModuleDoc; }); } }); if (errors.length) { errors.forEach(error => log.error(error)); throw new Error('Failed to process NgModule relationships.'); } docs.forEach(doc => { if (doc.docType === 'ngmodule') { Object.keys(doc.ngmoduleOptions).forEach(key => { const value = doc.ngmoduleOptions[key]; if (value && !Array.isArray(value)) { doc.ngmoduleOptions[key] = [value]; } }); this.exportDocTypes.forEach(type => { const containerName = getContainerName(type); const container = doc[containerName]; if (container) { container.sort(byId); } }); } }); } }; }; function getContainerName(docType) { return docType + 's'; } function byId(a, b) { return a.id > b.id ? 1 : -1; }
aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.js
1
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.9990617632865906, 0.6243683695793152, 0.00016679902910254896, 0.9982420206069946, 0.483112633228302 ]
{ "id": 1, "code_window": [ " $runAfter: ['extractDecoratedClassesProcessor', 'computeIdsProcessor'],\n", " $runBefore: ['createSitemap'],\n", " exportDocTypes: ['directive', 'pipe'],\n", " $process(docs) {\n", " // Match all the directives/pipes to their module\n", " const errors = [];\n", " docs.forEach(doc => {\n", " if (this.exportDocTypes.indexOf(doc.docType) !== -1) {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " skipAbstractDirectives: true,\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.js", "type": "add", "edit_start_line_idx": 5 }
export * from './users.component';
aio/content/examples/styleguide/src/02-07/app/users/index.ts
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.00016911975399125367, 0.00016911975399125367, 0.00016911975399125367, 0.00016911975399125367, 0 ]
{ "id": 1, "code_window": [ " $runAfter: ['extractDecoratedClassesProcessor', 'computeIdsProcessor'],\n", " $runBefore: ['createSitemap'],\n", " exportDocTypes: ['directive', 'pipe'],\n", " $process(docs) {\n", " // Match all the directives/pipes to their module\n", " const errors = [];\n", " docs.forEach(doc => {\n", " if (this.exportDocTypes.indexOf(doc.docType) !== -1) {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " skipAbstractDirectives: true,\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.js", "type": "add", "edit_start_line_idx": 5 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ export const ERROR_TYPE = 'ngType'; export const ERROR_DEBUG_CONTEXT = 'ngDebugContext'; export const ERROR_ORIGINAL_ERROR = 'ngOriginalError'; export const ERROR_LOGGER = 'ngErrorLogger'; export function wrappedError(message: string, originalError: any): Error { const msg = `${message} caused by: ${ originalError instanceof Error ? originalError.message : originalError}`; const error = Error(msg); (error as any)[ERROR_ORIGINAL_ERROR] = originalError; return error; }
packages/core/src/util/errors.ts
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.00017701667093206197, 0.00017207993369083852, 0.00016748018970247358, 0.00017174291133414954, 0.000003900538558809785 ]
{ "id": 1, "code_window": [ " $runAfter: ['extractDecoratedClassesProcessor', 'computeIdsProcessor'],\n", " $runBefore: ['createSitemap'],\n", " exportDocTypes: ['directive', 'pipe'],\n", " $process(docs) {\n", " // Match all the directives/pipes to their module\n", " const errors = [];\n", " docs.forEach(doc => {\n", " if (this.exportDocTypes.indexOf(doc.docType) !== -1) {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " skipAbstractDirectives: true,\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.js", "type": "add", "edit_start_line_idx": 5 }
import { Component } from '@angular/core'; @Component({ selector: 'sg-app', templateUrl: './app.component.html' }) export class AppComponent { }
aio/content/examples/styleguide/src/05-03/app/app.component.ts
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.00017069120076484978, 0.00017069120076484978, 0.00017069120076484978, 0.00017069120076484978, 0 ]
{ "id": 2, "code_window": [ " // Match all the directives/pipes to their module\n", " const errors = [];\n", " docs.forEach(doc => {\n", " if (this.exportDocTypes.indexOf(doc.docType) !== -1) {\n", " if (!doc.ngModules || doc.ngModules.length === 0) {\n", " errors.push(createDocMessage(`\"${doc.id}\" has no @ngModule tag. Docs of type \"${doc.docType}\" must have this tag.`, doc));\n", " return;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const options = doc[`${doc.docType}Options`];\n", "\n", " // Directives without a selector are considered abstract and do\n", " // not need to be part of any `@NgModule`.\n", " if (this.skipAbstractDirectives && doc.docType === 'directive' && !options.selector) {\n", " return;\n", " }\n", "\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.js", "type": "add", "edit_start_line_idx": 10 }
const testPackage = require('../../helpers/test-package'); const Dgeni = require('dgeni'); describe('processNgModuleDocs processor', () => { let processor; let injector; beforeEach(() => { const dgeni = new Dgeni([testPackage('angular-api-package')]); injector = dgeni.configureInjector(); processor = injector.get('processNgModuleDocs'); }); it('should be available on the injector', () => { expect(processor.$process).toBeDefined(); }); it('should run before the correct processor', () => { expect(processor.$runBefore).toEqual(['createSitemap']); }); it('should run after the correct processor', () => { expect(processor.$runAfter).toEqual(['extractDecoratedClassesProcessor', 'computeIdsProcessor']); }); it('should non-arrayNgModule options to arrays', () => { const docs = [{ docType: 'ngmodule', ngmoduleOptions: { a: ['AAA'], b: 'BBB', c: 42 } }]; processor.$process(docs); expect(docs[0].ngmoduleOptions.a).toEqual(['AAA']); expect(docs[0].ngmoduleOptions.b).toEqual(['BBB']); expect(docs[0].ngmoduleOptions.c).toEqual([42]); }); it('should link directive/pipe docs with their NgModule docs (sorted by id)', () => { const aliasMap = injector.get('aliasMap'); const ngModule1 = { docType: 'ngmodule', id: 'NgModule1', aliases: ['NgModule1'], ngmoduleOptions: {}}; const ngModule2 = { docType: 'ngmodule', id: 'NgModule2', aliases: ['NgModule2'], ngmoduleOptions: {}}; const directive1 = { docType: 'directive', id: 'Directive1', ngModules: ['NgModule1']}; const directive2 = { docType: 'directive', id: 'Directive2', ngModules: ['NgModule2']}; const directive3 = { docType: 'directive', id: 'Directive3', ngModules: ['NgModule1', 'NgModule2']}; const pipe1 = { docType: 'pipe', id: 'Pipe1', ngModules: ['NgModule1']}; const pipe2 = { docType: 'pipe', id: 'Pipe2', ngModules: ['NgModule2']}; const pipe3 = { docType: 'pipe', id: 'Pipe3', ngModules: ['NgModule1', 'NgModule2']}; aliasMap.addDoc(ngModule1); aliasMap.addDoc(ngModule2); processor.$process([ngModule1, pipe2, directive2, directive3, pipe1, ngModule2, directive1, pipe3]); expect(ngModule1.directives).toEqual([directive1, directive3]); expect(ngModule1.pipes).toEqual([pipe1, pipe3]); expect(ngModule2.directives).toEqual([directive2, directive3]); expect(ngModule2.pipes).toEqual([pipe2, pipe3]); expect(directive1.ngModules).toEqual([ngModule1]); expect(directive2.ngModules).toEqual([ngModule2]); expect(directive3.ngModules).toEqual([ngModule1, ngModule2]); expect(pipe1.ngModules).toEqual([ngModule1]); expect(pipe2.ngModules).toEqual([ngModule2]); expect(pipe3.ngModules).toEqual([ngModule1, ngModule2]); }); it('should error if a pipe/directive does not have a `@ngModule` tag', () => { const log = injector.get('log'); expect(() => { processor.$process([{ docType: 'directive', id: 'Directive1' }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"Directive1" has no @ngModule tag. Docs of type "directive" must have this tag. - doc "Directive1" (directive) '); expect(() => { processor.$process([{ docType: 'pipe', id: 'Pipe1' }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"Pipe1" has no @ngModule tag. Docs of type "pipe" must have this tag. - doc "Pipe1" (pipe) '); }); it('should error if a pipe/directive has an @ngModule tag that does not match an NgModule doc', () => { const log = injector.get('log'); expect(() => { processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['MissingNgModule'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule MissingNgModule" does not match a public NgModule - doc "Directive1" (directive) '); expect(() => { processor.$process([{ docType: 'pipe', id: 'Pipe1', ngModules: ['MissingNgModule'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule MissingNgModule" does not match a public NgModule - doc "Pipe1" (pipe) '); }); it('should error if a pipe/directive has an @ngModule tag that matches more than one NgModule doc', () => { const aliasMap = injector.get('aliasMap'); const log = injector.get('log'); const ngModule1 = { docType: 'ngmodule', id: 'NgModule1', aliases: ['NgModuleAlias'], ngmoduleOptions: {}}; const ngModule2 = { docType: 'ngmodule', id: 'NgModule2', aliases: ['NgModuleAlias'], ngmoduleOptions: {}}; aliasMap.addDoc(ngModule1); aliasMap.addDoc(ngModule2); expect(() => { processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['NgModuleAlias'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule NgModuleAlias" is ambiguous. Matches: NgModule1, NgModule2 - doc "Directive1" (directive) '); expect(() => { processor.$process([{ docType: 'pipe', id: 'Pipe1', ngModules: ['NgModuleAlias'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule NgModuleAlias" is ambiguous. Matches: NgModule1, NgModule2 - doc "Pipe1" (pipe) '); }); });
aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js
1
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.0012968439841642976, 0.0003485497727524489, 0.00016618164954707026, 0.0001836236915551126, 0.0003197754849679768 ]
{ "id": 2, "code_window": [ " // Match all the directives/pipes to their module\n", " const errors = [];\n", " docs.forEach(doc => {\n", " if (this.exportDocTypes.indexOf(doc.docType) !== -1) {\n", " if (!doc.ngModules || doc.ngModules.length === 0) {\n", " errors.push(createDocMessage(`\"${doc.id}\" has no @ngModule tag. Docs of type \"${doc.docType}\" must have this tag.`, doc));\n", " return;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const options = doc[`${doc.docType}Options`];\n", "\n", " // Directives without a selector are considered abstract and do\n", " // not need to be part of any `@NgModule`.\n", " if (this.skipAbstractDirectives && doc.docType === 'directive' && !options.selector) {\n", " return;\n", " }\n", "\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.js", "type": "add", "edit_start_line_idx": 10 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {compileComponentFromMetadata, ConstantPool, CssSelector, DEFAULT_INTERPOLATION_CONFIG, DomElementSchemaRegistry, Expression, ExternalExpr, Identifiers, InterpolationConfig, LexerRange, makeBindingParser, ParseError, ParseSourceFile, parseTemplate, ParseTemplateOptions, R3ComponentMetadata, R3FactoryTarget, R3TargetBinder, SchemaMetadata, SelectorMatcher, Statement, TmplAstNode, WrappedNodeExpr} from '@angular/compiler'; import * as ts from 'typescript'; import {CycleAnalyzer} from '../../cycles'; import {ErrorCode, FatalDiagnosticError} from '../../diagnostics'; import {absoluteFrom, relative} from '../../file_system'; import {DefaultImportRecorder, ModuleResolver, Reference, ReferenceEmitter} from '../../imports'; import {DependencyTracker} from '../../incremental/api'; import {IndexingContext} from '../../indexer'; import {DirectiveMeta, extractDirectiveGuards, InjectableClassRegistry, MetadataReader, MetadataRegistry} from '../../metadata'; import {flattenInheritedDirectiveMetadata} from '../../metadata/src/inheritance'; import {EnumValue, PartialEvaluator} from '../../partial_evaluator'; import {ClassDeclaration, Decorator, ReflectionHost, reflectObjectLiteral} from '../../reflection'; import {ComponentScopeReader, LocalModuleScopeRegistry} from '../../scope'; import {AnalysisOutput, CompileResult, DecoratorHandler, DetectResult, HandlerFlags, HandlerPrecedence, ResolveResult} from '../../transform'; import {TemplateSourceMapping, TypeCheckContext} from '../../typecheck'; import {tsSourceMapBug29300Fixed} from '../../util/src/ts_source_map_bug_29300'; import {SubsetOfKeys} from '../../util/src/typescript'; import {ResourceLoader} from './api'; import {getDirectiveDiagnostics, getProviderDiagnostics} from './diagnostics'; import {extractDirectiveMetadata, parseFieldArrayValue} from './directive'; import {compileNgFactoryDefField} from './factory'; import {generateSetClassMetadataCall} from './metadata'; import {findAngularDecorator, isAngularCoreReference, isExpressionForwardReference, makeDuplicateDeclarationError, readBaseClass, resolveProvidersRequiringFactory, unwrapExpression, wrapFunctionExpressionsInParens} from './util'; const EMPTY_MAP = new Map<string, Expression>(); const EMPTY_ARRAY: any[] = []; /** * These fields of `R3ComponentMetadata` are updated in the `resolve` phase. * * The `keyof R3ComponentMetadata &` condition ensures that only fields of `R3ComponentMetadata` can * be included here. */ export type ComponentMetadataResolvedFields = SubsetOfKeys<R3ComponentMetadata, 'directives'|'pipes'|'wrapDirectivesAndPipesInClosure'>; export interface ComponentAnalysisData { /** * `meta` includes those fields of `R3ComponentMetadata` which are calculated at `analyze` time * (not during resolve). */ meta: Omit<R3ComponentMetadata, ComponentMetadataResolvedFields>; baseClass: Reference<ClassDeclaration>|'dynamic'|null; guards: ReturnType<typeof extractDirectiveGuards>; template: ParsedTemplateWithSource; metadataStmt: Statement|null; /** * Providers extracted from the `providers` field of the component annotation which will require * an Angular factory definition at runtime. */ providersRequiringFactory: Set<Reference<ClassDeclaration>>|null; /** * Providers extracted from the `viewProviders` field of the component annotation which will * require an Angular factory definition at runtime. */ viewProvidersRequiringFactory: Set<Reference<ClassDeclaration>>|null; } export type ComponentResolutionData = Pick<R3ComponentMetadata, ComponentMetadataResolvedFields>; /** * `DecoratorHandler` which handles the `@Component` annotation. */ export class ComponentDecoratorHandler implements DecoratorHandler<Decorator, ComponentAnalysisData, ComponentResolutionData> { constructor( private reflector: ReflectionHost, private evaluator: PartialEvaluator, private metaRegistry: MetadataRegistry, private metaReader: MetadataReader, private scopeReader: ComponentScopeReader, private scopeRegistry: LocalModuleScopeRegistry, private isCore: boolean, private resourceLoader: ResourceLoader, private rootDirs: ReadonlyArray<string>, private defaultPreserveWhitespaces: boolean, private i18nUseExternalIds: boolean, private enableI18nLegacyMessageIdFormat: boolean, private i18nNormalizeLineEndingsInICUs: boolean|undefined, private moduleResolver: ModuleResolver, private cycleAnalyzer: CycleAnalyzer, private refEmitter: ReferenceEmitter, private defaultImportRecorder: DefaultImportRecorder, private depTracker: DependencyTracker|null, private injectableRegistry: InjectableClassRegistry, private annotateForClosureCompiler: boolean) {} private literalCache = new Map<Decorator, ts.ObjectLiteralExpression>(); private elementSchemaRegistry = new DomElementSchemaRegistry(); /** * During the asynchronous preanalyze phase, it's necessary to parse the template to extract * any potential <link> tags which might need to be loaded. This cache ensures that work is not * thrown away, and the parsed template is reused during the analyze phase. */ private preanalyzeTemplateCache = new Map<ts.Declaration, ParsedTemplateWithSource>(); readonly precedence = HandlerPrecedence.PRIMARY; readonly name = ComponentDecoratorHandler.name; detect(node: ClassDeclaration, decorators: Decorator[]|null): DetectResult<Decorator>|undefined { if (!decorators) { return undefined; } const decorator = findAngularDecorator(decorators, 'Component', this.isCore); if (decorator !== undefined) { return { trigger: decorator.node, decorator, metadata: decorator, }; } else { return undefined; } } preanalyze(node: ClassDeclaration, decorator: Readonly<Decorator>): Promise<void>|undefined { // In preanalyze, resource URLs associated with the component are asynchronously preloaded via // the resourceLoader. This is the only time async operations are allowed for a component. // These resources are: // // - the templateUrl, if there is one // - any styleUrls if present // - any stylesheets referenced from <link> tags in the template itself // // As a result of the last one, the template must be parsed as part of preanalysis to extract // <link> tags, which may involve waiting for the templateUrl to be resolved first. // If preloading isn't possible, then skip this step. if (!this.resourceLoader.canPreload) { return undefined; } const meta = this._resolveLiteral(decorator); const component = reflectObjectLiteral(meta); const containingFile = node.getSourceFile().fileName; // Convert a styleUrl string into a Promise to preload it. const resolveStyleUrl = (styleUrl: string): Promise<void> => { const resourceUrl = this.resourceLoader.resolve(styleUrl, containingFile); const promise = this.resourceLoader.preload(resourceUrl); return promise || Promise.resolve(); }; // A Promise that waits for the template and all <link>ed styles within it to be preloaded. const templateAndTemplateStyleResources = this._preloadAndParseTemplate(node, decorator, component, containingFile).then(template => { if (template === null) { return undefined; } else { return Promise.all(template.styleUrls.map(resolveStyleUrl)).then(() => undefined); } }); // Extract all the styleUrls in the decorator. const styleUrls = this._extractStyleUrls(component, []); if (styleUrls === null) { // A fast path exists if there are no styleUrls, to just wait for // templateAndTemplateStyleResources. return templateAndTemplateStyleResources; } else { // Wait for both the template and all styleUrl resources to resolve. return Promise.all([templateAndTemplateStyleResources, ...styleUrls.map(resolveStyleUrl)]) .then(() => undefined); } } analyze( node: ClassDeclaration, decorator: Readonly<Decorator>, flags: HandlerFlags = HandlerFlags.NONE): AnalysisOutput<ComponentAnalysisData> { const containingFile = node.getSourceFile().fileName; this.literalCache.delete(decorator); // @Component inherits @Directive, so begin by extracting the @Directive metadata and building // on it. const directiveResult = extractDirectiveMetadata( node, decorator, this.reflector, this.evaluator, this.defaultImportRecorder, this.isCore, flags, this.annotateForClosureCompiler, this.elementSchemaRegistry.getDefaultComponentElementName()); if (directiveResult === undefined) { // `extractDirectiveMetadata` returns undefined when the @Directive has `jit: true`. In this // case, compilation of the decorator is skipped. Returning an empty object signifies // that no analysis was produced. return {}; } // Next, read the `@Component`-specific fields. const {decorator: component, metadata} = directiveResult; // Go through the root directories for this project, and select the one with the smallest // relative path representation. const relativeContextFilePath = this.rootDirs.reduce<string|undefined>((previous, rootDir) => { const candidate = relative(absoluteFrom(rootDir), absoluteFrom(containingFile)); if (previous === undefined || candidate.length < previous.length) { return candidate; } else { return previous; } }, undefined)!; // Note that we could technically combine the `viewProvidersRequiringFactory` and // `providersRequiringFactory` into a single set, but we keep the separate so that // we can distinguish where an error is coming from when logging the diagnostics in `resolve`. let viewProvidersRequiringFactory: Set<Reference<ClassDeclaration>>|null = null; let providersRequiringFactory: Set<Reference<ClassDeclaration>>|null = null; let wrappedViewProviders: Expression|null = null; if (component.has('viewProviders')) { const viewProviders = component.get('viewProviders')!; viewProvidersRequiringFactory = resolveProvidersRequiringFactory(viewProviders, this.reflector, this.evaluator); wrappedViewProviders = new WrappedNodeExpr( this.annotateForClosureCompiler ? wrapFunctionExpressionsInParens(viewProviders) : viewProviders); } if (component.has('providers')) { providersRequiringFactory = resolveProvidersRequiringFactory( component.get('providers')!, this.reflector, this.evaluator); } // Parse the template. // If a preanalyze phase was executed, the template may already exist in parsed form, so check // the preanalyzeTemplateCache. // Extract a closure of the template parsing code so that it can be reparsed with different // options if needed, like in the indexing pipeline. let template: ParsedTemplateWithSource; if (this.preanalyzeTemplateCache.has(node)) { // The template was parsed in preanalyze. Use it and delete it to save memory. const preanalyzed = this.preanalyzeTemplateCache.get(node)!; this.preanalyzeTemplateCache.delete(node); template = preanalyzed; } else { // The template was not already parsed. Either there's a templateUrl, or an inline template. if (component.has('templateUrl')) { const templateUrlExpr = component.get('templateUrl')!; const templateUrl = this.evaluator.evaluate(templateUrlExpr); if (typeof templateUrl !== 'string') { throw new FatalDiagnosticError( ErrorCode.VALUE_HAS_WRONG_TYPE, templateUrlExpr, 'templateUrl must be a string'); } const resourceUrl = this.resourceLoader.resolve(templateUrl, containingFile); template = this._extractExternalTemplate(node, component, templateUrlExpr, resourceUrl); } else { // Expect an inline template to be present. template = this._extractInlineTemplate(node, decorator, component, containingFile); } } if (template.errors !== undefined) { throw new Error( `Errors parsing template: ${template.errors.map(e => e.toString()).join(', ')}`); } // Figure out the set of styles. The ordering here is important: external resources (styleUrls) // precede inline styles, and styles defined in the template override styles defined in the // component. let styles: string[]|null = null; const styleUrls = this._extractStyleUrls(component, template.styleUrls); if (styleUrls !== null) { if (styles === null) { styles = []; } for (const styleUrl of styleUrls) { const resourceUrl = this.resourceLoader.resolve(styleUrl, containingFile); const resourceStr = this.resourceLoader.load(resourceUrl); styles.push(resourceStr); if (this.depTracker !== null) { this.depTracker.addResourceDependency(node.getSourceFile(), absoluteFrom(resourceUrl)); } } } if (component.has('styles')) { const litStyles = parseFieldArrayValue(component, 'styles', this.evaluator); if (litStyles !== null) { if (styles === null) { styles = litStyles; } else { styles.push(...litStyles); } } } if (template.styles.length > 0) { if (styles === null) { styles = template.styles; } else { styles.push(...template.styles); } } const encapsulation: number = this._resolveEnumValue(component, 'encapsulation', 'ViewEncapsulation') || 0; const changeDetection: number|null = this._resolveEnumValue(component, 'changeDetection', 'ChangeDetectionStrategy'); let animations: Expression|null = null; if (component.has('animations')) { animations = new WrappedNodeExpr(component.get('animations')!); } const output: AnalysisOutput<ComponentAnalysisData> = { analysis: { baseClass: readBaseClass(node, this.reflector, this.evaluator), meta: { ...metadata, template: { nodes: template.emitNodes, ngContentSelectors: template.ngContentSelectors, }, encapsulation, interpolation: template.interpolation, styles: styles || [], // These will be replaced during the compilation step, after all `NgModule`s have been // analyzed and the full compilation scope for the component can be realized. animations, viewProviders: wrappedViewProviders, i18nUseExternalIds: this.i18nUseExternalIds, relativeContextFilePath, }, guards: extractDirectiveGuards(node, this.reflector), metadataStmt: generateSetClassMetadataCall( node, this.reflector, this.defaultImportRecorder, this.isCore, this.annotateForClosureCompiler), template, providersRequiringFactory, viewProvidersRequiringFactory, }, }; if (changeDetection !== null) { output.analysis!.meta.changeDetection = changeDetection; } return output; } register(node: ClassDeclaration, analysis: ComponentAnalysisData): void { // Register this component's information with the `MetadataRegistry`. This ensures that // the information about the component is available during the compile() phase. const ref = new Reference(node); this.metaRegistry.registerDirectiveMetadata({ ref, name: node.name.text, selector: analysis.meta.selector, exportAs: analysis.meta.exportAs, inputs: analysis.meta.inputs, outputs: analysis.meta.outputs, queries: analysis.meta.queries.map(query => query.propertyName), isComponent: true, baseClass: analysis.baseClass, ...analysis.guards, }); this.injectableRegistry.registerInjectable(node); } index( context: IndexingContext, node: ClassDeclaration, analysis: Readonly<ComponentAnalysisData>) { const scope = this.scopeReader.getScopeForComponent(node); const selector = analysis.meta.selector; const matcher = new SelectorMatcher<DirectiveMeta>(); if (scope === 'error') { // Don't bother indexing components which had erroneous scopes. return null; } if (scope !== null) { for (const directive of scope.compilation.directives) { if (directive.selector !== null) { matcher.addSelectables(CssSelector.parse(directive.selector), directive); } } } const binder = new R3TargetBinder(matcher); const boundTemplate = binder.bind({template: analysis.template.diagNodes}); context.addComponent({ declaration: node, selector, boundTemplate, templateMeta: { isInline: analysis.template.isInline, file: analysis.template.file, }, }); } typeCheck(ctx: TypeCheckContext, node: ClassDeclaration, meta: Readonly<ComponentAnalysisData>): void { if (!ts.isClassDeclaration(node)) { return; } const matcher = new SelectorMatcher<DirectiveMeta>(); const pipes = new Map<string, Reference<ClassDeclaration<ts.ClassDeclaration>>>(); let schemas: SchemaMetadata[] = []; const scope = this.scopeReader.getScopeForComponent(node); if (scope === 'error') { // Don't type-check components that had errors in their scopes. return; } if (scope !== null) { for (const meta of scope.compilation.directives) { if (meta.selector !== null) { const extMeta = flattenInheritedDirectiveMetadata(this.metaReader, meta.ref); matcher.addSelectables(CssSelector.parse(meta.selector), extMeta); } } for (const {name, ref} of scope.compilation.pipes) { if (!ts.isClassDeclaration(ref.node)) { throw new Error(`Unexpected non-class declaration ${ ts.SyntaxKind[ref.node.kind]} for pipe ${ref.debugName}`); } pipes.set(name, ref as Reference<ClassDeclaration<ts.ClassDeclaration>>); } schemas = scope.schemas; } const bound = new R3TargetBinder(matcher).bind({template: meta.template.diagNodes}); ctx.addTemplate( new Reference(node), bound, pipes, schemas, meta.template.sourceMapping, meta.template.file); } resolve(node: ClassDeclaration, analysis: Readonly<ComponentAnalysisData>): ResolveResult<ComponentResolutionData> { const context = node.getSourceFile(); // Check whether this component was registered with an NgModule. If so, it should be compiled // under that module's compilation scope. const scope = this.scopeReader.getScopeForComponent(node); let metadata = analysis.meta as Readonly<R3ComponentMetadata>; const data: ComponentResolutionData = { directives: EMPTY_ARRAY, pipes: EMPTY_MAP, wrapDirectivesAndPipesInClosure: false, }; if (scope !== null && scope !== 'error') { // Replace the empty components and directives from the analyze() step with a fully expanded // scope. This is possible now because during resolve() the whole compilation unit has been // fully analyzed. // // First it needs to be determined if actually importing the directives/pipes used in the // template would create a cycle. Currently ngtsc refuses to generate cycles, so an option // known as "remote scoping" is used if a cycle would be created. In remote scoping, the // module file sets the directives/pipes on the ɵcmp of the component, without // requiring new imports (but also in a way that breaks tree shaking). // // Determining this is challenging, because the TemplateDefinitionBuilder is responsible for // matching directives and pipes in the template; however, that doesn't run until the actual // compile() step. It's not possible to run template compilation sooner as it requires the // ConstantPool for the overall file being compiled (which isn't available until the transform // step). // // Instead, directives/pipes are matched independently here, using the R3TargetBinder. This is // an alternative implementation of template matching which is used for template type-checking // and will eventually replace matching in the TemplateDefinitionBuilder. // Set up the R3TargetBinder, as well as a 'directives' array and a 'pipes' map that are later // fed to the TemplateDefinitionBuilder. First, a SelectorMatcher is constructed to match // directives that are in scope. const matcher = new SelectorMatcher<DirectiveMeta&{expression: Expression}>(); const directives: {selector: string, expression: Expression}[] = []; for (const dir of scope.compilation.directives) { const {ref, selector} = dir; if (selector !== null) { const expression = this.refEmitter.emit(ref, context); directives.push({selector, expression}); matcher.addSelectables(CssSelector.parse(selector), {...dir, expression}); } } const pipes = new Map<string, Expression>(); for (const pipe of scope.compilation.pipes) { pipes.set(pipe.name, this.refEmitter.emit(pipe.ref, context)); } // Next, the component template AST is bound using the R3TargetBinder. This produces an // BoundTarget, which is similar to a ts.TypeChecker. const binder = new R3TargetBinder(matcher); const bound = binder.bind({template: metadata.template.nodes}); // The BoundTarget knows which directives and pipes matched the template. const usedDirectives = bound.getUsedDirectives(); const usedPipes = bound.getUsedPipes().map(name => pipes.get(name)!); // Scan through the directives/pipes actually used in the template and check whether any // import which needs to be generated would create a cycle. const cycleDetected = usedDirectives.some(dir => this._isCyclicImport(dir.expression, context)) || usedPipes.some(pipe => this._isCyclicImport(pipe, context)); if (!cycleDetected) { // No cycle was detected. Record the imports that need to be created in the cycle detector // so that future cyclic import checks consider their production. for (const {expression} of usedDirectives) { this._recordSyntheticImport(expression, context); } for (const pipe of usedPipes) { this._recordSyntheticImport(pipe, context); } // Check whether the directive/pipe arrays in ɵcmp need to be wrapped in closures. // This is required if any directive/pipe reference is to a declaration in the same file but // declared after this component. const wrapDirectivesAndPipesInClosure = usedDirectives.some( dir => isExpressionForwardReference(dir.expression, node.name, context)) || usedPipes.some(pipe => isExpressionForwardReference(pipe, node.name, context)); // Actual compilation still uses the full scope, not the narrowed scope determined by // R3TargetBinder. This is a hedge against potential issues with the R3TargetBinder - right // now the TemplateDefinitionBuilder is the "source of truth" for which directives/pipes are // actually used (though the two should agree perfectly). // // TODO(alxhub): switch TemplateDefinitionBuilder over to using R3TargetBinder directly. data.directives = directives; data.pipes = pipes; data.wrapDirectivesAndPipesInClosure = wrapDirectivesAndPipesInClosure; } else { // Declaring the directiveDefs/pipeDefs arrays directly would require imports that would // create a cycle. Instead, mark this component as requiring remote scoping, so that the // NgModule file will take care of setting the directives for the component. this.scopeRegistry.setComponentAsRequiringRemoteScoping(node); } } const diagnostics: ts.Diagnostic[] = []; if (analysis.providersRequiringFactory !== null && analysis.meta.providers instanceof WrappedNodeExpr) { const providerDiagnostics = getProviderDiagnostics( analysis.providersRequiringFactory, analysis.meta.providers!.node, this.injectableRegistry); diagnostics.push(...providerDiagnostics); } if (analysis.viewProvidersRequiringFactory !== null && analysis.meta.viewProviders instanceof WrappedNodeExpr) { const viewProviderDiagnostics = getProviderDiagnostics( analysis.viewProvidersRequiringFactory, analysis.meta.viewProviders!.node, this.injectableRegistry); diagnostics.push(...viewProviderDiagnostics); } const directiveDiagnostics = getDirectiveDiagnostics( node, this.metaReader, this.evaluator, this.reflector, this.scopeRegistry, 'Component'); if (directiveDiagnostics !== null) { diagnostics.push(...directiveDiagnostics); } if (diagnostics.length > 0) { return {diagnostics}; } return {data}; } compile( node: ClassDeclaration, analysis: Readonly<ComponentAnalysisData>, resolution: Readonly<ComponentResolutionData>, pool: ConstantPool): CompileResult[] { const meta: R3ComponentMetadata = {...analysis.meta, ...resolution}; const res = compileComponentFromMetadata(meta, pool, makeBindingParser()); const factoryRes = compileNgFactoryDefField( {...meta, injectFn: Identifiers.directiveInject, target: R3FactoryTarget.Component}); if (analysis.metadataStmt !== null) { factoryRes.statements.push(analysis.metadataStmt); } return [ factoryRes, { name: 'ɵcmp', initializer: res.expression, statements: [], type: res.type, } ]; } private _resolveLiteral(decorator: Decorator): ts.ObjectLiteralExpression { if (this.literalCache.has(decorator)) { return this.literalCache.get(decorator)!; } if (decorator.args === null || decorator.args.length !== 1) { throw new FatalDiagnosticError( ErrorCode.DECORATOR_ARITY_WRONG, Decorator.nodeForError(decorator), `Incorrect number of arguments to @Component decorator`); } const meta = unwrapExpression(decorator.args[0]); if (!ts.isObjectLiteralExpression(meta)) { throw new FatalDiagnosticError( ErrorCode.DECORATOR_ARG_NOT_LITERAL, meta, `Decorator argument must be literal.`); } this.literalCache.set(decorator, meta); return meta; } private _resolveEnumValue( component: Map<string, ts.Expression>, field: string, enumSymbolName: string): number|null { let resolved: number|null = null; if (component.has(field)) { const expr = component.get(field)!; const value = this.evaluator.evaluate(expr) as any; if (value instanceof EnumValue && isAngularCoreReference(value.enumRef, enumSymbolName)) { resolved = value.resolved as number; } else { throw new FatalDiagnosticError( ErrorCode.VALUE_HAS_WRONG_TYPE, expr, `${field} must be a member of ${enumSymbolName} enum from @angular/core`); } } return resolved; } private _extractStyleUrls(component: Map<string, ts.Expression>, extraUrls: string[]): string[]|null { if (!component.has('styleUrls')) { return extraUrls.length > 0 ? extraUrls : null; } const styleUrlsExpr = component.get('styleUrls')!; const styleUrls = this.evaluator.evaluate(styleUrlsExpr); if (!Array.isArray(styleUrls) || !styleUrls.every(url => typeof url === 'string')) { throw new FatalDiagnosticError( ErrorCode.VALUE_HAS_WRONG_TYPE, styleUrlsExpr, 'styleUrls must be an array of strings'); } styleUrls.push(...extraUrls); return styleUrls as string[]; } private _preloadAndParseTemplate( node: ClassDeclaration, decorator: Decorator, component: Map<string, ts.Expression>, containingFile: string): Promise<ParsedTemplate|null> { if (component.has('templateUrl')) { // Extract the templateUrl and preload it. const templateUrlExpr = component.get('templateUrl')!; const templateUrl = this.evaluator.evaluate(templateUrlExpr); if (typeof templateUrl !== 'string') { throw new FatalDiagnosticError( ErrorCode.VALUE_HAS_WRONG_TYPE, templateUrlExpr, 'templateUrl must be a string'); } const resourceUrl = this.resourceLoader.resolve(templateUrl, containingFile); const templatePromise = this.resourceLoader.preload(resourceUrl); // If the preload worked, then actually load and parse the template, and wait for any style // URLs to resolve. if (templatePromise !== undefined) { return templatePromise.then(() => { const template = this._extractExternalTemplate(node, component, templateUrlExpr, resourceUrl); this.preanalyzeTemplateCache.set(node, template); return template; }); } else { return Promise.resolve(null); } } else { const template = this._extractInlineTemplate(node, decorator, component, containingFile); this.preanalyzeTemplateCache.set(node, template); return Promise.resolve(template); } } private _extractExternalTemplate( node: ClassDeclaration, component: Map<string, ts.Expression>, templateUrlExpr: ts.Expression, resourceUrl: string): ParsedTemplateWithSource { const templateStr = this.resourceLoader.load(resourceUrl); if (this.depTracker !== null) { this.depTracker.addResourceDependency(node.getSourceFile(), absoluteFrom(resourceUrl)); } const template = this._parseTemplate( component, templateStr, sourceMapUrl(resourceUrl), /* templateRange */ undefined, /* escapedString */ false); return { ...template, sourceMapping: { type: 'external', componentClass: node, node: templateUrlExpr, template: templateStr, templateUrl: resourceUrl, }, }; } private _extractInlineTemplate( node: ClassDeclaration, decorator: Decorator, component: Map<string, ts.Expression>, containingFile: string): ParsedTemplateWithSource { if (!component.has('template')) { throw new FatalDiagnosticError( ErrorCode.COMPONENT_MISSING_TEMPLATE, Decorator.nodeForError(decorator), 'component is missing a template'); } const templateExpr = component.get('template')!; let templateStr: string; let templateUrl: string = ''; let templateRange: LexerRange|undefined = undefined; let sourceMapping: TemplateSourceMapping; let escapedString = false; // We only support SourceMaps for inline templates that are simple string literals. if (ts.isStringLiteral(templateExpr) || ts.isNoSubstitutionTemplateLiteral(templateExpr)) { // the start and end of the `templateExpr` node includes the quotation marks, which we // must // strip templateRange = getTemplateRange(templateExpr); templateStr = templateExpr.getSourceFile().text; templateUrl = containingFile; escapedString = true; sourceMapping = { type: 'direct', node: templateExpr as (ts.StringLiteral | ts.NoSubstitutionTemplateLiteral), }; } else { const resolvedTemplate = this.evaluator.evaluate(templateExpr); if (typeof resolvedTemplate !== 'string') { throw new FatalDiagnosticError( ErrorCode.VALUE_HAS_WRONG_TYPE, templateExpr, 'template must be a string'); } templateStr = resolvedTemplate; sourceMapping = { type: 'indirect', node: templateExpr, componentClass: node, template: templateStr, }; } const template = this._parseTemplate(component, templateStr, templateUrl, templateRange, escapedString); return {...template, sourceMapping}; } private _parseTemplate( component: Map<string, ts.Expression>, templateStr: string, templateUrl: string, templateRange: LexerRange|undefined, escapedString: boolean): ParsedTemplate { let preserveWhitespaces: boolean = this.defaultPreserveWhitespaces; if (component.has('preserveWhitespaces')) { const expr = component.get('preserveWhitespaces')!; const value = this.evaluator.evaluate(expr); if (typeof value !== 'boolean') { throw new FatalDiagnosticError( ErrorCode.VALUE_HAS_WRONG_TYPE, expr, 'preserveWhitespaces must be a boolean'); } preserveWhitespaces = value; } let interpolation: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG; if (component.has('interpolation')) { const expr = component.get('interpolation')!; const value = this.evaluator.evaluate(expr); if (!Array.isArray(value) || value.length !== 2 || !value.every(element => typeof element === 'string')) { throw new FatalDiagnosticError( ErrorCode.VALUE_HAS_WRONG_TYPE, expr, 'interpolation must be an array with 2 elements of string type'); } interpolation = InterpolationConfig.fromArray(value as [string, string]); } const {errors, nodes: emitNodes, styleUrls, styles, ngContentSelectors} = parseTemplate(templateStr, templateUrl, { preserveWhitespaces, interpolationConfig: interpolation, range: templateRange, escapedString, enableI18nLegacyMessageIdFormat: this.enableI18nLegacyMessageIdFormat, i18nNormalizeLineEndingsInICUs: this.i18nNormalizeLineEndingsInICUs, }); // Unfortunately, the primary parse of the template above may not contain accurate source map // information. If used directly, it would result in incorrect code locations in template // errors, etc. There are two main problems: // // 1. `preserveWhitespaces: false` annihilates the correctness of template source mapping, as // the whitespace transformation changes the contents of HTML text nodes before they're // parsed into Angular expressions. // 2. By default, the template parser strips leading trivia characters (like spaces, tabs, and // newlines). This also destroys source mapping information. // // In order to guarantee the correctness of diagnostics, templates are parsed a second time with // the above options set to preserve source mappings. const {nodes: diagNodes} = parseTemplate(templateStr, templateUrl, { preserveWhitespaces: true, interpolationConfig: interpolation, range: templateRange, escapedString, enableI18nLegacyMessageIdFormat: this.enableI18nLegacyMessageIdFormat, i18nNormalizeLineEndingsInICUs: this.i18nNormalizeLineEndingsInICUs, leadingTriviaChars: [], }); return { interpolation, emitNodes, diagNodes, styleUrls, styles, ngContentSelectors, errors, template: templateStr, templateUrl, isInline: component.has('template'), file: new ParseSourceFile(templateStr, templateUrl), }; } private _expressionToImportedFile(expr: Expression, origin: ts.SourceFile): ts.SourceFile|null { if (!(expr instanceof ExternalExpr)) { return null; } // Figure out what file is being imported. return this.moduleResolver.resolveModule(expr.value.moduleName!, origin.fileName); } private _isCyclicImport(expr: Expression, origin: ts.SourceFile): boolean { const imported = this._expressionToImportedFile(expr, origin); if (imported === null) { return false; } // Check whether the import is legal. return this.cycleAnalyzer.wouldCreateCycle(origin, imported); } private _recordSyntheticImport(expr: Expression, origin: ts.SourceFile): void { const imported = this._expressionToImportedFile(expr, origin); if (imported === null) { return; } this.cycleAnalyzer.recordSyntheticImport(origin, imported); } } function getTemplateRange(templateExpr: ts.Expression) { const startPos = templateExpr.getStart() + 1; const {line, character} = ts.getLineAndCharacterOfPosition(templateExpr.getSourceFile(), startPos); return { startPos, startLine: line, startCol: character, endPos: templateExpr.getEnd() - 1, }; } function sourceMapUrl(resourceUrl: string): string { if (!tsSourceMapBug29300Fixed()) { // By removing the template URL we are telling the translator not to try to // map the external source file to the generated code, since the version // of TS that is running does not support it. return ''; } else { return resourceUrl; } } /** * Information about the template which was extracted during parsing. * * This contains the actual parsed template as well as any metadata collected during its parsing, * some of which might be useful for re-parsing the template with different options. */ export interface ParsedTemplate { /** * The `InterpolationConfig` specified by the user. */ interpolation: InterpolationConfig; /** * A full path to the file which contains the template. * * This can be either the original .ts file if the template is inline, or the .html file if an * external file was used. */ templateUrl: string; /** * The string contents of the template. * * This is the "logical" template string, after expansion of any escaped characters (for inline * templates). This may differ from the actual template bytes as they appear in the .ts file. */ template: string; /** * Any errors from parsing the template the first time. */ errors?: ParseError[]|undefined; /** * The template AST, parsed according to the user's specifications. */ emitNodes: TmplAstNode[]; /** * The template AST, parsed in a manner which preserves source map information for diagnostics. * * Not useful for emit. */ diagNodes: TmplAstNode[]; /** * */ /** * Any styleUrls extracted from the metadata. */ styleUrls: string[]; /** * Any inline styles extracted from the metadata. */ styles: string[]; /** * Any ng-content selectors extracted from the template. */ ngContentSelectors: string[]; /** * Whether the template was inline. */ isInline: boolean; /** * The `ParseSourceFile` for the template. */ file: ParseSourceFile; } export interface ParsedTemplateWithSource extends ParsedTemplate { sourceMapping: TemplateSourceMapping; }
packages/compiler-cli/src/ngtsc/annotations/src/component.ts
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.009148085489869118, 0.0004898959887214005, 0.00016238052921835333, 0.0001724463072605431, 0.0013336663832888007 ]
{ "id": 2, "code_window": [ " // Match all the directives/pipes to their module\n", " const errors = [];\n", " docs.forEach(doc => {\n", " if (this.exportDocTypes.indexOf(doc.docType) !== -1) {\n", " if (!doc.ngModules || doc.ngModules.length === 0) {\n", " errors.push(createDocMessage(`\"${doc.id}\" has no @ngModule tag. Docs of type \"${doc.docType}\" must have this tag.`, doc));\n", " return;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const options = doc[`${doc.docType}Options`];\n", "\n", " // Directives without a selector are considered abstract and do\n", " // not need to be part of any `@NgModule`.\n", " if (this.skipAbstractDirectives && doc.docType === 'directive' && !options.selector) {\n", " return;\n", " }\n", "\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.js", "type": "add", "edit_start_line_idx": 10 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {AST, AstVisitor, ASTWithSource, Binary, BindingPipe, Chain, Conditional, EmptyExpr, FunctionCall, ImplicitReceiver, Interpolation, KeyedRead, KeyedWrite, LiteralArray, LiteralMap, LiteralPrimitive, MethodCall, NonNullAssert, PrefixNot, PropertyRead, PropertyWrite, Quote, SafeMethodCall, SafePropertyRead} from '@angular/compiler'; import * as ts from 'typescript'; import {TypeCheckingConfig} from './api'; import {addParseSpanInfo, ignoreDiagnostics, wrapForDiagnostics} from './diagnostics'; import {tsCastToAny} from './ts_util'; export const NULL_AS_ANY = ts.createAsExpression(ts.createNull(), ts.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword)); const UNDEFINED = ts.createIdentifier('undefined'); const BINARY_OPS = new Map<string, ts.SyntaxKind>([ ['+', ts.SyntaxKind.PlusToken], ['-', ts.SyntaxKind.MinusToken], ['<', ts.SyntaxKind.LessThanToken], ['>', ts.SyntaxKind.GreaterThanToken], ['<=', ts.SyntaxKind.LessThanEqualsToken], ['>=', ts.SyntaxKind.GreaterThanEqualsToken], ['==', ts.SyntaxKind.EqualsEqualsToken], ['===', ts.SyntaxKind.EqualsEqualsEqualsToken], ['*', ts.SyntaxKind.AsteriskToken], ['/', ts.SyntaxKind.SlashToken], ['%', ts.SyntaxKind.PercentToken], ['!=', ts.SyntaxKind.ExclamationEqualsToken], ['!==', ts.SyntaxKind.ExclamationEqualsEqualsToken], ['||', ts.SyntaxKind.BarBarToken], ['&&', ts.SyntaxKind.AmpersandAmpersandToken], ['&', ts.SyntaxKind.AmpersandToken], ['|', ts.SyntaxKind.BarToken], ]); /** * Convert an `AST` to TypeScript code directly, without going through an intermediate `Expression` * AST. */ export function astToTypescript( ast: AST, maybeResolve: (ast: AST) => (ts.Expression | null), config: TypeCheckingConfig): ts.Expression { const translator = new AstTranslator(maybeResolve, config); return translator.translate(ast); } class AstTranslator implements AstVisitor { constructor( private maybeResolve: (ast: AST) => (ts.Expression | null), private config: TypeCheckingConfig) {} translate(ast: AST): ts.Expression { // Skip over an `ASTWithSource` as its `visit` method calls directly into its ast's `visit`, // which would prevent any custom resolution through `maybeResolve` for that node. if (ast instanceof ASTWithSource) { ast = ast.ast; } // The `EmptyExpr` doesn't have a dedicated method on `AstVisitor`, so it's special cased here. if (ast instanceof EmptyExpr) { return UNDEFINED; } // First attempt to let any custom resolution logic provide a translation for the given node. const resolved = this.maybeResolve(ast); if (resolved !== null) { return resolved; } return ast.visit(this); } visitBinary(ast: Binary): ts.Expression { const lhs = wrapForDiagnostics(this.translate(ast.left)); const rhs = wrapForDiagnostics(this.translate(ast.right)); const op = BINARY_OPS.get(ast.operation); if (op === undefined) { throw new Error(`Unsupported Binary.operation: ${ast.operation}`); } const node = ts.createBinary(lhs, op as any, rhs); addParseSpanInfo(node, ast.sourceSpan); return node; } visitChain(ast: Chain): ts.Expression { const elements = ast.expressions.map(expr => this.translate(expr)); const node = wrapForDiagnostics(ts.createCommaList(elements)); addParseSpanInfo(node, ast.sourceSpan); return node; } visitConditional(ast: Conditional): ts.Expression { const condExpr = this.translate(ast.condition); const trueExpr = this.translate(ast.trueExp); const falseExpr = this.translate(ast.falseExp); const node = ts.createParen(ts.createConditional(condExpr, trueExpr, falseExpr)); addParseSpanInfo(node, ast.sourceSpan); return node; } visitFunctionCall(ast: FunctionCall): ts.Expression { const receiver = wrapForDiagnostics(this.translate(ast.target!)); const args = ast.args.map(expr => this.translate(expr)); const node = ts.createCall(receiver, undefined, args); addParseSpanInfo(node, ast.sourceSpan); return node; } visitImplicitReceiver(ast: ImplicitReceiver): never { throw new Error('Method not implemented.'); } visitInterpolation(ast: Interpolation): ts.Expression { // Build up a chain of binary + operations to simulate the string concatenation of the // interpolation's expressions. The chain is started using an actual string literal to ensure // the type is inferred as 'string'. return ast.expressions.reduce( (lhs, ast) => ts.createBinary(lhs, ts.SyntaxKind.PlusToken, this.translate(ast)), ts.createLiteral('')); } visitKeyedRead(ast: KeyedRead): ts.Expression { const receiver = wrapForDiagnostics(this.translate(ast.obj)); const key = this.translate(ast.key); const node = ts.createElementAccess(receiver, key); addParseSpanInfo(node, ast.sourceSpan); return node; } visitKeyedWrite(ast: KeyedWrite): ts.Expression { const receiver = wrapForDiagnostics(this.translate(ast.obj)); const left = ts.createElementAccess(receiver, this.translate(ast.key)); // TODO(joost): annotate `left` with the span of the element access, which is not currently // available on `ast`. const right = this.translate(ast.value); const node = wrapForDiagnostics(ts.createBinary(left, ts.SyntaxKind.EqualsToken, right)); addParseSpanInfo(node, ast.sourceSpan); return node; } visitLiteralArray(ast: LiteralArray): ts.Expression { const elements = ast.expressions.map(expr => this.translate(expr)); const literal = ts.createArrayLiteral(elements); // If strictLiteralTypes is disabled, array literals are cast to `any`. const node = this.config.strictLiteralTypes ? literal : tsCastToAny(literal); addParseSpanInfo(node, ast.sourceSpan); return node; } visitLiteralMap(ast: LiteralMap): ts.Expression { const properties = ast.keys.map(({key}, idx) => { const value = this.translate(ast.values[idx]); return ts.createPropertyAssignment(ts.createStringLiteral(key), value); }); const literal = ts.createObjectLiteral(properties, true); // If strictLiteralTypes is disabled, object literals are cast to `any`. const node = this.config.strictLiteralTypes ? literal : tsCastToAny(literal); addParseSpanInfo(node, ast.sourceSpan); return node; } visitLiteralPrimitive(ast: LiteralPrimitive): ts.Expression { let node: ts.Expression; if (ast.value === undefined) { node = ts.createIdentifier('undefined'); } else if (ast.value === null) { node = ts.createNull(); } else { node = ts.createLiteral(ast.value); } addParseSpanInfo(node, ast.sourceSpan); return node; } visitMethodCall(ast: MethodCall): ts.Expression { const receiver = wrapForDiagnostics(this.translate(ast.receiver)); const method = ts.createPropertyAccess(receiver, ast.name); const args = ast.args.map(expr => this.translate(expr)); const node = ts.createCall(method, undefined, args); addParseSpanInfo(node, ast.sourceSpan); return node; } visitNonNullAssert(ast: NonNullAssert): ts.Expression { const expr = wrapForDiagnostics(this.translate(ast.expression)); const node = ts.createNonNullExpression(expr); addParseSpanInfo(node, ast.sourceSpan); return node; } visitPipe(ast: BindingPipe): never { throw new Error('Method not implemented.'); } visitPrefixNot(ast: PrefixNot): ts.Expression { const expression = wrapForDiagnostics(this.translate(ast.expression)); const node = ts.createLogicalNot(expression); addParseSpanInfo(node, ast.sourceSpan); return node; } visitPropertyRead(ast: PropertyRead): ts.Expression { // This is a normal property read - convert the receiver to an expression and emit the correct // TypeScript expression to read the property. const receiver = wrapForDiagnostics(this.translate(ast.receiver)); const node = ts.createPropertyAccess(receiver, ast.name); addParseSpanInfo(node, ast.sourceSpan); return node; } visitPropertyWrite(ast: PropertyWrite): ts.Expression { const receiver = wrapForDiagnostics(this.translate(ast.receiver)); const left = ts.createPropertyAccess(receiver, ast.name); // TODO(joost): annotate `left` with the span of the property access, which is not currently // available on `ast`. const right = this.translate(ast.value); const node = wrapForDiagnostics(ts.createBinary(left, ts.SyntaxKind.EqualsToken, right)); addParseSpanInfo(node, ast.sourceSpan); return node; } visitQuote(ast: Quote): never { throw new Error('Method not implemented.'); } visitSafeMethodCall(ast: SafeMethodCall): ts.Expression { // See the comments in SafePropertyRead above for an explanation of the cases here. let node: ts.Expression; const receiver = wrapForDiagnostics(this.translate(ast.receiver)); const args = ast.args.map(expr => this.translate(expr)); if (this.config.strictSafeNavigationTypes) { // "a?.method(...)" becomes (null as any ? a!.method(...) : undefined) const method = ts.createPropertyAccess(ts.createNonNullExpression(receiver), ast.name); const call = ts.createCall(method, undefined, args); node = ts.createParen(ts.createConditional(NULL_AS_ANY, call, UNDEFINED)); } else if (VeSafeLhsInferenceBugDetector.veWillInferAnyFor(ast)) { // "a?.method(...)" becomes (a as any).method(...) const method = ts.createPropertyAccess(tsCastToAny(receiver), ast.name); node = ts.createCall(method, undefined, args); } else { // "a?.method(...)" becomes (a!.method(...) as any) const method = ts.createPropertyAccess(ts.createNonNullExpression(receiver), ast.name); node = tsCastToAny(ts.createCall(method, undefined, args)); } addParseSpanInfo(node, ast.sourceSpan); return node; } visitSafePropertyRead(ast: SafePropertyRead): ts.Expression { let node: ts.Expression; const receiver = wrapForDiagnostics(this.translate(ast.receiver)); // The form of safe property reads depends on whether strictness is in use. if (this.config.strictSafeNavigationTypes) { // Basically, the return here is either the type of the complete expression with a null-safe // property read, or `undefined`. So a ternary is used to create an "or" type: // "a?.b" becomes (null as any ? a!.b : undefined) // The type of this expression is (typeof a!.b) | undefined, which is exactly as desired. const expr = ts.createPropertyAccess(ts.createNonNullExpression(receiver), ast.name); node = ts.createParen(ts.createConditional(NULL_AS_ANY, expr, UNDEFINED)); } else if (VeSafeLhsInferenceBugDetector.veWillInferAnyFor(ast)) { // Emulate a View Engine bug where 'any' is inferred for the left-hand side of the safe // navigation operation. With this bug, the type of the left-hand side is regarded as any. // Therefore, the left-hand side only needs repeating in the output (to validate it), and then // 'any' is used for the rest of the expression. This is done using a comma operator: // "a?.b" becomes (a as any).b, which will of course have type 'any'. node = ts.createPropertyAccess(tsCastToAny(receiver), ast.name); } else { // The View Engine bug isn't active, so check the entire type of the expression, but the final // result is still inferred as `any`. // "a?.b" becomes (a!.b as any) const expr = ts.createPropertyAccess(ts.createNonNullExpression(receiver), ast.name); node = tsCastToAny(expr); } addParseSpanInfo(node, ast.sourceSpan); return node; } } /** * Checks whether View Engine will infer a type of 'any' for the left-hand side of a safe navigation * operation. * * In View Engine's template type-checker, certain receivers of safe navigation operations will * cause a temporary variable to be allocated as part of the checking expression, to save the value * of the receiver and use it more than once in the expression. This temporary variable has type * 'any'. In practice, this means certain receivers cause View Engine to not check the full * expression, and other receivers will receive more complete checking. * * For compatibility, this logic is adapted from View Engine's expression_converter.ts so that the * Ivy checker can emulate this bug when needed. */ class VeSafeLhsInferenceBugDetector implements AstVisitor { private static SINGLETON = new VeSafeLhsInferenceBugDetector(); static veWillInferAnyFor(ast: SafeMethodCall|SafePropertyRead) { return ast.receiver.visit(VeSafeLhsInferenceBugDetector.SINGLETON); } visitBinary(ast: Binary): boolean { return ast.left.visit(this) || ast.right.visit(this); } visitChain(ast: Chain): boolean { return false; } visitConditional(ast: Conditional): boolean { return ast.condition.visit(this) || ast.trueExp.visit(this) || ast.falseExp.visit(this); } visitFunctionCall(ast: FunctionCall): boolean { return true; } visitImplicitReceiver(ast: ImplicitReceiver): boolean { return false; } visitInterpolation(ast: Interpolation): boolean { return ast.expressions.some(exp => exp.visit(this)); } visitKeyedRead(ast: KeyedRead): boolean { return false; } visitKeyedWrite(ast: KeyedWrite): boolean { return false; } visitLiteralArray(ast: LiteralArray): boolean { return true; } visitLiteralMap(ast: LiteralMap): boolean { return true; } visitLiteralPrimitive(ast: LiteralPrimitive): boolean { return false; } visitMethodCall(ast: MethodCall): boolean { return true; } visitPipe(ast: BindingPipe): boolean { return true; } visitPrefixNot(ast: PrefixNot): boolean { return ast.expression.visit(this); } visitNonNullAssert(ast: PrefixNot): boolean { return ast.expression.visit(this); } visitPropertyRead(ast: PropertyRead): boolean { return false; } visitPropertyWrite(ast: PropertyWrite): boolean { return false; } visitQuote(ast: Quote): boolean { return false; } visitSafeMethodCall(ast: SafeMethodCall): boolean { return true; } visitSafePropertyRead(ast: SafePropertyRead): boolean { return false; } }
packages/compiler-cli/src/ngtsc/typecheck/src/expression.ts
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.00017823628149926662, 0.00017244314949493855, 0.0001615262299310416, 0.0001733932876959443, 0.0000035248729091108544 ]
{ "id": 2, "code_window": [ " // Match all the directives/pipes to their module\n", " const errors = [];\n", " docs.forEach(doc => {\n", " if (this.exportDocTypes.indexOf(doc.docType) !== -1) {\n", " if (!doc.ngModules || doc.ngModules.length === 0) {\n", " errors.push(createDocMessage(`\"${doc.id}\" has no @ngModule tag. Docs of type \"${doc.docType}\" must have this tag.`, doc));\n", " return;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " const options = doc[`${doc.docType}Options`];\n", "\n", " // Directives without a selector are considered abstract and do\n", " // not need to be part of any `@NgModule`.\n", " if (this.skipAbstractDirectives && doc.docType === 'directive' && !options.selector) {\n", " return;\n", " }\n", "\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.js", "type": "add", "edit_start_line_idx": 10 }
load("//modules/playground/e2e_test:example_test.bzl", "example_test") example_test( name = "router", srcs = glob(["**/*.ts"]), server = "//modules/playground/src/web_workers/router:devserver", )
modules/playground/e2e_test/web_workers/router/BUILD.bazel
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.00017204662435688078, 0.00017204662435688078, 0.00017204662435688078, 0.00017204662435688078, 0 ]
{ "id": 3, "code_window": [ " });\n", "\n", " it('should link directive/pipe docs with their NgModule docs (sorted by id)', () => {\n", " const aliasMap = injector.get('aliasMap');\n", " const ngModule1 = { docType: 'ngmodule', id: 'NgModule1', aliases: ['NgModule1'], ngmoduleOptions: {}};\n", " const ngModule2 = { docType: 'ngmodule', id: 'NgModule2', aliases: ['NgModule2'], ngmoduleOptions: {}};\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " const directiveOptions = {selector: 'some-selector'};\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "add", "edit_start_line_idx": 41 }
const testPackage = require('../../helpers/test-package'); const Dgeni = require('dgeni'); describe('processNgModuleDocs processor', () => { let processor; let injector; beforeEach(() => { const dgeni = new Dgeni([testPackage('angular-api-package')]); injector = dgeni.configureInjector(); processor = injector.get('processNgModuleDocs'); }); it('should be available on the injector', () => { expect(processor.$process).toBeDefined(); }); it('should run before the correct processor', () => { expect(processor.$runBefore).toEqual(['createSitemap']); }); it('should run after the correct processor', () => { expect(processor.$runAfter).toEqual(['extractDecoratedClassesProcessor', 'computeIdsProcessor']); }); it('should non-arrayNgModule options to arrays', () => { const docs = [{ docType: 'ngmodule', ngmoduleOptions: { a: ['AAA'], b: 'BBB', c: 42 } }]; processor.$process(docs); expect(docs[0].ngmoduleOptions.a).toEqual(['AAA']); expect(docs[0].ngmoduleOptions.b).toEqual(['BBB']); expect(docs[0].ngmoduleOptions.c).toEqual([42]); }); it('should link directive/pipe docs with their NgModule docs (sorted by id)', () => { const aliasMap = injector.get('aliasMap'); const ngModule1 = { docType: 'ngmodule', id: 'NgModule1', aliases: ['NgModule1'], ngmoduleOptions: {}}; const ngModule2 = { docType: 'ngmodule', id: 'NgModule2', aliases: ['NgModule2'], ngmoduleOptions: {}}; const directive1 = { docType: 'directive', id: 'Directive1', ngModules: ['NgModule1']}; const directive2 = { docType: 'directive', id: 'Directive2', ngModules: ['NgModule2']}; const directive3 = { docType: 'directive', id: 'Directive3', ngModules: ['NgModule1', 'NgModule2']}; const pipe1 = { docType: 'pipe', id: 'Pipe1', ngModules: ['NgModule1']}; const pipe2 = { docType: 'pipe', id: 'Pipe2', ngModules: ['NgModule2']}; const pipe3 = { docType: 'pipe', id: 'Pipe3', ngModules: ['NgModule1', 'NgModule2']}; aliasMap.addDoc(ngModule1); aliasMap.addDoc(ngModule2); processor.$process([ngModule1, pipe2, directive2, directive3, pipe1, ngModule2, directive1, pipe3]); expect(ngModule1.directives).toEqual([directive1, directive3]); expect(ngModule1.pipes).toEqual([pipe1, pipe3]); expect(ngModule2.directives).toEqual([directive2, directive3]); expect(ngModule2.pipes).toEqual([pipe2, pipe3]); expect(directive1.ngModules).toEqual([ngModule1]); expect(directive2.ngModules).toEqual([ngModule2]); expect(directive3.ngModules).toEqual([ngModule1, ngModule2]); expect(pipe1.ngModules).toEqual([ngModule1]); expect(pipe2.ngModules).toEqual([ngModule2]); expect(pipe3.ngModules).toEqual([ngModule1, ngModule2]); }); it('should error if a pipe/directive does not have a `@ngModule` tag', () => { const log = injector.get('log'); expect(() => { processor.$process([{ docType: 'directive', id: 'Directive1' }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"Directive1" has no @ngModule tag. Docs of type "directive" must have this tag. - doc "Directive1" (directive) '); expect(() => { processor.$process([{ docType: 'pipe', id: 'Pipe1' }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"Pipe1" has no @ngModule tag. Docs of type "pipe" must have this tag. - doc "Pipe1" (pipe) '); }); it('should error if a pipe/directive has an @ngModule tag that does not match an NgModule doc', () => { const log = injector.get('log'); expect(() => { processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['MissingNgModule'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule MissingNgModule" does not match a public NgModule - doc "Directive1" (directive) '); expect(() => { processor.$process([{ docType: 'pipe', id: 'Pipe1', ngModules: ['MissingNgModule'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule MissingNgModule" does not match a public NgModule - doc "Pipe1" (pipe) '); }); it('should error if a pipe/directive has an @ngModule tag that matches more than one NgModule doc', () => { const aliasMap = injector.get('aliasMap'); const log = injector.get('log'); const ngModule1 = { docType: 'ngmodule', id: 'NgModule1', aliases: ['NgModuleAlias'], ngmoduleOptions: {}}; const ngModule2 = { docType: 'ngmodule', id: 'NgModule2', aliases: ['NgModuleAlias'], ngmoduleOptions: {}}; aliasMap.addDoc(ngModule1); aliasMap.addDoc(ngModule2); expect(() => { processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['NgModuleAlias'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule NgModuleAlias" is ambiguous. Matches: NgModule1, NgModule2 - doc "Directive1" (directive) '); expect(() => { processor.$process([{ docType: 'pipe', id: 'Pipe1', ngModules: ['NgModuleAlias'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule NgModuleAlias" is ambiguous. Matches: NgModule1, NgModule2 - doc "Pipe1" (pipe) '); }); });
aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js
1
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.9990664124488831, 0.5763906240463257, 0.0001669170887907967, 0.9518051147460938, 0.4845217168331146 ]
{ "id": 3, "code_window": [ " });\n", "\n", " it('should link directive/pipe docs with their NgModule docs (sorted by id)', () => {\n", " const aliasMap = injector.get('aliasMap');\n", " const ngModule1 = { docType: 'ngmodule', id: 'NgModule1', aliases: ['NgModule1'], ngmoduleOptions: {}};\n", " const ngModule2 = { docType: 'ngmodule', id: 'NgModule2', aliases: ['NgModule2'], ngmoduleOptions: {}};\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " const directiveOptions = {selector: 'some-selector'};\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "add", "edit_start_line_idx": 41 }
export * from './test-hero.service';
aio/content/examples/testing/src/app/model/testing/index.ts
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.00016896630404517055, 0.00016896630404517055, 0.00016896630404517055, 0.00016896630404517055, 0 ]
{ "id": 3, "code_window": [ " });\n", "\n", " it('should link directive/pipe docs with their NgModule docs (sorted by id)', () => {\n", " const aliasMap = injector.get('aliasMap');\n", " const ngModule1 = { docType: 'ngmodule', id: 'NgModule1', aliases: ['NgModule1'], ngmoduleOptions: {}};\n", " const ngModule2 = { docType: 'ngmodule', id: 'NgModule2', aliases: ['NgModule2'], ngmoduleOptions: {}};\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " const directiveOptions = {selector: 'some-selector'};\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "add", "edit_start_line_idx": 41 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {AsyncTestCompleter, beforeEach, describe, expect, inject, it} from '@angular/core/testing/src/testing_internal'; import {filter} from 'rxjs/operators'; import {EventEmitter} from '../src/event_emitter'; { describe('EventEmitter', () => { let emitter: EventEmitter<any>; beforeEach(() => { emitter = new EventEmitter(); }); it('should call the next callback', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { emitter.subscribe({ next: (value: any) => { expect(value).toEqual(99); async.done(); } }); emitter.emit(99); })); it('should call the throw callback', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { emitter.subscribe({ next: () => {}, error: (error: any) => { expect(error).toEqual('Boom'); async.done(); } }); emitter.error('Boom'); })); it('should work when no throw callback is provided', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { emitter.subscribe({ next: () => {}, error: (_: any) => { async.done(); } }); emitter.error('Boom'); })); it('should call the return callback', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { emitter.subscribe({ next: () => {}, error: (_: any) => {}, complete: () => { async.done(); } }); emitter.complete(); })); it('should subscribe to the wrapper synchronously', () => { let called = false; emitter.subscribe({ next: (value: any) => { called = true; } }); emitter.emit(99); expect(called).toBe(true); }); it('delivers next and error events synchronously', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const log: any[] /** TODO #9100 */ = []; emitter.subscribe({ next: (x: any) => { log.push(x); expect(log).toEqual([1, 2]); }, error: (err: any) => { log.push(err); expect(log).toEqual([1, 2, 3, 4]); async.done(); } }); log.push(1); emitter.emit(2); log.push(3); emitter.error(4); log.push(5); })); it('delivers next and complete events synchronously', () => { const log: any[] /** TODO #9100 */ = []; emitter.subscribe({ next: (x: any) => { log.push(x); expect(log).toEqual([1, 2]); }, error: null, complete: () => { log.push(4); expect(log).toEqual([1, 2, 3, 4]); } }); log.push(1); emitter.emit(2); log.push(3); emitter.complete(); log.push(5); expect(log).toEqual([1, 2, 3, 4, 5]); }); it('delivers events asynchronously when forced to async mode', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const e = new EventEmitter(true); const log: any[] /** TODO #9100 */ = []; e.subscribe((x: any) => { log.push(x); expect(log).toEqual([1, 3, 2]); async.done(); }); log.push(1); e.emit(2); log.push(3); })); it('reports whether it has subscribers', () => { const e = new EventEmitter(false); expect(e.observers.length > 0).toBe(false); e.subscribe({next: () => {}}); expect(e.observers.length > 0).toBe(true); }); it('remove a subscriber subscribed directly to EventEmitter', () => { const sub = emitter.subscribe(); expect(emitter.observers.length).toBe(1); sub.unsubscribe(); expect(emitter.observers.length).toBe(0); }); it('remove a subscriber subscribed after applying operators with pipe()', () => { const sub = emitter.pipe(filter(() => true)).subscribe(); expect(emitter.observers.length).toBe(1); sub.unsubscribe(); expect(emitter.observers.length).toBe(0); }); it('unsubscribing a subscriber invokes the dispose method', () => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const sub = emitter.subscribe(); sub.add(() => async.done()); sub.unsubscribe(); }); }); it('unsubscribing a subscriber after applying operators with pipe() invokes the dispose method', () => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const sub = emitter.pipe(filter(() => true)).subscribe(); sub.add(() => async.done()); sub.unsubscribe(); }); }); it('error thrown inside an Rx chain propagates to the error handler and disposes the chain', () => { let errorPropagated = false; emitter .pipe( filter(() => { throw new Error(); }), ) .subscribe( () => {}, err => errorPropagated = true, ); emitter.next(1); expect(errorPropagated).toBe(true); expect(emitter.observers.length).toBe(0); }); it('error sent by EventEmitter should dispose the Rx chain and remove subscribers', () => { let errorPropagated = false; emitter.pipe(filter(() => true)) .subscribe( () => {}, err => errorPropagated = true, ); emitter.error(1); expect(errorPropagated).toBe(true); expect(emitter.observers.length).toBe(0); }); // TODO: vsavkin: add tests cases // should call dispose on the subscription if generator returns {done:true} // should call dispose on the subscription on throw // should call dispose on the subscription on return }); }
packages/core/test/event_emitter_spec.ts
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.00017455681518185884, 0.00016979288193397224, 0.00016141707601491362, 0.00017054358613677323, 0.000003253906697864295 ]
{ "id": 3, "code_window": [ " });\n", "\n", " it('should link directive/pipe docs with their NgModule docs (sorted by id)', () => {\n", " const aliasMap = injector.get('aliasMap');\n", " const ngModule1 = { docType: 'ngmodule', id: 'NgModule1', aliases: ['NgModule1'], ngmoduleOptions: {}};\n", " const ngModule2 = { docType: 'ngmodule', id: 'NgModule2', aliases: ['NgModule2'], ngmoduleOptions: {}};\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ " const directiveOptions = {selector: 'some-selector'};\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "add", "edit_start_line_idx": 41 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js (function(global) { global.ng = global.ng || {}; global.ng.common = global.ng.common || {}; global.ng.common.locales = global.ng.common.locales || {}; var u = undefined; function plural(n) { var i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length; if (i === 1 && v === 0) return 1; return 5; } global.ng.common.locales['en-gd'] = [ 'en-GD', [['a', 'p'], ['am', 'pm'], u], [['am', 'pm'], u, u], [ ['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'] ], u, [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] ], u, [['B', 'A'], ['BC', 'AD'], ['Before Christ', 'Anno Domini']], 1, [6, 0], ['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE, d MMMM y'], ['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'], ['{1}, {0}', u, '{1} \'at\' {0}', u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], 'XCD', '$', 'East Caribbean Dollar', {'JPY': ['JP¥', '¥'], 'USD': ['US$', '$'], 'XCD': ['$']}, 'ltr', plural, [ [ ['mi', 'n', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], ['midnight', 'noon', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], u ], [['midnight', 'noon', 'morning', 'afternoon', 'evening', 'night'], u, u], [ '00:00', '12:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '21:00'], ['21:00', '06:00'] ] ] ]; })(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global || typeof window !== 'undefined' && window);
packages/common/locales/global/en-GD.js
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.00017521483823657036, 0.00017211605154443532, 0.000168450569617562, 0.0001732866803649813, 0.00000242298324337753 ]
{ "id": 4, "code_window": [ " const ngModule1 = { docType: 'ngmodule', id: 'NgModule1', aliases: ['NgModule1'], ngmoduleOptions: {}};\n", " const ngModule2 = { docType: 'ngmodule', id: 'NgModule2', aliases: ['NgModule2'], ngmoduleOptions: {}};\n", " const directive1 = { docType: 'directive', id: 'Directive1', ngModules: ['NgModule1']};\n", " const directive2 = { docType: 'directive', id: 'Directive2', ngModules: ['NgModule2']};\n", " const directive3 = { docType: 'directive', id: 'Directive3', ngModules: ['NgModule1', 'NgModule2']};\n", " const pipe1 = { docType: 'pipe', id: 'Pipe1', ngModules: ['NgModule1']};\n", " const pipe2 = { docType: 'pipe', id: 'Pipe2', ngModules: ['NgModule2']};\n", " const pipe3 = { docType: 'pipe', id: 'Pipe3', ngModules: ['NgModule1', 'NgModule2']};\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " const directive1 = { docType: 'directive', id: 'Directive1', ngModules: ['NgModule1'], directiveOptions};\n", " const directive2 = { docType: 'directive', id: 'Directive2', ngModules: ['NgModule2'], directiveOptions};\n", " const directive3 = { docType: 'directive', id: 'Directive3', ngModules: ['NgModule1', 'NgModule2'], directiveOptions};\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "replace", "edit_start_line_idx": 43 }
var _ = require('lodash'); module.exports = function extractDecoratedClassesProcessor(EXPORT_DOC_TYPES) { // Add the "directive" docType into those that can be exported from a module EXPORT_DOC_TYPES.push('directive', 'pipe'); return { $runAfter: ['processing-docs'], $runBefore: ['docs-processed'], decoratorTypes: ['Directive', 'Component', 'Pipe', 'NgModule'], $process: function(docs) { var decoratorTypes = this.decoratorTypes; _.forEach(docs, function(doc) { _.forEach(doc.decorators, function(decorator) { if (decoratorTypes.indexOf(decorator.name) !== -1) { doc.docType = decorator.name.toLowerCase(); doc[doc.docType + 'Options'] = decorator.argumentInfo[0]; } }); }); return docs; } }; };
aio/tools/transforms/angular-api-package/processors/extractDecoratedClasses.js
1
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.0008004560950212181, 0.0003942849871236831, 0.00016722183499950916, 0.00021517701679840684, 0.0002878728264477104 ]
{ "id": 4, "code_window": [ " const ngModule1 = { docType: 'ngmodule', id: 'NgModule1', aliases: ['NgModule1'], ngmoduleOptions: {}};\n", " const ngModule2 = { docType: 'ngmodule', id: 'NgModule2', aliases: ['NgModule2'], ngmoduleOptions: {}};\n", " const directive1 = { docType: 'directive', id: 'Directive1', ngModules: ['NgModule1']};\n", " const directive2 = { docType: 'directive', id: 'Directive2', ngModules: ['NgModule2']};\n", " const directive3 = { docType: 'directive', id: 'Directive3', ngModules: ['NgModule1', 'NgModule2']};\n", " const pipe1 = { docType: 'pipe', id: 'Pipe1', ngModules: ['NgModule1']};\n", " const pipe2 = { docType: 'pipe', id: 'Pipe2', ngModules: ['NgModule2']};\n", " const pipe3 = { docType: 'pipe', id: 'Pipe3', ngModules: ['NgModule1', 'NgModule2']};\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " const directive1 = { docType: 'directive', id: 'Directive1', ngModules: ['NgModule1'], directiveOptions};\n", " const directive2 = { docType: 'directive', id: 'Directive2', ngModules: ['NgModule2'], directiveOptions};\n", " const directive3 = { docType: 'directive', id: 'Directive3', ngModules: ['NgModule1', 'NgModule2'], directiveOptions};\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "replace", "edit_start_line_idx": 43 }
var path = require('canonical-path'); /** * @dgService getLinkInfo * @description * Get link information to a document that matches the given url * @kind function * @param {String} url The url to match * @param {String} title An optional title to return in the link information * @return {Object} The link information * * @property {boolean} relativeLinks Whether we expect the links to be relative to the originating doc */ module.exports = function getLinkInfo(getDocFromAlias, encodeCodeBlock, log) { return getLinkInfoImpl; function getLinkInfoImpl(url, title, currentDoc) { var linkInfo = {url: url, type: 'url', valid: true, title: title || url}; if (!url) { throw new Error('Invalid url'); } var docs = getDocFromAlias(url, currentDoc); if (!getLinkInfoImpl.useFirstAmbiguousLink && docs.length > 1) { linkInfo.valid = false; linkInfo.errorType = 'ambiguous'; linkInfo.error = 'Ambiguous link: "' + url + '".\n' + docs.reduce(function(msg, doc) { return msg + '\n "' + doc.id + '" (' + doc.docType + ') : (' + doc.path + ' / ' + doc.fileInfo.relativePath + ')'; }, 'Matching docs: '); } else if (docs.length >= 1) { linkInfo.url = docs[0].path; linkInfo.title = title || docs[0].title || docs[0].name && encodeCodeBlock(docs[0].name, true); linkInfo.type = 'doc'; if (getLinkInfoImpl.relativeLinks && currentDoc && currentDoc.path) { var currentFolder = path.dirname(currentDoc.path); var docFolder = path.dirname(linkInfo.url); var relativeFolder = path.relative(path.join('/', currentFolder), path.join('/', docFolder)); linkInfo.url = path.join(relativeFolder, path.basename(linkInfo.url)); log.debug(currentDoc.path, docs[0].path, linkInfo.url); } } else if (url.indexOf('#') > 0) { var pathAndHash = url.split('#'); linkInfo = getLinkInfoImpl(pathAndHash[0], title, currentDoc); linkInfo.url = linkInfo.url + '#' + pathAndHash[1]; return linkInfo; } else if (url.indexOf('/') === -1 && url.indexOf('#') !== 0) { linkInfo.valid = false; linkInfo.errorType = 'missing'; linkInfo.error = 'Invalid link (does not match any doc): "' + url + '"'; } else { linkInfo.title = title || ((url.indexOf('#') === 0) ? url.substring(1) : path.basename(url, '.html')); } if (linkInfo.title === undefined) { linkInfo.valid = false; linkInfo.errorType = 'no-title'; linkInfo.error = 'The link is missing a title'; } return linkInfo; } };
aio/tools/transforms/links-package/services/getLinkInfo.js
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.00016919345944188535, 0.00016668555326759815, 0.0001643401919864118, 0.00016662449343129992, 0.0000018590147874419927 ]
{ "id": 4, "code_window": [ " const ngModule1 = { docType: 'ngmodule', id: 'NgModule1', aliases: ['NgModule1'], ngmoduleOptions: {}};\n", " const ngModule2 = { docType: 'ngmodule', id: 'NgModule2', aliases: ['NgModule2'], ngmoduleOptions: {}};\n", " const directive1 = { docType: 'directive', id: 'Directive1', ngModules: ['NgModule1']};\n", " const directive2 = { docType: 'directive', id: 'Directive2', ngModules: ['NgModule2']};\n", " const directive3 = { docType: 'directive', id: 'Directive3', ngModules: ['NgModule1', 'NgModule2']};\n", " const pipe1 = { docType: 'pipe', id: 'Pipe1', ngModules: ['NgModule1']};\n", " const pipe2 = { docType: 'pipe', id: 'Pipe2', ngModules: ['NgModule2']};\n", " const pipe3 = { docType: 'pipe', id: 'Pipe3', ngModules: ['NgModule1', 'NgModule2']};\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " const directive1 = { docType: 'directive', id: 'Directive1', ngModules: ['NgModule1'], directiveOptions};\n", " const directive2 = { docType: 'directive', id: 'Directive2', ngModules: ['NgModule2'], directiveOptions};\n", " const directive3 = { docType: 'directive', id: 'Directive3', ngModules: ['NgModule1', 'NgModule2'], directiveOptions};\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "replace", "edit_start_line_idx": 43 }
export declare const A: string; export declare var B: string;
tools/ts-api-guardian/test/fixtures/simple_expected.d.ts
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.00016934177256189287, 0.00016934177256189287, 0.00016934177256189287, 0.00016934177256189287, 0 ]
{ "id": 4, "code_window": [ " const ngModule1 = { docType: 'ngmodule', id: 'NgModule1', aliases: ['NgModule1'], ngmoduleOptions: {}};\n", " const ngModule2 = { docType: 'ngmodule', id: 'NgModule2', aliases: ['NgModule2'], ngmoduleOptions: {}};\n", " const directive1 = { docType: 'directive', id: 'Directive1', ngModules: ['NgModule1']};\n", " const directive2 = { docType: 'directive', id: 'Directive2', ngModules: ['NgModule2']};\n", " const directive3 = { docType: 'directive', id: 'Directive3', ngModules: ['NgModule1', 'NgModule2']};\n", " const pipe1 = { docType: 'pipe', id: 'Pipe1', ngModules: ['NgModule1']};\n", " const pipe2 = { docType: 'pipe', id: 'Pipe2', ngModules: ['NgModule2']};\n", " const pipe3 = { docType: 'pipe', id: 'Pipe3', ngModules: ['NgModule1', 'NgModule2']};\n" ], "labels": [ "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " const directive1 = { docType: 'directive', id: 'Directive1', ngModules: ['NgModule1'], directiveOptions};\n", " const directive2 = { docType: 'directive', id: 'Directive2', ngModules: ['NgModule2'], directiveOptions};\n", " const directive3 = { docType: 'directive', id: 'Directive3', ngModules: ['NgModule1', 'NgModule2'], directiveOptions};\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "replace", "edit_start_line_idx": 43 }
// #docplaster import { Component, HostBinding, OnInit } from '@angular/core'; import { trigger, transition, animate, style, query, stagger } from '@angular/animations'; import { HEROES } from './mock-heroes'; // #docregion filter-animations @Component({ // #enddocregion filter-animations selector: 'app-hero-list-page', templateUrl: 'hero-list-page.component.html', styleUrls: ['hero-list-page.component.css'], // #docregion page-animations, filter-animations animations: [ // #enddocregion filter-animations trigger('pageAnimations', [ transition(':enter', [ query('.hero, form', [ style({opacity: 0, transform: 'translateY(-100px)'}), stagger(-30, [ animate('500ms cubic-bezier(0.35, 0, 0.25, 1)', style({ opacity: 1, transform: 'none' })) ]) ]) ]) ]), // #enddocregion page-animations // #docregion increment // #docregion filter-animations trigger('filterAnimation', [ transition(':enter, * => 0, * => -1', []), transition(':increment', [ query(':enter', [ style({ opacity: 0, width: '0px' }), stagger(50, [ animate('300ms ease-out', style({ opacity: 1, width: '*' })), ]), ], { optional: true }) ]), transition(':decrement', [ query(':leave', [ stagger(50, [ animate('300ms ease-out', style({ opacity: 0, width: '0px' })), ]), ]) ]), ]), // #enddocregion increment // #docregion page-animations ] }) export class HeroListPageComponent implements OnInit { // #enddocregion filter-animations @HostBinding('@pageAnimations') public animatePage = true; _heroes = []; // #docregion filter-animations heroTotal = -1; // #enddocregion filter-animations get heroes() { return this._heroes; } ngOnInit() { this._heroes = HEROES; } updateCriteria(criteria: string) { criteria = criteria ? criteria.trim() : ''; this._heroes = HEROES.filter(hero => hero.name.toLowerCase().includes(criteria.toLowerCase())); const newTotal = this.heroes.length; if (this.heroTotal !== newTotal) { this.heroTotal = newTotal; } else if (!criteria) { this.heroTotal = -1; } } // #docregion filter-animations } // #enddocregion filter-animations
aio/content/examples/animations/src/app/hero-list-page.component.ts
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.00017276516882702708, 0.00016955102910287678, 0.00016481836792081594, 0.00017007108544930816, 0.0000023058894385030726 ]
{ "id": 5, "code_window": [ " expect(pipe3.ngModules).toEqual([ngModule1, ngModule2]);\n", " });\n", "\n", " it('should error if a pipe/directive does not have a `@ngModule` tag', () => {\n", " const log = injector.get('log');\n", " expect(() => {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " it('should not error if an abstract directove does not have a `@ngModule` tag', () => {\n", " expect(() => {\n", " processor.$process([{ docType: 'directive', id: 'AbstractDir', directiveOptions: {} }]);\n", " }).not.toThrow();\n", "\n", " expect(() => {\n", " processor.$process([{ docType: 'directive', id: 'AbstractDir',\n", " directiveOptions: {selector: undefined} }]);\n", " }).not.toThrow();\n", " });\n", "\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "add", "edit_start_line_idx": 68 }
const testPackage = require('../../helpers/test-package'); const Dgeni = require('dgeni'); describe('processNgModuleDocs processor', () => { let processor; let injector; beforeEach(() => { const dgeni = new Dgeni([testPackage('angular-api-package')]); injector = dgeni.configureInjector(); processor = injector.get('processNgModuleDocs'); }); it('should be available on the injector', () => { expect(processor.$process).toBeDefined(); }); it('should run before the correct processor', () => { expect(processor.$runBefore).toEqual(['createSitemap']); }); it('should run after the correct processor', () => { expect(processor.$runAfter).toEqual(['extractDecoratedClassesProcessor', 'computeIdsProcessor']); }); it('should non-arrayNgModule options to arrays', () => { const docs = [{ docType: 'ngmodule', ngmoduleOptions: { a: ['AAA'], b: 'BBB', c: 42 } }]; processor.$process(docs); expect(docs[0].ngmoduleOptions.a).toEqual(['AAA']); expect(docs[0].ngmoduleOptions.b).toEqual(['BBB']); expect(docs[0].ngmoduleOptions.c).toEqual([42]); }); it('should link directive/pipe docs with their NgModule docs (sorted by id)', () => { const aliasMap = injector.get('aliasMap'); const ngModule1 = { docType: 'ngmodule', id: 'NgModule1', aliases: ['NgModule1'], ngmoduleOptions: {}}; const ngModule2 = { docType: 'ngmodule', id: 'NgModule2', aliases: ['NgModule2'], ngmoduleOptions: {}}; const directive1 = { docType: 'directive', id: 'Directive1', ngModules: ['NgModule1']}; const directive2 = { docType: 'directive', id: 'Directive2', ngModules: ['NgModule2']}; const directive3 = { docType: 'directive', id: 'Directive3', ngModules: ['NgModule1', 'NgModule2']}; const pipe1 = { docType: 'pipe', id: 'Pipe1', ngModules: ['NgModule1']}; const pipe2 = { docType: 'pipe', id: 'Pipe2', ngModules: ['NgModule2']}; const pipe3 = { docType: 'pipe', id: 'Pipe3', ngModules: ['NgModule1', 'NgModule2']}; aliasMap.addDoc(ngModule1); aliasMap.addDoc(ngModule2); processor.$process([ngModule1, pipe2, directive2, directive3, pipe1, ngModule2, directive1, pipe3]); expect(ngModule1.directives).toEqual([directive1, directive3]); expect(ngModule1.pipes).toEqual([pipe1, pipe3]); expect(ngModule2.directives).toEqual([directive2, directive3]); expect(ngModule2.pipes).toEqual([pipe2, pipe3]); expect(directive1.ngModules).toEqual([ngModule1]); expect(directive2.ngModules).toEqual([ngModule2]); expect(directive3.ngModules).toEqual([ngModule1, ngModule2]); expect(pipe1.ngModules).toEqual([ngModule1]); expect(pipe2.ngModules).toEqual([ngModule2]); expect(pipe3.ngModules).toEqual([ngModule1, ngModule2]); }); it('should error if a pipe/directive does not have a `@ngModule` tag', () => { const log = injector.get('log'); expect(() => { processor.$process([{ docType: 'directive', id: 'Directive1' }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"Directive1" has no @ngModule tag. Docs of type "directive" must have this tag. - doc "Directive1" (directive) '); expect(() => { processor.$process([{ docType: 'pipe', id: 'Pipe1' }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"Pipe1" has no @ngModule tag. Docs of type "pipe" must have this tag. - doc "Pipe1" (pipe) '); }); it('should error if a pipe/directive has an @ngModule tag that does not match an NgModule doc', () => { const log = injector.get('log'); expect(() => { processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['MissingNgModule'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule MissingNgModule" does not match a public NgModule - doc "Directive1" (directive) '); expect(() => { processor.$process([{ docType: 'pipe', id: 'Pipe1', ngModules: ['MissingNgModule'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule MissingNgModule" does not match a public NgModule - doc "Pipe1" (pipe) '); }); it('should error if a pipe/directive has an @ngModule tag that matches more than one NgModule doc', () => { const aliasMap = injector.get('aliasMap'); const log = injector.get('log'); const ngModule1 = { docType: 'ngmodule', id: 'NgModule1', aliases: ['NgModuleAlias'], ngmoduleOptions: {}}; const ngModule2 = { docType: 'ngmodule', id: 'NgModule2', aliases: ['NgModuleAlias'], ngmoduleOptions: {}}; aliasMap.addDoc(ngModule1); aliasMap.addDoc(ngModule2); expect(() => { processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['NgModuleAlias'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule NgModuleAlias" is ambiguous. Matches: NgModule1, NgModule2 - doc "Directive1" (directive) '); expect(() => { processor.$process([{ docType: 'pipe', id: 'Pipe1', ngModules: ['NgModuleAlias'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule NgModuleAlias" is ambiguous. Matches: NgModule1, NgModule2 - doc "Pipe1" (pipe) '); }); });
aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js
1
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.9986844658851624, 0.49885380268096924, 0.0001656167587498203, 0.49567291140556335, 0.4963841140270233 ]
{ "id": 5, "code_window": [ " expect(pipe3.ngModules).toEqual([ngModule1, ngModule2]);\n", " });\n", "\n", " it('should error if a pipe/directive does not have a `@ngModule` tag', () => {\n", " const log = injector.get('log');\n", " expect(() => {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " it('should not error if an abstract directove does not have a `@ngModule` tag', () => {\n", " expect(() => {\n", " processor.$process([{ docType: 'directive', id: 'AbstractDir', directiveOptions: {} }]);\n", " }).not.toThrow();\n", "\n", " expect(() => {\n", " processor.$process([{ docType: 'directive', id: 'AbstractDir',\n", " directiveOptions: {selector: undefined} }]);\n", " }).not.toThrow();\n", " });\n", "\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "add", "edit_start_line_idx": 68 }
{ "name": "angular-examples-master", "version": "1.0.0", "private": true, "description": "Master package.json, the superset of all dependencies for all of the _example package.json files. See _boilerplate/package.json for example npm scripts.", "scripts": { "http-server": "http-server", "protractor": "protractor", "webdriver:update": "node ../../../../scripts/webdriver-manager-update.js", "preinstall": "node ../../../../tools/yarn/check-yarn.js", "postinstall": "yarn webdriver:update" }, "//engines-comment": "Keep this in sync with /package.json and /aio/package.json", "engines": { "node": ">=10.9.0 <13.0.0", "yarn": ">=1.21.1 <2" }, "keywords": [], "author": "", "license": "MIT", "repository": {}, "dependencies": { "@angular/animations": "~9.1.4", "@angular/common": "~9.1.4", "@angular/compiler": "~9.1.4", "@angular/core": "~9.1.4", "@angular/elements": "~9.1.4", "@angular/forms": "~9.1.4", "@angular/platform-browser": "~9.1.4", "@angular/platform-browser-dynamic": "~9.1.4", "@angular/platform-server": "~9.1.4", "@angular/router": "~9.1.4", "@angular/service-worker": "~9.1.4", "@angular/upgrade": "~9.1.4", "@nguniversal/express-engine": "~9.0.1", "@webcomponents/custom-elements": "^1.4.1", "angular": "1.7.9", "angular-in-memory-web-api": "~0.9.0", "angular-route": "1.7.9", "core-js": "^2.5.4", "express": "^4.15.2", "rxjs": "~6.5.4", "systemjs": "0.19.39", "tslib": "^1.10.0", "zone.js": "~0.10.3" }, "devDependencies": { "@angular-devkit/build-angular": "~0.901.4", "@angular/cli": "~9.1.4", "@angular/compiler-cli": "~9.1.4", "@angular/language-service": "~9.1.4", "@nguniversal/builders": "^9.0.2", "@types/angular": "1.6.47", "@types/angular-animate": "1.5.10", "@types/angular-mocks": "1.6.0", "@types/angular-resource": "1.5.14", "@types/angular-route": "1.3.5", "@types/express": "^4.17.0", "@types/jasmine": "~3.5.0", "@types/jasminewd2": "~2.0.3", "@types/jquery": "3.3.28", "@types/node": "^12.11.1", "canonical-path": "1.0.0", "codelyzer": "^5.1.2", "concurrently": "^5.0.1", "http-server": "^0.12.0", "jasmine-core": "~3.5.0", "jasmine-marbles": "~0.6.0", "jasmine-spec-reporter": "~4.2.1", "karma": "~5.0.0", "karma-chrome-launcher": "~3.1.0", "karma-coverage-istanbul-reporter": "~2.1.0", "karma-jasmine": "~3.0.1", "karma-jasmine-html-reporter": "^1.4.2", "lite-server": "^2.2.2", "lodash": "^4.16.2", "protractor": "~5.4.3", "puppeteer": "2.1.1", "rimraf": "^2.5.4", "rollup": "^1.1.0", "rollup-plugin-commonjs": "^9.2.1", "rollup-plugin-node-resolve": "^4.0.0", "rollup-plugin-uglify": "^1.0.1", "source-map-explorer": "^1.3.2", "ts-node": "~8.3.0", "tslint": "~6.1.0", "typescript": "~3.8.3" } }
aio/tools/examples/shared/package.json
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.00017692217079456896, 0.00017317637684755027, 0.00017092819325625896, 0.00017328353715129197, 0.0000018127375369658694 ]
{ "id": 5, "code_window": [ " expect(pipe3.ngModules).toEqual([ngModule1, ngModule2]);\n", " });\n", "\n", " it('should error if a pipe/directive does not have a `@ngModule` tag', () => {\n", " const log = injector.get('log');\n", " expect(() => {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " it('should not error if an abstract directove does not have a `@ngModule` tag', () => {\n", " expect(() => {\n", " processor.$process([{ docType: 'directive', id: 'AbstractDir', directiveOptions: {} }]);\n", " }).not.toThrow();\n", "\n", " expect(() => {\n", " processor.$process([{ docType: 'directive', id: 'AbstractDir',\n", " directiveOptions: {selector: undefined} }]);\n", " }).not.toThrow();\n", " });\n", "\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "add", "edit_start_line_idx": 68 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; export default [ [ ['mi', 'n', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], ['midnight', 'noon', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], u ], [['midnight', 'noon', 'morning', 'afternoon', 'evening', 'night'], u, u], [ '00:00', '12:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '21:00'], ['21:00', '06:00'] ] ];
packages/common/locales/extra/en.ts
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.0001749593939166516, 0.00017396236944478005, 0.00017287030641455203, 0.00017405737889930606, 8.555088584216719e-7 ]
{ "id": 5, "code_window": [ " expect(pipe3.ngModules).toEqual([ngModule1, ngModule2]);\n", " });\n", "\n", " it('should error if a pipe/directive does not have a `@ngModule` tag', () => {\n", " const log = injector.get('log');\n", " expect(() => {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " it('should not error if an abstract directove does not have a `@ngModule` tag', () => {\n", " expect(() => {\n", " processor.$process([{ docType: 'directive', id: 'AbstractDir', directiveOptions: {} }]);\n", " }).not.toThrow();\n", "\n", " expect(() => {\n", " processor.$process([{ docType: 'directive', id: 'AbstractDir',\n", " directiveOptions: {selector: undefined} }]);\n", " }).not.toThrow();\n", " });\n", "\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "add", "edit_start_line_idx": 68 }
html, body { margin: 0; padding: 0; } button { margin: 0; padding: 0; border: 0; background: none; font-size: 100%; vertical-align: baseline; font-family: inherit; font-weight: inherit; color: inherit; -webkit-appearance: none; appearance: none; } body { font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif; line-height: 1.4em; background: #f5f5f5; color: #4d4d4d; min-width: 230px; max-width: 550px; margin: 0 auto; font-weight: 300; } button, input[type="checkbox"] { outline: none; } .hidden { display: none; } .todoapp { background: #fff; margin: 130px 0 40px 0; position: relative; box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1); } .todoapp input::-webkit-input-placeholder { font-style: italic; font-weight: 300; color: #e6e6e6; } .todoapp input::-moz-placeholder { font-style: italic; font-weight: 300; color: #e6e6e6; } .todoapp input::input-placeholder { font-style: italic; font-weight: 300; color: #e6e6e6; } .todoapp h1 { position: absolute; top: -155px; width: 100%; font-size: 80px; line-height: 80px; font-weight: 100; text-align: center; color: rgba(175, 47, 47, 0.15); -webkit-text-rendering: optimizeLegibility; -moz-text-rendering: optimizeLegibility; text-rendering: optimizeLegibility; } .new-todo, .edit { position: relative; margin: 0; width: 100%; font-size: 24px; font-family: inherit; font-weight: inherit; line-height: 1.4em; border: 0; outline: none; color: inherit; padding: 6px; border: 1px solid #999; box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2); box-sizing: border-box; } .new-todo { padding: 16px 16px 16px 60px; border: none; background: rgba(0, 0, 0, 0.003); box-shadow: inset 0 -2px 1px rgba(0,0,0,0.03); } .main { position: relative; z-index: 2; border-top: 1px solid #e6e6e6; } label[for='toggle-all'] { display: none; } .toggle-all { position: absolute; top: -55px; left: -12px; width: 60px; height: 34px; text-align: center; border: none; /* Mobile Safari */ } .toggle-all:before { content: '❯'; font-size: 22px; color: #e6e6e6; padding: 10px 27px 10px 27px; } .toggle-all:checked:before { color: #737373; } .todo-list { margin: 0; padding: 0; list-style: none; } .todo-list li { position: relative; font-size: 24px; border-bottom: 1px solid #ededed; } .todo-list li:last-child { border-bottom: none; } .todo-list li.editing { border-bottom: none; padding: 0; } .todo-list li.editing .edit { display: block; width: 506px; padding: 13px 17px 12px 17px; margin: 0 0 0 43px; } .todo-list li.editing .view { display: none; } .todo-list li .toggle { text-align: center; width: 40px; /* auto, since non-WebKit browsers doesn't support input styling */ height: auto; position: absolute; top: 0; bottom: 0; margin: auto 0; border: none; /* Mobile Safari */ -webkit-appearance: none; appearance: none; } .todo-list li .toggle:after { content: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="-10 -18 100 135"><circle cx="50" cy="50" r="50" fill="none" stroke="#ededed" stroke-width="3"/></svg>'); } .todo-list li .toggle:checked:after { content: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="-10 -18 100 135"><circle cx="50" cy="50" r="50" fill="none" stroke="#bddad5" stroke-width="3"/><path fill="#5dc2af" d="M72 25L42 71 27 56l-4 4 20 20 34-52z"/></svg>'); } .todo-list li label { white-space: pre-line; word-break: break-all; padding: 15px 60px 15px 15px; margin-left: 45px; display: block; line-height: 1.2; transition: color 0.4s; } .todo-list li.completed label { color: #d9d9d9; text-decoration: line-through; } .todo-list li .destroy { display: none; position: absolute; top: 0; right: 10px; bottom: 0; width: 40px; height: 40px; margin: auto 0; font-size: 30px; color: #cc9a9a; margin-bottom: 11px; transition: color 0.2s ease-out; } .todo-list li .destroy:hover { color: #af5b5e; } .todo-list li .destroy:after { content: '×'; } .todo-list li:hover .destroy { display: block; } .todo-list li .edit { display: none; } .todo-list li.editing:last-child { margin-bottom: -1px; } .footer { color: #777; padding: 10px 15px; height: 20px; text-align: center; border-top: 1px solid #e6e6e6; } .footer:before { content: ''; position: absolute; right: 0; bottom: 0; left: 0; height: 50px; overflow: hidden; box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2), 0 8px 0 -3px #f6f6f6, 0 9px 1px -3px rgba(0, 0, 0, 0.2), 0 16px 0 -6px #f6f6f6, 0 17px 2px -6px rgba(0, 0, 0, 0.2); } .todo-count { float: left; text-align: left; } .todo-count strong { font-weight: 300; } .filters { margin: 0; padding: 0; list-style: none; position: absolute; right: 0; left: 0; } .filters li { display: inline; } .filters li a { color: inherit; margin: 3px; padding: 3px 7px; text-decoration: none; border: 1px solid transparent; border-radius: 3px; } .filters li a.selected, .filters li a:hover { border-color: rgba(175, 47, 47, 0.1); } .filters li a.selected { border-color: rgba(175, 47, 47, 0.2); } .clear-completed, html .clear-completed:active { float: right; position: relative; line-height: 20px; text-decoration: none; cursor: pointer; } .clear-completed:hover { text-decoration: underline; } .info { margin: 65px auto 0; color: #bfbfbf; font-size: 10px; text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5); text-align: center; } .info p { line-height: 1; } .info a { color: inherit; text-decoration: none; font-weight: 400; } .info a:hover { text-decoration: underline; } /* Hack to remove background from Mobile Safari. Can't use it globally since it destroys checkboxes in Firefox */ @media screen and (-webkit-min-device-pixel-ratio:0) { .toggle-all, .todo-list li .toggle { background: none; } .todo-list li .toggle { height: 40px; } .toggle-all { -webkit-transform: rotate(90deg); transform: rotate(90deg); -webkit-appearance: none; appearance: none; } } @media (max-width: 430px) { .footer { height: 50px; } .filters { bottom: 10px; } }
packages/core/test/bundling/todo_i18n/todo.css
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.00017893221229314804, 0.00017535794177092612, 0.00016933275037445128, 0.00017564136942382902, 0.0000018455891677149339 ]
{ "id": 6, "code_window": [ " it('should error if a pipe/directive does not have a `@ngModule` tag', () => {\n", " const log = injector.get('log');\n", " expect(() => {\n", " processor.$process([{ docType: 'directive', id: 'Directive1' }]);\n", " }).toThrowError('Failed to process NgModule relationships.');\n", " expect(log.error).toHaveBeenCalledWith(\n", " '\"Directive1\" has no @ngModule tag. Docs of type \"directive\" must have this tag. - doc \"Directive1\" (directive) ');\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " processor.$process([{ docType: 'directive', id: 'Directive1',\n", " directiveOptions: {selector: 'dir1'} }]);\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "replace", "edit_start_line_idx": 71 }
var _ = require('lodash'); module.exports = function extractDecoratedClassesProcessor(EXPORT_DOC_TYPES) { // Add the "directive" docType into those that can be exported from a module EXPORT_DOC_TYPES.push('directive', 'pipe'); return { $runAfter: ['processing-docs'], $runBefore: ['docs-processed'], decoratorTypes: ['Directive', 'Component', 'Pipe', 'NgModule'], $process: function(docs) { var decoratorTypes = this.decoratorTypes; _.forEach(docs, function(doc) { _.forEach(doc.decorators, function(decorator) { if (decoratorTypes.indexOf(decorator.name) !== -1) { doc.docType = decorator.name.toLowerCase(); doc[doc.docType + 'Options'] = decorator.argumentInfo[0]; } }); }); return docs; } }; };
aio/tools/transforms/angular-api-package/processors/extractDecoratedClasses.js
1
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.003321245312690735, 0.0014129815390333533, 0.00016633734048809856, 0.0007513617747463286, 0.0013703203294426203 ]
{ "id": 6, "code_window": [ " it('should error if a pipe/directive does not have a `@ngModule` tag', () => {\n", " const log = injector.get('log');\n", " expect(() => {\n", " processor.$process([{ docType: 'directive', id: 'Directive1' }]);\n", " }).toThrowError('Failed to process NgModule relationships.');\n", " expect(log.error).toHaveBeenCalledWith(\n", " '\"Directive1\" has no @ngModule tag. Docs of type \"directive\" must have this tag. - doc \"Directive1\" (directive) ');\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " processor.$process([{ docType: 'directive', id: 'Directive1',\n", " directiveOptions: {selector: 'dir1'} }]);\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "replace", "edit_start_line_idx": 71 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {DOCUMENT, isPlatformBrowser, ɵgetDOM as getDOM} from '@angular/common'; import {APP_INITIALIZER, Compiler, Component, createPlatformFactory, CUSTOM_ELEMENTS_SCHEMA, Directive, ErrorHandler, Inject, Injector, Input, LOCALE_ID, NgModule, OnDestroy, Pipe, PLATFORM_ID, PLATFORM_INITIALIZER, Provider, Sanitizer, StaticProvider, Type, VERSION} from '@angular/core'; import {ApplicationRef, destroyPlatform} from '@angular/core/src/application_ref'; import {Console} from '@angular/core/src/console'; import {ComponentRef} from '@angular/core/src/linker/component_factory'; import {Testability, TestabilityRegistry} from '@angular/core/src/testability/testability'; import {afterEach, AsyncTestCompleter, beforeEach, beforeEachProviders, describe, inject, it, Log} from '@angular/core/testing/src/testing_internal'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {expect} from '@angular/platform-browser/testing/src/matchers'; import {ivyEnabled, modifiedInIvy, onlyInIvy} from '@angular/private/testing'; @Component({selector: 'non-existent', template: ''}) class NonExistentComp { } @Component({selector: 'hello-app', template: '{{greeting}} world!'}) class HelloRootCmp { greeting: string; constructor() { this.greeting = 'hello'; } } @Component({selector: 'hello-app', template: 'before: <ng-content></ng-content> after: done'}) class HelloRootCmpContent { constructor() {} } @Component({selector: 'hello-app-2', template: '{{greeting}} world, again!'}) class HelloRootCmp2 { greeting: string; constructor() { this.greeting = 'hello'; } } @Component({selector: 'hello-app', template: ''}) class HelloRootCmp3 { appBinding: any /** TODO #9100 */; constructor(@Inject('appBinding') appBinding: any /** TODO #9100 */) { this.appBinding = appBinding; } } @Component({selector: 'hello-app', template: ''}) class HelloRootCmp4 { appRef: any /** TODO #9100 */; constructor(@Inject(ApplicationRef) appRef: ApplicationRef) { this.appRef = appRef; } } @Component({selector: 'hello-app'}) class HelloRootMissingTemplate { } @Directive({selector: 'hello-app'}) class HelloRootDirectiveIsNotCmp { } @Component({selector: 'hello-app', template: ''}) class HelloOnDestroyTickCmp implements OnDestroy { appRef: ApplicationRef; constructor(@Inject(ApplicationRef) appRef: ApplicationRef) { this.appRef = appRef; } ngOnDestroy(): void { this.appRef.tick(); } } @Component({selector: 'hello-app', templateUrl: './sometemplate.html'}) class HelloUrlCmp { greeting = 'hello'; } @Directive({selector: '[someDir]', host: {'[title]': 'someDir'}}) class SomeDirective { // TODO(issue/24571): remove '!'. @Input() someDir!: string; } @Pipe({name: 'somePipe'}) class SomePipe { transform(value: string): any { return `transformed ${value}`; } } @Component({selector: 'hello-app', template: `<div [someDir]="'someValue' | somePipe"></div>`}) class HelloCmpUsingPlatformDirectiveAndPipe { show: boolean = false; } @Component({selector: 'hello-app', template: '<some-el [someProp]="true">hello world!</some-el>'}) class HelloCmpUsingCustomElement { } class MockConsole { res: any[][] = []; error(...s: any[]): void { this.res.push(s); } } class DummyConsole implements Console { public warnings: string[] = []; log(message: string) {} warn(message: string) { this.warnings.push(message); } } class TestModule {} function bootstrap( cmpType: any, providers: Provider[] = [], platformProviders: StaticProvider[] = [], imports: Type<any>[] = []): Promise<any> { @NgModule({ imports: [BrowserModule, ...imports], declarations: [cmpType], bootstrap: [cmpType], providers: providers, schemas: [CUSTOM_ELEMENTS_SCHEMA] }) class TestModule { } return platformBrowserDynamic(platformProviders).bootstrapModule(TestModule); } { let el: any /** TODO #9100 */, el2: any /** TODO #9100 */, testProviders: Provider[], lightDom: any /** TODO #9100 */; describe('bootstrap factory method', () => { if (isNode) return; let compilerConsole: DummyConsole; beforeEachProviders(() => { return [Log]; }); beforeEach(inject([DOCUMENT], (doc: any) => { destroyPlatform(); compilerConsole = new DummyConsole(); testProviders = [{provide: Console, useValue: compilerConsole}]; const oldRoots = doc.querySelectorAll('hello-app,hello-app-2,light-dom-el'); for (let i = 0; i < oldRoots.length; i++) { getDOM().remove(oldRoots[i]); } el = getDOM().createElement('hello-app', doc); el2 = getDOM().createElement('hello-app-2', doc); lightDom = getDOM().createElement('light-dom-el', doc); doc.body.appendChild(el); doc.body.appendChild(el2); el.appendChild(lightDom); lightDom.textContent = 'loading'; })); afterEach(destroyPlatform); // TODO(misko): can't use `modifiedInIvy.it` because the `it` is somehow special here. modifiedInIvy('bootstrapping non-Component throws in View Engine').isEnabled && it('should throw if bootstrapped Directive is not a Component', inject([AsyncTestCompleter], (done: AsyncTestCompleter) => { const logger = new MockConsole(); const errorHandler = new ErrorHandler(); (errorHandler as any)._console = logger as any; expect( () => bootstrap( HelloRootDirectiveIsNotCmp, [{provide: ErrorHandler, useValue: errorHandler}])) .toThrowError(`HelloRootDirectiveIsNotCmp cannot be used as an entry component.`); done.done(); })); // TODO(misko): can't use `onlyInIvy.it` because the `it` is somehow special here. onlyInIvy('bootstrapping non-Component rejects Promise in Ivy').isEnabled && it('should throw if bootstrapped Directive is not a Component', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const logger = new MockConsole(); const errorHandler = new ErrorHandler(); (errorHandler as any)._console = logger as any; bootstrap(HelloRootDirectiveIsNotCmp, [ {provide: ErrorHandler, useValue: errorHandler} ]).catch((error: Error) => { expect(error).toEqual( new Error(`HelloRootDirectiveIsNotCmp cannot be used as an entry component.`)); async.done(); }); })); it('should retrieve sanitizer', inject([Injector], (injector: Injector) => { const sanitizer: Sanitizer|null = injector.get(Sanitizer, null); if (ivyEnabled) { // In Ivy we don't want to have sanitizer in DI. We use DI only to overwrite the // sanitizer, but not for default one. The default one is pulled in by the Ivy // instructions as needed. expect(sanitizer).toBe(null); } else { // In VE we always need to have Sanitizer available. expect(sanitizer).not.toBe(null); } })); it('should throw if no element is found', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const logger = new MockConsole(); const errorHandler = new ErrorHandler(); (errorHandler as any)._console = logger as any; bootstrap(NonExistentComp, [ {provide: ErrorHandler, useValue: errorHandler} ]).then(null, (reason) => { expect(reason.message) .toContain('The selector "non-existent" did not match any elements'); async.done(); return null; }); })); it('should throw if no provider', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const logger = new MockConsole(); const errorHandler = new ErrorHandler(); (errorHandler as any)._console = logger as any; class IDontExist {} @Component({selector: 'cmp', template: 'Cmp'}) class CustomCmp { constructor(iDontExist: IDontExist) {} } @Component({ selector: 'hello-app', template: '<cmp></cmp>', }) class RootCmp { } @NgModule({declarations: [CustomCmp], exports: [CustomCmp]}) class CustomModule { } bootstrap(RootCmp, [{provide: ErrorHandler, useValue: errorHandler}], [], [ CustomModule ]).then(null, (e: Error) => { let errorMsg: string; if (ivyEnabled) { errorMsg = `R3InjectorError(TestModule)[IDontExist -> IDontExist -> IDontExist]: \n`; } else { errorMsg = `StaticInjectorError(TestModule)[CustomCmp -> IDontExist]: \n` + ' StaticInjectorError(Platform: core)[CustomCmp -> IDontExist]: \n' + ' NullInjectorError: No provider for IDontExist!'; } expect(e.message).toContain(errorMsg); async.done(); return null; }); })); if (getDOM().supportsDOMEvents()) { it('should forward the error to promise when bootstrap fails', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const logger = new MockConsole(); const errorHandler = new ErrorHandler(); (errorHandler as any)._console = logger as any; const refPromise = bootstrap(NonExistentComp, [{provide: ErrorHandler, useValue: errorHandler}]); refPromise.then(null, (reason: any) => { expect(reason.message) .toContain('The selector "non-existent" did not match any elements'); async.done(); }); })); it('should invoke the default exception handler when bootstrap fails', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const logger = new MockConsole(); const errorHandler = new ErrorHandler(); (errorHandler as any)._console = logger as any; const refPromise = bootstrap(NonExistentComp, [{provide: ErrorHandler, useValue: errorHandler}]); refPromise.then(null, (reason) => { expect(logger.res[0].join('#')) .toContain('ERROR#Error: The selector "non-existent" did not match any elements'); async.done(); return null; }); })); } it('should create an injector promise', () => { const refPromise = bootstrap(HelloRootCmp, testProviders); expect(refPromise).toEqual(jasmine.any(Promise)); }); it('should set platform name to browser', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const refPromise = bootstrap(HelloRootCmp, testProviders); refPromise.then((ref) => { expect(isPlatformBrowser(ref.injector.get(PLATFORM_ID))).toBe(true); async.done(); }); })); it('should display hello world', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const refPromise = bootstrap(HelloRootCmp, testProviders); refPromise.then((ref) => { expect(el).toHaveText('hello world!'); expect(el.getAttribute('ng-version')).toEqual(VERSION.full); async.done(); }); })); it('should throw a descriptive error if BrowserModule is installed again via a lazily loaded module', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { @NgModule({imports: [BrowserModule]}) class AsyncModule { } bootstrap(HelloRootCmp, testProviders) .then((ref: ComponentRef<HelloRootCmp>) => { const compiler: Compiler = ref.injector.get(Compiler); return compiler.compileModuleAsync(AsyncModule).then(factory => { expect(() => factory.create(ref.injector)) .toThrowError( `BrowserModule has already been loaded. If you need access to common directives such as NgIf and NgFor from a lazy loaded module, import CommonModule instead.`); }); }) .then(() => async.done(), err => async.fail(err)); })); it('should support multiple calls to bootstrap', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const refPromise1 = bootstrap(HelloRootCmp, testProviders); const refPromise2 = bootstrap(HelloRootCmp2, testProviders); Promise.all([refPromise1, refPromise2]).then((refs) => { expect(el).toHaveText('hello world!'); expect(el2).toHaveText('hello world, again!'); async.done(); }); })); it('should not crash if change detection is invoked when the root component is disposed', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { bootstrap(HelloOnDestroyTickCmp, testProviders).then((ref) => { expect(() => ref.destroy()).not.toThrow(); async.done(); }); })); it('should unregister change detectors when components are disposed', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { bootstrap(HelloRootCmp, testProviders).then((ref) => { const appRef = ref.injector.get(ApplicationRef); ref.destroy(); expect(() => appRef.tick()).not.toThrow(); async.done(); }); })); it('should make the provided bindings available to the application component', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const refPromise = bootstrap( HelloRootCmp3, [testProviders, {provide: 'appBinding', useValue: 'BoundValue'}]); refPromise.then((ref) => { expect(ref.injector.get('appBinding')).toEqual('BoundValue'); async.done(); }); })); it('should not override locale provided during bootstrap', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const refPromise = bootstrap(HelloRootCmp, [testProviders], [{provide: LOCALE_ID, useValue: 'fr-FR'}]); refPromise.then(ref => { expect(ref.injector.get(LOCALE_ID)).toEqual('fr-FR'); async.done(); }); })); it('should avoid cyclic dependencies when root component requires Lifecycle through DI', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const refPromise = bootstrap(HelloRootCmp4, testProviders); refPromise.then((ref) => { const appRef = ref.injector.get(ApplicationRef); expect(appRef).toBeDefined(); async.done(); }); })); it('should run platform initializers', inject([Log, AsyncTestCompleter], (log: Log, async: AsyncTestCompleter) => { const p = createPlatformFactory(platformBrowserDynamic, 'someName', [ {provide: PLATFORM_INITIALIZER, useValue: log.fn('platform_init1'), multi: true}, {provide: PLATFORM_INITIALIZER, useValue: log.fn('platform_init2'), multi: true} ])(); @NgModule({ imports: [BrowserModule], providers: [ {provide: APP_INITIALIZER, useValue: log.fn('app_init1'), multi: true}, {provide: APP_INITIALIZER, useValue: log.fn('app_init2'), multi: true} ] }) class SomeModule { ngDoBootstrap() {} } expect(log.result()).toEqual('platform_init1; platform_init2'); log.clear(); p.bootstrapModule(SomeModule).then(() => { expect(log.result()).toEqual('app_init1; app_init2'); async.done(); }); })); it('should remove styles when transitioning from a server render', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { @Component({ selector: 'root', template: 'root', }) class RootCmp { } @NgModule({ bootstrap: [RootCmp], declarations: [RootCmp], imports: [BrowserModule.withServerTransition({appId: 'my-app'})], }) class TestModule { } // First, set up styles to be removed. const dom = getDOM(); const platform = platformBrowserDynamic(); const document = platform.injector.get(DOCUMENT); const style = dom.createElement('style', document); style.setAttribute('ng-transition', 'my-app'); document.head.appendChild(style); const root = dom.createElement('root', document); document.body.appendChild(root); platform.bootstrapModule(TestModule).then(() => { const styles: HTMLElement[] = Array.prototype.slice.apply(document.getElementsByTagName('style') || []); styles.forEach(style => { expect(style.getAttribute('ng-transition')).not.toBe('my-app'); }); async.done(); }); })); it('should register each application with the testability registry', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const refPromise1: Promise<ComponentRef<any>> = bootstrap(HelloRootCmp, testProviders); const refPromise2: Promise<ComponentRef<any>> = bootstrap(HelloRootCmp2, testProviders); Promise.all([refPromise1, refPromise2]).then((refs: ComponentRef<any>[]) => { const registry = refs[0].injector.get(TestabilityRegistry); const testabilities = [refs[0].injector.get(Testability), refs[1].injector.get(Testability)]; Promise.all(testabilities).then((testabilities: Testability[]) => { expect(registry.findTestabilityInTree(el)).toEqual(testabilities[0]); expect(registry.findTestabilityInTree(el2)).toEqual(testabilities[1]); async.done(); }); }); })); it('should allow to pass schemas', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { bootstrap(HelloCmpUsingCustomElement, testProviders).then((compRef) => { expect(el).toHaveText('hello world!'); async.done(); }); })); describe('change detection', () => { const log: string[] = []; @Component({ selector: 'hello-app', template: '<div id="button-a" (click)="onClick()">{{title}}</div>', }) class CompA { title: string = ''; ngDoCheck() { log.push('CompA:ngDoCheck'); } onClick() { this.title = 'CompA'; log.push('CompA:onClick'); } } @Component({ selector: 'hello-app-2', template: '<div id="button-b" (click)="onClick()">{{title}}</div>', }) class CompB { title: string = ''; ngDoCheck() { log.push('CompB:ngDoCheck'); } onClick() { this.title = 'CompB'; log.push('CompB:onClick'); } } it('should be triggered for all bootstrapped components in case change happens in one of them', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { @NgModule({ imports: [BrowserModule], declarations: [CompA, CompB], bootstrap: [CompA, CompB], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) class TestModuleA { } platformBrowserDynamic().bootstrapModule(TestModuleA).then((ref) => { log.length = 0; el.querySelectorAll('#button-a')[0].click(); expect(log).toContain('CompA:onClick'); expect(log).toContain('CompA:ngDoCheck'); expect(log).toContain('CompB:ngDoCheck'); log.length = 0; el2.querySelectorAll('#button-b')[0].click(); expect(log).toContain('CompB:onClick'); expect(log).toContain('CompA:ngDoCheck'); expect(log).toContain('CompB:ngDoCheck'); async.done(); }); })); it('should work in isolation for each component bootstrapped individually', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { const refPromise1 = bootstrap(CompA); const refPromise2 = bootstrap(CompB); Promise.all([refPromise1, refPromise2]).then((refs) => { log.length = 0; el.querySelectorAll('#button-a')[0].click(); expect(log).toContain('CompA:onClick'); expect(log).toContain('CompA:ngDoCheck'); expect(log).not.toContain('CompB:ngDoCheck'); log.length = 0; el2.querySelectorAll('#button-b')[0].click(); expect(log).toContain('CompB:onClick'); expect(log).toContain('CompB:ngDoCheck'); expect(log).not.toContain('CompA:ngDoCheck'); async.done(); }); })); }); }); }
packages/platform-browser/test/browser/bootstrap_spec.ts
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.9952223896980286, 0.15117570757865906, 0.00016461418999824673, 0.0001761542516760528, 0.3557080030441284 ]
{ "id": 6, "code_window": [ " it('should error if a pipe/directive does not have a `@ngModule` tag', () => {\n", " const log = injector.get('log');\n", " expect(() => {\n", " processor.$process([{ docType: 'directive', id: 'Directive1' }]);\n", " }).toThrowError('Failed to process NgModule relationships.');\n", " expect(log.error).toHaveBeenCalledWith(\n", " '\"Directive1\" has no @ngModule tag. Docs of type \"directive\" must have this tag. - doc \"Directive1\" (directive) ');\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " processor.$process([{ docType: 'directive', id: 'Directive1',\n", " directiveOptions: {selector: 'dir1'} }]);\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "replace", "edit_start_line_idx": 71 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; function plural(n: number): number { let i = Math.floor(Math.abs(n)), t = parseInt(n.toString().replace(/^[^.]*\.?|0+$/g, ''), 10) || 0; if (n === 1 || !(t === 0) && (i === 0 || i === 1)) return 1; return 5; } export default [ 'da', [['a', 'p'], ['AM', 'PM'], u], [['AM', 'PM'], u, u], [ ['S', 'M', 'T', 'O', 'T', 'F', 'L'], ['søn.', 'man.', 'tir.', 'ons.', 'tor.', 'fre.', 'lør.'], ['søndag', 'mandag', 'tirsdag', 'onsdag', 'torsdag', 'fredag', 'lørdag'], ['sø', 'ma', 'ti', 'on', 'to', 'fr', 'lø'] ], [ ['S', 'M', 'T', 'O', 'T', 'F', 'L'], ['søn', 'man', 'tir', 'ons', 'tor', 'fre', 'lør'], ['søndag', 'mandag', 'tirsdag', 'onsdag', 'torsdag', 'fredag', 'lørdag'], ['sø', 'ma', 'ti', 'on', 'to', 'fr', 'lø'] ], [ ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'], ['jan.', 'feb.', 'mar.', 'apr.', 'maj', 'jun.', 'jul.', 'aug.', 'sep.', 'okt.', 'nov.', 'dec.'], [ 'januar', 'februar', 'marts', 'april', 'maj', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'december' ] ], u, [['fKr', 'eKr'], ['f.Kr.', 'e.Kr.'], u], 1, [6, 0], ['dd.MM.y', 'd. MMM y', 'd. MMMM y', 'EEEE \'den\' d. MMMM y'], ['HH.mm', 'HH.mm.ss', 'HH.mm.ss z', 'HH.mm.ss zzzz'], ['{1} {0}', u, '{1} \'kl\'. {0}', u], [',', '.', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', '.'], ['#,##0.###', '#,##0 %', '#,##0.00 ¤', '#E0'], 'DKK', 'kr.', 'dansk krone', { 'AUD': ['AU$', '$'], 'DKK': ['kr.'], 'ISK': [u, 'kr.'], 'JPY': ['JP¥', '¥'], 'NOK': [u, 'kr.'], 'RON': [u, 'L'], 'SEK': [u, 'kr.'], 'THB': ['฿'], 'TWD': ['NT$'], 'USD': ['US$', '$'] }, 'ltr', plural ];
packages/common/locales/da.ts
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.0001777668367139995, 0.00017552768986206502, 0.00017291975382249802, 0.00017596824909560382, 0.000001555808239572798 ]
{ "id": 6, "code_window": [ " it('should error if a pipe/directive does not have a `@ngModule` tag', () => {\n", " const log = injector.get('log');\n", " expect(() => {\n", " processor.$process([{ docType: 'directive', id: 'Directive1' }]);\n", " }).toThrowError('Failed to process NgModule relationships.');\n", " expect(log.error).toHaveBeenCalledWith(\n", " '\"Directive1\" has no @ngModule tag. Docs of type \"directive\" must have this tag. - doc \"Directive1\" (directive) ');\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " processor.$process([{ docType: 'directive', id: 'Directive1',\n", " directiveOptions: {selector: 'dir1'} }]);\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "replace", "edit_start_line_idx": 71 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {browser, by, element, protractor} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../e2e_util/e2e_util'; describe('WebWorkers Todo', function() { afterEach(() => { verifyNoBrowserErrors(); browser.ignoreSynchronization = false; }); const URL = '/'; it('should bootstrap', () => { // This test can't wait for Angular as Testability is not available when using WebWorker browser.ignoreSynchronization = true; browser.get(URL); waitForBootstrap(); expect(element(by.css('#todoapp header')).getText()).toEqual('todos'); }); }); function waitForBootstrap(): void { browser.wait(protractor.until.elementLocated(by.css('todo-app #todoapp')), 15000); }
modules/playground/e2e_test/web_workers/todo/todo_spec.ts
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.000175528708496131, 0.0001738010032568127, 0.00017009541625156999, 0.00017478992231190205, 0.000002171521146010491 ]
{ "id": 7, "code_window": [ " it('should error if a pipe/directive has an @ngModule tag that does not match an NgModule doc', () => {\n", " const log = injector.get('log');\n", " expect(() => {\n", " processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['MissingNgModule'] }]);\n", " }).toThrowError('Failed to process NgModule relationships.');\n", " expect(log.error).toHaveBeenCalledWith(\n", " '\"@ngModule MissingNgModule\" does not match a public NgModule - doc \"Directive1\" (directive) ');\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['MissingNgModule'],\n", " directiveOptions: {selector: 'dir1'} }]);\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "replace", "edit_start_line_idx": 86 }
const testPackage = require('../../helpers/test-package'); const Dgeni = require('dgeni'); describe('processNgModuleDocs processor', () => { let processor; let injector; beforeEach(() => { const dgeni = new Dgeni([testPackage('angular-api-package')]); injector = dgeni.configureInjector(); processor = injector.get('processNgModuleDocs'); }); it('should be available on the injector', () => { expect(processor.$process).toBeDefined(); }); it('should run before the correct processor', () => { expect(processor.$runBefore).toEqual(['createSitemap']); }); it('should run after the correct processor', () => { expect(processor.$runAfter).toEqual(['extractDecoratedClassesProcessor', 'computeIdsProcessor']); }); it('should non-arrayNgModule options to arrays', () => { const docs = [{ docType: 'ngmodule', ngmoduleOptions: { a: ['AAA'], b: 'BBB', c: 42 } }]; processor.$process(docs); expect(docs[0].ngmoduleOptions.a).toEqual(['AAA']); expect(docs[0].ngmoduleOptions.b).toEqual(['BBB']); expect(docs[0].ngmoduleOptions.c).toEqual([42]); }); it('should link directive/pipe docs with their NgModule docs (sorted by id)', () => { const aliasMap = injector.get('aliasMap'); const ngModule1 = { docType: 'ngmodule', id: 'NgModule1', aliases: ['NgModule1'], ngmoduleOptions: {}}; const ngModule2 = { docType: 'ngmodule', id: 'NgModule2', aliases: ['NgModule2'], ngmoduleOptions: {}}; const directive1 = { docType: 'directive', id: 'Directive1', ngModules: ['NgModule1']}; const directive2 = { docType: 'directive', id: 'Directive2', ngModules: ['NgModule2']}; const directive3 = { docType: 'directive', id: 'Directive3', ngModules: ['NgModule1', 'NgModule2']}; const pipe1 = { docType: 'pipe', id: 'Pipe1', ngModules: ['NgModule1']}; const pipe2 = { docType: 'pipe', id: 'Pipe2', ngModules: ['NgModule2']}; const pipe3 = { docType: 'pipe', id: 'Pipe3', ngModules: ['NgModule1', 'NgModule2']}; aliasMap.addDoc(ngModule1); aliasMap.addDoc(ngModule2); processor.$process([ngModule1, pipe2, directive2, directive3, pipe1, ngModule2, directive1, pipe3]); expect(ngModule1.directives).toEqual([directive1, directive3]); expect(ngModule1.pipes).toEqual([pipe1, pipe3]); expect(ngModule2.directives).toEqual([directive2, directive3]); expect(ngModule2.pipes).toEqual([pipe2, pipe3]); expect(directive1.ngModules).toEqual([ngModule1]); expect(directive2.ngModules).toEqual([ngModule2]); expect(directive3.ngModules).toEqual([ngModule1, ngModule2]); expect(pipe1.ngModules).toEqual([ngModule1]); expect(pipe2.ngModules).toEqual([ngModule2]); expect(pipe3.ngModules).toEqual([ngModule1, ngModule2]); }); it('should error if a pipe/directive does not have a `@ngModule` tag', () => { const log = injector.get('log'); expect(() => { processor.$process([{ docType: 'directive', id: 'Directive1' }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"Directive1" has no @ngModule tag. Docs of type "directive" must have this tag. - doc "Directive1" (directive) '); expect(() => { processor.$process([{ docType: 'pipe', id: 'Pipe1' }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"Pipe1" has no @ngModule tag. Docs of type "pipe" must have this tag. - doc "Pipe1" (pipe) '); }); it('should error if a pipe/directive has an @ngModule tag that does not match an NgModule doc', () => { const log = injector.get('log'); expect(() => { processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['MissingNgModule'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule MissingNgModule" does not match a public NgModule - doc "Directive1" (directive) '); expect(() => { processor.$process([{ docType: 'pipe', id: 'Pipe1', ngModules: ['MissingNgModule'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule MissingNgModule" does not match a public NgModule - doc "Pipe1" (pipe) '); }); it('should error if a pipe/directive has an @ngModule tag that matches more than one NgModule doc', () => { const aliasMap = injector.get('aliasMap'); const log = injector.get('log'); const ngModule1 = { docType: 'ngmodule', id: 'NgModule1', aliases: ['NgModuleAlias'], ngmoduleOptions: {}}; const ngModule2 = { docType: 'ngmodule', id: 'NgModule2', aliases: ['NgModuleAlias'], ngmoduleOptions: {}}; aliasMap.addDoc(ngModule1); aliasMap.addDoc(ngModule2); expect(() => { processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['NgModuleAlias'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule NgModuleAlias" is ambiguous. Matches: NgModule1, NgModule2 - doc "Directive1" (directive) '); expect(() => { processor.$process([{ docType: 'pipe', id: 'Pipe1', ngModules: ['NgModuleAlias'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule NgModuleAlias" is ambiguous. Matches: NgModule1, NgModule2 - doc "Pipe1" (pipe) '); }); });
aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js
1
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.9983285069465637, 0.4998466670513153, 0.00017120024131145328, 0.5037474632263184, 0.497775673866272 ]
{ "id": 7, "code_window": [ " it('should error if a pipe/directive has an @ngModule tag that does not match an NgModule doc', () => {\n", " const log = injector.get('log');\n", " expect(() => {\n", " processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['MissingNgModule'] }]);\n", " }).toThrowError('Failed to process NgModule relationships.');\n", " expect(log.error).toHaveBeenCalledWith(\n", " '\"@ngModule MissingNgModule\" does not match a public NgModule - doc \"Directive1\" (directive) ');\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['MissingNgModule'],\n", " directiveOptions: {selector: 'dir1'} }]);\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "replace", "edit_start_line_idx": 86 }
// #docplaster // #docregion , v3 import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; // #enddocregion v3 import { ComposeMessageComponent } from './compose-message/compose-message.component'; // #docregion v3 import { PageNotFoundComponent } from './page-not-found/page-not-found.component'; const appRoutes: Routes = [ // #enddocregion v3 // #docregion compose { path: 'compose', component: ComposeMessageComponent, outlet: 'popup' }, // #enddocregion compose // #docregion v3 { path: '', redirectTo: '/heroes', pathMatch: 'full' }, { path: '**', component: PageNotFoundComponent } ]; @NgModule({ imports: [ RouterModule.forRoot( appRoutes, { enableTracing: true } // <-- debugging purposes only ) ], exports: [ RouterModule ] }) export class AppRoutingModule {}
aio/content/examples/router/src/app/app-routing.module.3.ts
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.00017385318642482162, 0.00017091131303459406, 0.00016711647913325578, 0.00017133780056610703, 0.0000025231495328625897 ]
{ "id": 7, "code_window": [ " it('should error if a pipe/directive has an @ngModule tag that does not match an NgModule doc', () => {\n", " const log = injector.get('log');\n", " expect(() => {\n", " processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['MissingNgModule'] }]);\n", " }).toThrowError('Failed to process NgModule relationships.');\n", " expect(log.error).toHaveBeenCalledWith(\n", " '\"@ngModule MissingNgModule\" does not match a public NgModule - doc \"Directive1\" (directive) ');\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['MissingNgModule'],\n", " directiveOptions: {selector: 'dir1'} }]);\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "replace", "edit_start_line_idx": 86 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // This benchmark uses i18n in its `ExpandingRowSummary` component so `$localize` must be loaded. import '@angular/localize/init'; import {enableProdMode} from '@angular/core'; import {platformBrowser} from '@angular/platform-browser'; import {ExpandingRowBenchmarkModule} from './benchmark'; import {ExpandingRowBenchmarkModuleNgFactory} from './benchmark.ngfactory'; setMode(ExpandingRowBenchmarkModule.hasOwnProperty('ɵmod') ? 'Ivy' : 'ViewEngine'); enableProdMode(); platformBrowser().bootstrapModuleFactory(ExpandingRowBenchmarkModuleNgFactory); function setMode(name: string): void { document.querySelector('#rendererMode')!.textContent = `Render Mode: ${name}`; }
modules/benchmarks/src/expanding_rows/index_aot.ts
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.00017738468886818737, 0.00017383757221978158, 0.00017078709788620472, 0.00017334088624920696, 0.000002716255039558746 ]
{ "id": 7, "code_window": [ " it('should error if a pipe/directive has an @ngModule tag that does not match an NgModule doc', () => {\n", " const log = injector.get('log');\n", " expect(() => {\n", " processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['MissingNgModule'] }]);\n", " }).toThrowError('Failed to process NgModule relationships.');\n", " expect(log.error).toHaveBeenCalledWith(\n", " '\"@ngModule MissingNgModule\" does not match a public NgModule - doc \"Directive1\" (directive) ');\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['MissingNgModule'],\n", " directiveOptions: {selector: 'dir1'} }]);\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "replace", "edit_start_line_idx": 86 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var domino = require('domino'); var mockRequire = require('mock-require'); var nativeTimeout = setTimeout; require('./zone-mix'); mockRequire('electron', { desktopCapturer: { getSources: function(callback) { nativeTimeout(callback); } }, shell: { openExternal: function(callback) { nativeTimeout(callback); } }, ipcRenderer: { on: function(callback) { nativeTimeout(callback); } }, }); require('./zone-patch-electron'); var electron = require('electron'); var zone = Zone.current.fork({name: 'zone'}); zone.run(function() { electron.desktopCapturer.getSources(function() { if (Zone.current.name !== 'zone') { process.exit(1); } }); electron.shell.openExternal(function() { console.log('shell', Zone.current.name); if (Zone.current.name !== 'zone') { process.exit(1); } }); electron.ipcRenderer.on(function() { if (Zone.current.name !== 'zone') { process.exit(1); } }); });
packages/zone.js/test/extra/electron.js
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.00017865774862002581, 0.0001753006799845025, 0.00017184135504066944, 0.00017476966604590416, 0.0000025133108465524856 ]
{ "id": 8, "code_window": [ " aliasMap.addDoc(ngModule2);\n", "\n", " expect(() => {\n", " processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['NgModuleAlias'] }]);\n", " }).toThrowError('Failed to process NgModule relationships.');\n", " expect(log.error).toHaveBeenCalledWith(\n", " '\"@ngModule NgModuleAlias\" is ambiguous. Matches: NgModule1, NgModule2 - doc \"Directive1\" (directive) ');\n", "\n", " expect(() => {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " processor.$process([{\n", " docType: 'directive', id: 'Directive1', ngModules: ['NgModuleAlias'],\n", " directiveOptions: {selector: 'dir1'} }]);\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "replace", "edit_start_line_idx": 107 }
const testPackage = require('../../helpers/test-package'); const Dgeni = require('dgeni'); describe('processNgModuleDocs processor', () => { let processor; let injector; beforeEach(() => { const dgeni = new Dgeni([testPackage('angular-api-package')]); injector = dgeni.configureInjector(); processor = injector.get('processNgModuleDocs'); }); it('should be available on the injector', () => { expect(processor.$process).toBeDefined(); }); it('should run before the correct processor', () => { expect(processor.$runBefore).toEqual(['createSitemap']); }); it('should run after the correct processor', () => { expect(processor.$runAfter).toEqual(['extractDecoratedClassesProcessor', 'computeIdsProcessor']); }); it('should non-arrayNgModule options to arrays', () => { const docs = [{ docType: 'ngmodule', ngmoduleOptions: { a: ['AAA'], b: 'BBB', c: 42 } }]; processor.$process(docs); expect(docs[0].ngmoduleOptions.a).toEqual(['AAA']); expect(docs[0].ngmoduleOptions.b).toEqual(['BBB']); expect(docs[0].ngmoduleOptions.c).toEqual([42]); }); it('should link directive/pipe docs with their NgModule docs (sorted by id)', () => { const aliasMap = injector.get('aliasMap'); const ngModule1 = { docType: 'ngmodule', id: 'NgModule1', aliases: ['NgModule1'], ngmoduleOptions: {}}; const ngModule2 = { docType: 'ngmodule', id: 'NgModule2', aliases: ['NgModule2'], ngmoduleOptions: {}}; const directive1 = { docType: 'directive', id: 'Directive1', ngModules: ['NgModule1']}; const directive2 = { docType: 'directive', id: 'Directive2', ngModules: ['NgModule2']}; const directive3 = { docType: 'directive', id: 'Directive3', ngModules: ['NgModule1', 'NgModule2']}; const pipe1 = { docType: 'pipe', id: 'Pipe1', ngModules: ['NgModule1']}; const pipe2 = { docType: 'pipe', id: 'Pipe2', ngModules: ['NgModule2']}; const pipe3 = { docType: 'pipe', id: 'Pipe3', ngModules: ['NgModule1', 'NgModule2']}; aliasMap.addDoc(ngModule1); aliasMap.addDoc(ngModule2); processor.$process([ngModule1, pipe2, directive2, directive3, pipe1, ngModule2, directive1, pipe3]); expect(ngModule1.directives).toEqual([directive1, directive3]); expect(ngModule1.pipes).toEqual([pipe1, pipe3]); expect(ngModule2.directives).toEqual([directive2, directive3]); expect(ngModule2.pipes).toEqual([pipe2, pipe3]); expect(directive1.ngModules).toEqual([ngModule1]); expect(directive2.ngModules).toEqual([ngModule2]); expect(directive3.ngModules).toEqual([ngModule1, ngModule2]); expect(pipe1.ngModules).toEqual([ngModule1]); expect(pipe2.ngModules).toEqual([ngModule2]); expect(pipe3.ngModules).toEqual([ngModule1, ngModule2]); }); it('should error if a pipe/directive does not have a `@ngModule` tag', () => { const log = injector.get('log'); expect(() => { processor.$process([{ docType: 'directive', id: 'Directive1' }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"Directive1" has no @ngModule tag. Docs of type "directive" must have this tag. - doc "Directive1" (directive) '); expect(() => { processor.$process([{ docType: 'pipe', id: 'Pipe1' }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"Pipe1" has no @ngModule tag. Docs of type "pipe" must have this tag. - doc "Pipe1" (pipe) '); }); it('should error if a pipe/directive has an @ngModule tag that does not match an NgModule doc', () => { const log = injector.get('log'); expect(() => { processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['MissingNgModule'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule MissingNgModule" does not match a public NgModule - doc "Directive1" (directive) '); expect(() => { processor.$process([{ docType: 'pipe', id: 'Pipe1', ngModules: ['MissingNgModule'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule MissingNgModule" does not match a public NgModule - doc "Pipe1" (pipe) '); }); it('should error if a pipe/directive has an @ngModule tag that matches more than one NgModule doc', () => { const aliasMap = injector.get('aliasMap'); const log = injector.get('log'); const ngModule1 = { docType: 'ngmodule', id: 'NgModule1', aliases: ['NgModuleAlias'], ngmoduleOptions: {}}; const ngModule2 = { docType: 'ngmodule', id: 'NgModule2', aliases: ['NgModuleAlias'], ngmoduleOptions: {}}; aliasMap.addDoc(ngModule1); aliasMap.addDoc(ngModule2); expect(() => { processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['NgModuleAlias'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule NgModuleAlias" is ambiguous. Matches: NgModule1, NgModule2 - doc "Directive1" (directive) '); expect(() => { processor.$process([{ docType: 'pipe', id: 'Pipe1', ngModules: ['NgModuleAlias'] }]); }).toThrowError('Failed to process NgModule relationships.'); expect(log.error).toHaveBeenCalledWith( '"@ngModule NgModuleAlias" is ambiguous. Matches: NgModule1, NgModule2 - doc "Pipe1" (pipe) '); }); });
aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js
1
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.22908422350883484, 0.035135965794324875, 0.0001640346017666161, 0.001791353803128004, 0.07310692220926285 ]
{ "id": 8, "code_window": [ " aliasMap.addDoc(ngModule2);\n", "\n", " expect(() => {\n", " processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['NgModuleAlias'] }]);\n", " }).toThrowError('Failed to process NgModule relationships.');\n", " expect(log.error).toHaveBeenCalledWith(\n", " '\"@ngModule NgModuleAlias\" is ambiguous. Matches: NgModule1, NgModule2 - doc \"Directive1\" (directive) ');\n", "\n", " expect(() => {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " processor.$process([{\n", " docType: 'directive', id: 'Directive1', ngModules: ['NgModuleAlias'],\n", " directiveOptions: {selector: 'dir1'} }]);\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "replace", "edit_start_line_idx": 107 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Type} from '../interface/type'; import {Component} from './directives'; /** * Used to resolve resource URLs on `@Component` when used with JIT compilation. * * Example: * ``` * @Component({ * selector: 'my-comp', * templateUrl: 'my-comp.html', // This requires asynchronous resolution * }) * class MyComponent{ * } * * // Calling `renderComponent` will fail because `renderComponent` is a synchronous process * // and `MyComponent`'s `@Component.templateUrl` needs to be resolved asynchronously. * * // Calling `resolveComponentResources()` will resolve `@Component.templateUrl` into * // `@Component.template`, which allows `renderComponent` to proceed in a synchronous manner. * * // Use browser's `fetch()` function as the default resource resolution strategy. * resolveComponentResources(fetch).then(() => { * // After resolution all URLs have been converted into `template` strings. * renderComponent(MyComponent); * }); * * ``` * * NOTE: In AOT the resolution happens during compilation, and so there should be no need * to call this method outside JIT mode. * * @param resourceResolver a function which is responsible for returning a `Promise` to the * contents of the resolved URL. Browser's `fetch()` method is a good default implementation. */ export function resolveComponentResources( resourceResolver: (url: string) => (Promise<string|{text(): Promise<string>}>)): Promise<void> { // Store all promises which are fetching the resources. const componentResolved: Promise<void>[] = []; // Cache so that we don't fetch the same resource more than once. const urlMap = new Map<string, Promise<string>>(); function cachedResourceResolve(url: string): Promise<string> { let promise = urlMap.get(url); if (!promise) { const resp = resourceResolver(url); urlMap.set(url, promise = resp.then(unwrapResponse)); } return promise; } componentResourceResolutionQueue.forEach((component: Component, type: Type<any>) => { const promises: Promise<void>[] = []; if (component.templateUrl) { promises.push(cachedResourceResolve(component.templateUrl).then((template) => { component.template = template; })); } const styleUrls = component.styleUrls; const styles = component.styles || (component.styles = []); const styleOffset = component.styles.length; styleUrls && styleUrls.forEach((styleUrl, index) => { styles.push(''); // pre-allocate array. promises.push(cachedResourceResolve(styleUrl).then((style) => { styles[styleOffset + index] = style; styleUrls.splice(styleUrls.indexOf(styleUrl), 1); if (styleUrls.length == 0) { component.styleUrls = undefined; } })); }); const fullyResolved = Promise.all(promises).then(() => componentDefResolved(type)); componentResolved.push(fullyResolved); }); clearResolutionOfComponentResourcesQueue(); return Promise.all(componentResolved).then(() => undefined); } let componentResourceResolutionQueue = new Map<Type<any>, Component>(); // Track when existing ɵcmp for a Type is waiting on resources. const componentDefPendingResolution = new Set<Type<any>>(); export function maybeQueueResolutionOfComponentResources(type: Type<any>, metadata: Component) { if (componentNeedsResolution(metadata)) { componentResourceResolutionQueue.set(type, metadata); componentDefPendingResolution.add(type); } } export function isComponentDefPendingResolution(type: Type<any>): boolean { return componentDefPendingResolution.has(type); } export function componentNeedsResolution(component: Component): boolean { return !!( (component.templateUrl && !component.hasOwnProperty('template')) || component.styleUrls && component.styleUrls.length); } export function clearResolutionOfComponentResourcesQueue(): Map<Type<any>, Component> { const old = componentResourceResolutionQueue; componentResourceResolutionQueue = new Map(); return old; } export function restoreComponentResolutionQueue(queue: Map<Type<any>, Component>): void { componentDefPendingResolution.clear(); queue.forEach((_, type) => componentDefPendingResolution.add(type)); componentResourceResolutionQueue = queue; } export function isComponentResourceResolutionQueueEmpty() { return componentResourceResolutionQueue.size === 0; } function unwrapResponse(response: string|{text(): Promise<string>}): string|Promise<string> { return typeof response == 'string' ? response : response.text(); } function componentDefResolved(type: Type<any>): void { componentDefPendingResolution.delete(type); }
packages/core/src/metadata/resource_loading.ts
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.00017848391144070774, 0.00017344116349704564, 0.00016143263201229274, 0.00017519688117317855, 0.000005176956619834527 ]
{ "id": 8, "code_window": [ " aliasMap.addDoc(ngModule2);\n", "\n", " expect(() => {\n", " processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['NgModuleAlias'] }]);\n", " }).toThrowError('Failed to process NgModule relationships.');\n", " expect(log.error).toHaveBeenCalledWith(\n", " '\"@ngModule NgModuleAlias\" is ambiguous. Matches: NgModule1, NgModule2 - doc \"Directive1\" (directive) ');\n", "\n", " expect(() => {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " processor.$process([{\n", " docType: 'directive', id: 'Directive1', ngModules: ['NgModuleAlias'],\n", " directiveOptions: {selector: 'dir1'} }]);\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "replace", "edit_start_line_idx": 107 }
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; function plural(n: number): number { if (n === 1) return 1; return 5; } export default [ 'ee-TG', [['ŋ', 'ɣ'], ['ŋdi', 'ɣetrɔ'], u], u, [ ['k', 'd', 'b', 'k', 'y', 'f', 'm'], ['kɔs', 'dzo', 'bla', 'kuɖ', 'yaw', 'fiɖ', 'mem'], ['kɔsiɖa', 'dzoɖa', 'blaɖa', 'kuɖa', 'yawoɖa', 'fiɖa', 'memleɖa'], ['kɔs', 'dzo', 'bla', 'kuɖ', 'yaw', 'fiɖ', 'mem'] ], u, [ ['d', 'd', 't', 'a', 'd', 'm', 's', 'd', 'a', 'k', 'a', 'd'], ['dzv', 'dzd', 'ted', 'afɔ', 'dam', 'mas', 'sia', 'dea', 'any', 'kel', 'ade', 'dzm'], [ 'dzove', 'dzodze', 'tedoxe', 'afɔfĩe', 'dama', 'masa', 'siamlɔm', 'deasiamime', 'anyɔnyɔ', 'kele', 'adeɛmekpɔxe', 'dzome' ] ], u, [['HYV', 'Yŋ'], u, ['Hafi Yesu Va', 'Yesu ŋɔli']], 1, [6, 0], ['M/d/yy', 'MMM d \'lia\', y', 'MMMM d \'lia\' y', 'EEEE, MMMM d \'lia\' y'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{0} {1}', u, u, u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'mnn', ':'], ['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], 'XOF', 'CFA', 'ɣetoɖofe afrikaga CFA franc BCEAO', { 'AUD': ['AU$', '$'], 'GHS': ['GH₵'], 'JPY': ['JP¥', '¥'], 'THB': ['฿'], 'USD': ['US$', '$'] }, 'ltr', plural ];
packages/common/locales/ee-TG.ts
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.0001792409602785483, 0.00017631123773753643, 0.0001731035445118323, 0.00017632490198593587, 0.0000019277285900898278 ]
{ "id": 8, "code_window": [ " aliasMap.addDoc(ngModule2);\n", "\n", " expect(() => {\n", " processor.$process([{ docType: 'directive', id: 'Directive1', ngModules: ['NgModuleAlias'] }]);\n", " }).toThrowError('Failed to process NgModule relationships.');\n", " expect(log.error).toHaveBeenCalledWith(\n", " '\"@ngModule NgModuleAlias\" is ambiguous. Matches: NgModule1, NgModule2 - doc \"Directive1\" (directive) ');\n", "\n", " expect(() => {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " processor.$process([{\n", " docType: 'directive', id: 'Directive1', ngModules: ['NgModuleAlias'],\n", " directiveOptions: {selector: 'dir1'} }]);\n" ], "file_path": "aio/tools/transforms/angular-api-package/processors/processNgModuleDocs.spec.js", "type": "replace", "edit_start_line_idx": 107 }
load("//tools:defaults.bzl", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "testing", testonly = True, srcs = glob([ "**/*.ts", ]), deps = [ "//packages:types", "//packages/compiler-cli/src/ngtsc/file_system", "@npm//typescript", ], )
packages/compiler-cli/src/ngtsc/file_system/testing/BUILD.bazel
0
https://github.com/angular/angular/commit/854bd7d0c8897201901a44f212138b4d42d9849c
[ 0.0001775415294105187, 0.00017689922242425382, 0.00017625691543798894, 0.00017689922242425382, 6.423069862648845e-7 ]
{ "id": 0, "code_window": [ " globals: {\n", " console: 'readonly',\n", " },\n", " overrides: [\n", " {\n", " extends: [\n", " 'plugin:@typescript-eslint/recommended',\n", " 'plugin:import/typescript',\n", " ],\n", " files: ['*.ts', '*.tsx'],\n", " plugins: ['@typescript-eslint/eslint-plugin', 'local'],\n", " rules: {\n", " '@typescript-eslint/array-type': ['error', {default: 'generic'}],\n", " '@typescript-eslint/ban-types': 'error',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " extends: ['plugin:@typescript-eslint/strict', 'plugin:import/typescript'],\n" ], "file_path": ".eslintrc.cjs", "type": "replace", "edit_start_line_idx": 42 }
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* eslint-disable sort-keys */ const fs = require('fs'); const path = require('path'); const {sync: readPkg} = require('read-pkg'); function getPackages() { const PACKAGES_DIR = path.resolve(__dirname, 'packages'); const packages = fs .readdirSync(PACKAGES_DIR) .map(file => path.resolve(PACKAGES_DIR, file)) .filter(f => fs.lstatSync(path.resolve(f)).isDirectory()) .filter(f => fs.existsSync(path.join(path.resolve(f), 'package.json'))); return packages.map(packageDir => { const pkg = readPkg({cwd: packageDir}); return pkg.name; }); } module.exports = { env: { es2020: true, }, extends: [ 'eslint:recommended', 'plugin:markdown/recommended', 'plugin:import/errors', 'plugin:eslint-comments/recommended', 'plugin:prettier/recommended', ], globals: { console: 'readonly', }, overrides: [ { extends: [ 'plugin:@typescript-eslint/recommended', 'plugin:import/typescript', ], files: ['*.ts', '*.tsx'], plugins: ['@typescript-eslint/eslint-plugin', 'local'], rules: { '@typescript-eslint/array-type': ['error', {default: 'generic'}], '@typescript-eslint/ban-types': 'error', '@typescript-eslint/no-inferrable-types': 'error', '@typescript-eslint/no-unused-vars': [ 'error', {argsIgnorePattern: '^_'}, ], '@typescript-eslint/prefer-ts-expect-error': 'error', '@typescript-eslint/no-var-requires': 'off', // TS verifies these 'consistent-return': 'off', 'no-dupe-class-members': 'off', 'no-unused-vars': 'off', // TODO: enable at some point '@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-non-null-assertion': 'off', // TODO: part of "stylistic" rules, remove explicit activation when that lands '@typescript-eslint/no-empty-function': 'error', '@typescript-eslint/no-empty-interface': 'error', }, }, { files: [ 'packages/jest-jasmine2/src/jasmine/Env.ts', 'packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts', 'packages/jest-jasmine2/src/jasmine/Spec.ts', 'packages/jest-jasmine2/src/jasmine/SpyStrategy.ts', 'packages/jest-jasmine2/src/jasmine/Suite.ts', 'packages/jest-jasmine2/src/jasmine/createSpy.ts', 'packages/jest-jasmine2/src/jasmine/jasmineLight.ts', 'packages/jest-mock/src/__tests__/index.test.ts', 'packages/jest-mock/src/index.ts', 'packages/pretty-format/src/__tests__/Immutable.test.ts', 'packages/pretty-format/src/__tests__/prettyFormat.test.ts', ], rules: { 'local/prefer-rest-params-eventually': 'warn', 'prefer-rest-params': 'off', }, }, { files: [ 'packages/expect/src/index.ts', 'packages/jest-fake-timers/src/legacyFakeTimers.ts', 'packages/jest-jasmine2/src/jasmine/Env.ts', 'packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts', 'packages/jest-jasmine2/src/jasmine/Spec.ts', 'packages/jest-jasmine2/src/jasmine/Suite.ts', 'packages/jest-jasmine2/src/jasmine/jasmineLight.ts', 'packages/jest-jasmine2/src/jestExpect.ts', 'packages/jest-resolve/src/resolver.ts', ], rules: { 'local/prefer-spread-eventually': 'warn', 'prefer-spread': 'off', }, }, { files: [ 'e2e/babel-plugin-jest-hoist/__tests__/typescript.test.ts', 'e2e/coverage-remapping/covered.ts', 'packages/expect/src/matchers.ts', 'packages/expect/src/print.ts', 'packages/expect/src/toThrowMatchers.ts', 'packages/expect-utils/src/utils.ts', 'packages/jest-core/src/collectHandles.ts', 'packages/jest-core/src/plugins/UpdateSnapshotsInteractive.ts', 'packages/jest-jasmine2/src/jasmine/SpyStrategy.ts', 'packages/jest-jasmine2/src/jasmine/Suite.ts', 'packages/jest-leak-detector/src/index.ts', 'packages/jest-matcher-utils/src/index.ts', 'packages/jest-mock/src/__tests__/index.test.ts', 'packages/jest-mock/src/index.ts', 'packages/jest-snapshot/src/index.ts', 'packages/jest-snapshot/src/printSnapshot.ts', 'packages/jest-snapshot/src/types.ts', 'packages/jest-util/src/convertDescriptorToString.ts', 'packages/pretty-format/src/index.ts', 'packages/pretty-format/src/plugins/DOMCollection.ts', ], rules: { '@typescript-eslint/ban-types': [ 'error', // TODO: remove these overrides: https://github.com/jestjs/jest/issues/10177 {types: {Function: false, object: false, '{}': false}}, ], 'local/ban-types-eventually': [ 'warn', { types: { // none of these types are in use, so can be errored on Boolean: false, Number: false, Object: false, String: false, Symbol: false, }, }, ], }, }, // 'eslint-plugin-jest' rules for test and test related files { files: [ '**/__mocks__/**', '**/__tests__/**', '**/*.md/**', '**/*.test.*', 'e2e/babel-plugin-jest-hoist/mockFile.js', 'e2e/failures/macros.js', 'e2e/test-in-root/*.js', 'e2e/test-match/test-suites/*', 'packages/test-utils/src/ConditionalTest.ts', ], env: {'jest/globals': true}, excludedFiles: ['**/__typetests__/**'], extends: ['plugin:jest/style'], plugins: ['jest'], rules: { 'jest/no-alias-methods': 'error', 'jest/no-focused-tests': 'error', 'jest/no-identical-title': 'error', 'jest/require-to-throw-message': 'error', 'jest/valid-expect': 'error', }, }, { files: ['e2e/__tests__/*'], rules: { 'jest/no-restricted-jest-methods': [ 'error', { fn: 'Please use fixtures instead of mocks in the end-to-end tests.', mock: 'Please use fixtures instead of mocks in the end-to-end tests.', doMock: 'Please use fixtures instead of mocks in the end-to-end tests.', setMock: 'Please use fixtures instead of mocks in the end-to-end tests.', spyOn: 'Please use fixtures instead of mocks in the end-to-end tests.', }, ], }, }, // to make it more suitable for running on code examples in docs/ folder { files: ['**/*.md/**'], rules: { '@typescript-eslint/no-unused-vars': 'off', '@typescript-eslint/no-empty-function': 'off', '@typescript-eslint/no-namespace': 'off', '@typescript-eslint/no-empty-interface': 'off', 'consistent-return': 'off', 'import/export': 'off', 'import/no-extraneous-dependencies': 'off', 'import/no-unresolved': 'off', 'jest/no-focused-tests': 'off', 'jest/require-to-throw-message': 'off', 'no-console': 'off', 'no-undef': 'off', 'no-unused-vars': 'off', 'sort-keys': 'off', }, }, // demonstration of matchers usage { files: ['**/UsingMatchers.md/**'], rules: { 'jest/prefer-to-be': 'off', }, }, // demonstration of 'jest/valid-expect' rule { files: [ '**/2017-05-06-jest-20-delightful-testing-multi-project-runner.md/**', ], rules: { 'jest/valid-expect': 'off', }, }, // Jest 11 did not had `toHaveLength` matcher { files: ['**/2016-04-12-jest-11.md/**'], rules: { 'jest/prefer-to-have-length': 'off', }, }, // snapshot in an example needs to keep escapes { files: [ '**/2017-02-21-jest-19-immersive-watch-mode-test-platform-improvements.md/**', ], rules: { 'no-useless-escape': 'off', }, }, // snapshots in examples plus inline snapshots need to keep backtick { files: ['**/*.md/**', 'e2e/custom-inline-snapshot-matchers/__tests__/*'], rules: { quotes: [ 'error', 'single', {allowTemplateLiterals: true, avoidEscape: true}, ], }, }, { files: ['docs/**/*', 'website/**/*'], rules: { 'no-redeclare': 'off', 'import/order': 'off', 'import/sort-keys': 'off', 'no-restricted-globals': ['off'], 'sort-keys': 'off', }, }, { files: ['examples/**/*'], rules: { 'no-restricted-imports': 'off', }, }, { files: 'packages/**/*.ts', rules: { '@typescript-eslint/explicit-module-boundary-types': 'error', 'import/no-anonymous-default-export': [ 'error', { allowAnonymousClass: false, allowAnonymousFunction: false, allowArray: false, allowArrowFunction: false, allowCallExpression: false, allowLiteral: false, allowObject: true, }, ], }, }, { files: ['**/__tests__/**', '**/__mocks__/**'], rules: { '@typescript-eslint/ban-ts-comment': 'off', '@typescript-eslint/no-empty-function': 'off', }, }, { files: [ '**/__tests__/**', '**/__mocks__/**', 'packages/jest-jasmine2/src/jasmine/**/*', 'packages/expect/src/jasmineUtils.ts', '**/vendor/**/*', ], rules: { '@typescript-eslint/explicit-module-boundary-types': 'off', }, }, { files: [ 'packages/jest-jasmine2/src/jasmine/**/*', 'packages/expect-utils/src/jasmineUtils.ts', ], rules: { 'eslint-comments/disable-enable-pair': 'off', 'eslint-comments/no-unlimited-disable': 'off', }, }, { files: [ 'e2e/error-on-deprecated/__tests__/*', 'e2e/jasmine-async/__tests__/*', ], globals: { fail: 'readonly', jasmine: 'readonly', pending: 'readonly', }, }, { files: [ 'e2e/**', 'website/**', '**/__benchmarks__/**', '**/__tests__/**', 'packages/jest-types/**/*', '.eslintplugin/**', ], rules: { 'import/no-extraneous-dependencies': 'off', }, }, { files: ['**/__typetests__/**'], rules: { '@typescript-eslint/no-empty-function': 'off', }, }, { env: {node: true}, files: ['*.js', '*.jsx', '*.mjs', '*.cjs'], }, { files: [ 'scripts/*', 'packages/*/__benchmarks__/test.js', 'packages/create-jest/src/runCreate.ts', 'packages/jest-repl/src/cli/runtime-cli.ts', ], rules: { 'no-console': 'off', }, }, { files: [ 'e2e/**', 'examples/**', 'website/**', '**/__mocks__/**', '**/__tests__/**', '**/__typetests__/**', ], rules: { '@typescript-eslint/no-unused-vars': 'off', 'import/no-unresolved': 'off', 'no-console': 'off', 'no-unused-vars': 'off', }, }, ], parser: '@typescript-eslint/parser', parserOptions: { sourceType: 'module', }, plugins: ['import', 'jsdoc', 'unicorn'], rules: { 'accessor-pairs': ['warn', {setWithoutGet: true}], 'block-scoped-var': 'off', 'callback-return': 'off', camelcase: ['off', {properties: 'always'}], complexity: 'off', 'consistent-return': 'warn', 'consistent-this': ['off', 'self'], 'constructor-super': 'error', 'default-case': 'off', 'dot-notation': 'off', eqeqeq: ['off', 'allow-null'], 'eslint-comments/disable-enable-pair': ['error', {allowWholeFile: true}], 'eslint-comments/no-unused-disable': 'error', 'func-names': 'off', 'func-style': ['off', 'declaration'], 'global-require': 'off', 'guard-for-in': 'off', 'handle-callback-err': 'off', 'id-length': 'off', 'id-match': 'off', 'import/no-extraneous-dependencies': [ 'error', { devDependencies: [ '**/__mocks__/**', '**/__tests__/**', '**/__typetests__/**', '**/?(*.)(spec|test).js?(x)', 'scripts/**', 'babel.config.js', 'testSetupFile.js', '.eslintrc.cjs', ], }, ], 'import/no-unresolved': ['error', {ignore: ['fsevents']}], 'import/order': [ 'error', { alphabetize: { order: 'asc', }, // this is the default order except for added `internal` in the middle groups: [ 'builtin', 'external', 'internal', 'parent', 'sibling', 'index', ], 'newlines-between': 'never', }, ], 'init-declarations': 'off', 'jsdoc/check-alignment': 'error', 'lines-around-comment': 'off', 'max-depth': 'off', 'max-nested-callbacks': 'off', 'max-params': 'off', 'max-statements': 'off', 'new-cap': 'off', 'new-parens': 'error', 'newline-after-var': 'off', 'no-alert': 'off', 'no-array-constructor': 'error', 'no-bitwise': 'warn', 'no-caller': 'error', 'no-case-declarations': 'off', 'no-class-assign': 'warn', 'no-cond-assign': 'off', 'no-confusing-arrow': 'off', 'no-console': [ 'warn', {allow: ['warn', 'error', 'time', 'timeEnd', 'timeStamp']}, ], 'no-const-assign': 'error', 'no-constant-condition': 'off', 'no-continue': 'off', 'no-control-regex': 'off', 'no-debugger': 'error', 'no-delete-var': 'error', 'no-div-regex': 'off', 'no-dupe-args': 'error', 'no-dupe-class-members': 'error', 'no-dupe-keys': 'error', 'no-duplicate-case': 'error', 'no-duplicate-imports': 'error', 'no-else-return': 'off', 'no-empty': 'off', 'no-empty-character-class': 'warn', 'no-empty-pattern': 'warn', 'no-eq-null': 'off', 'no-eval': 'error', 'no-ex-assign': 'warn', 'no-extend-native': 'warn', 'no-extra-bind': 'warn', 'no-extra-boolean-cast': 'warn', 'no-fallthrough': 'warn', 'no-floating-decimal': 'error', 'no-func-assign': 'error', 'no-implicit-coercion': 'off', 'no-implied-eval': 'error', 'no-inline-comments': 'off', 'no-inner-declarations': 'off', 'no-invalid-regexp': 'warn', 'no-invalid-this': 'off', 'no-irregular-whitespace': 'error', 'no-iterator': 'off', 'no-label-var': 'warn', 'no-labels': ['error', {allowLoop: true, allowSwitch: true}], 'no-lonely-if': 'off', 'no-loop-func': 'off', 'no-magic-numbers': 'off', 'no-mixed-requires': 'off', 'no-mixed-spaces-and-tabs': 'error', 'no-multi-str': 'error', 'no-multiple-empty-lines': 'off', 'no-native-reassign': ['error', {exceptions: ['Map', 'Set']}], 'no-negated-condition': 'off', 'no-negated-in-lhs': 'error', 'no-nested-ternary': 'off', 'no-new': 'warn', 'no-new-func': 'error', 'no-new-object': 'warn', 'no-new-require': 'off', 'no-new-wrappers': 'warn', 'no-obj-calls': 'error', 'no-octal': 'warn', 'no-octal-escape': 'warn', 'no-param-reassign': 'off', 'no-plusplus': 'off', 'no-process-env': 'off', 'no-process-exit': 'off', 'no-proto': 'error', 'no-prototype-builtins': 'error', 'no-redeclare': 'warn', 'no-regex-spaces': 'warn', 'no-restricted-globals': [ 'error', {message: 'Use `globalThis` instead.', name: 'global'}, ], 'no-restricted-imports': [ 'error', {message: 'Please use graceful-fs instead.', name: 'fs'}, ], 'no-restricted-modules': 'off', 'no-restricted-syntax': 'off', 'no-return-assign': 'off', 'no-script-url': 'error', 'no-self-compare': 'warn', 'no-sequences': 'warn', 'no-shadow': 'off', 'no-shadow-restricted-names': 'warn', 'no-sparse-arrays': 'error', 'no-sync': 'off', 'no-ternary': 'off', 'no-this-before-super': 'error', 'no-throw-literal': 'error', 'no-undef': 'error', 'no-undef-init': 'off', 'no-undefined': 'off', 'no-underscore-dangle': 'off', 'no-unneeded-ternary': 'warn', 'no-unreachable': 'error', 'no-unused-expressions': 'off', 'no-unused-vars': ['error', {argsIgnorePattern: '^_'}], 'no-use-before-define': 'off', 'no-useless-call': 'error', 'no-useless-computed-key': 'error', 'no-useless-concat': 'error', 'no-var': 'error', 'no-void': 'off', 'no-warn-comments': 'off', 'no-with': 'off', 'object-shorthand': 'error', 'one-var': ['warn', {initialized: 'never'}], 'operator-assignment': ['warn', 'always'], 'operator-linebreak': 'off', 'padded-blocks': 'off', 'prefer-arrow-callback': ['error', {allowNamedFunctions: true}], 'prefer-const': 'error', 'prefer-template': 'error', quotes: [ 'error', 'single', {allowTemplateLiterals: false, avoidEscape: true}, ], radix: 'warn', 'require-jsdoc': 'off', 'require-yield': 'off', 'sort-imports': ['error', {ignoreDeclarationSort: true}], 'sort-keys': 'error', 'sort-vars': 'off', 'spaced-comment': ['off', 'always', {exceptions: ['eslint', 'global']}], strict: 'off', 'use-isnan': 'error', 'valid-jsdoc': 'off', 'valid-typeof': 'error', 'vars-on-top': 'off', 'wrap-iife': 'off', 'wrap-regex': 'off', yoda: 'off', 'unicorn/explicit-length-check': 'error', 'unicorn/no-array-for-each': 'error', 'unicorn/no-negated-condition': 'error', 'unicorn/prefer-default-parameters': 'error', 'unicorn/prefer-includes': 'error', 'unicorn/template-indent': 'error', }, settings: { 'import/ignore': ['react-native'], // using `new RegExp` makes sure to escape `/` 'import/internal-regex': new RegExp( getPackages() .map(pkg => `^${pkg}$`) .join('|'), ).source, 'import/resolver': { typescript: {}, }, }, };
.eslintrc.cjs
1
https://github.com/jestjs/jest/commit/bd2305b374ff976e67579f188559d25d69443c30
[ 0.05023975670337677, 0.0009890953078866005, 0.0001629850157769397, 0.00016762380255386233, 0.006306487135589123 ]
{ "id": 0, "code_window": [ " globals: {\n", " console: 'readonly',\n", " },\n", " overrides: [\n", " {\n", " extends: [\n", " 'plugin:@typescript-eslint/recommended',\n", " 'plugin:import/typescript',\n", " ],\n", " files: ['*.ts', '*.tsx'],\n", " plugins: ['@typescript-eslint/eslint-plugin', 'local'],\n", " rules: {\n", " '@typescript-eslint/array-type': ['error', {default: 'generic'}],\n", " '@typescript-eslint/ban-types': 'error',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " extends: ['plugin:@typescript-eslint/strict', 'plugin:import/typescript'],\n" ], "file_path": ".eslintrc.cjs", "type": "replace", "edit_start_line_idx": 42 }
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ import * as path from 'path'; import {types} from 'util'; import execa = require('execa'); import type {SCMAdapter} from './types'; /** * Disable any configuration settings that might change Sapling's default output. * More info in `sl help environment`. _HG_PLAIN is intentional */ const env = {...process.env, HGPLAIN: '1'}; const adapter: SCMAdapter = { findChangedFiles: async (cwd, options) => { const includePaths = options.includePaths ?? []; const args = ['status', '-amnu']; if (options.withAncestor === true) { args.push('--rev', 'first(min(!public() & ::.)^+.^)'); } else if ( options.changedSince != null && options.changedSince.length > 0 ) { args.push('--rev', `ancestor(., ${options.changedSince})`); } else if (options.lastCommit === true) { args.push('--change', '.'); } args.push(...includePaths); let result: execa.ExecaReturnValue; try { result = await execa('sl', args, {cwd, env}); } catch (e) { if (types.isNativeError(e)) { const err = e as execa.ExecaError; // TODO: Should we keep the original `message`? err.message = err.stderr; } throw e; } return result.stdout .split('\n') .filter(s => s !== '') .map(changedPath => path.resolve(cwd, changedPath)); }, getRoot: async cwd => { try { const result = await execa('sl', ['root'], {cwd, env}); return result.stdout; } catch { return null; } }, }; export default adapter;
packages/jest-changed-files/src/sl.ts
0
https://github.com/jestjs/jest/commit/bd2305b374ff976e67579f188559d25d69443c30
[ 0.00017703152843751013, 0.0001708954368950799, 0.0001661683345446363, 0.00017167431360576302, 0.00000352975166606484 ]
{ "id": 0, "code_window": [ " globals: {\n", " console: 'readonly',\n", " },\n", " overrides: [\n", " {\n", " extends: [\n", " 'plugin:@typescript-eslint/recommended',\n", " 'plugin:import/typescript',\n", " ],\n", " files: ['*.ts', '*.tsx'],\n", " plugins: ['@typescript-eslint/eslint-plugin', 'local'],\n", " rules: {\n", " '@typescript-eslint/array-type': ['error', {default: 'generic'}],\n", " '@typescript-eslint/ban-types': 'error',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " extends: ['plugin:@typescript-eslint/strict', 'plugin:import/typescript'],\n" ], "file_path": ".eslintrc.cjs", "type": "replace", "edit_start_line_idx": 42 }
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ export default Symbol('hello!');
e2e/transform/async-transformer/some-symbol.js
0
https://github.com/jestjs/jest/commit/bd2305b374ff976e67579f188559d25d69443c30
[ 0.00017435454356018454, 0.00017435454356018454, 0.00017435454356018454, 0.00017435454356018454, 0 ]
{ "id": 0, "code_window": [ " globals: {\n", " console: 'readonly',\n", " },\n", " overrides: [\n", " {\n", " extends: [\n", " 'plugin:@typescript-eslint/recommended',\n", " 'plugin:import/typescript',\n", " ],\n", " files: ['*.ts', '*.tsx'],\n", " plugins: ['@typescript-eslint/eslint-plugin', 'local'],\n", " rules: {\n", " '@typescript-eslint/array-type': ['error', {default: 'generic'}],\n", " '@typescript-eslint/ban-types': 'error',\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " extends: ['plugin:@typescript-eslint/strict', 'plugin:import/typescript'],\n" ], "file_path": ".eslintrc.cjs", "type": "replace", "edit_start_line_idx": 42 }
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ /* eslint-disable no-duplicate-imports */ import {jest} from '@jest/globals'; import {jest as aliasedJest} from '@jest/globals'; import * as JestGlobals from '@jest/globals'; /* eslint-enable no-duplicate-imports */ import a from '../__test_modules__/a'; import b from '../__test_modules__/b'; import c from '../__test_modules__/c'; import d from '../__test_modules__/d'; // These will be hoisted above imports jest.unmock('../__test_modules__/a'); aliasedJest.unmock('../__test_modules__/b'); JestGlobals.jest.unmock('../__test_modules__/c'); // These will not be hoisted above imports { const jest = {unmock: () => {}}; jest.unmock('../__test_modules__/d'); } // tests test('named import', () => { expect(a._isMockFunction).toBeUndefined(); expect(a()).toBe('unmocked'); }); test('aliased named import', () => { expect(b._isMockFunction).toBeUndefined(); expect(b()).toBe('unmocked'); }); test('namespace import', () => { expect(c._isMockFunction).toBeUndefined(); expect(c()).toBe('unmocked'); }); test('fake jest, shadowed import', () => { expect(d._isMockFunction).toBe(true); expect(d()).toBeUndefined(); });
e2e/babel-plugin-jest-hoist/__tests__/importJest.test.js
0
https://github.com/jestjs/jest/commit/bd2305b374ff976e67579f188559d25d69443c30
[ 0.0001742413587635383, 0.00017082436534110457, 0.00016627214790787548, 0.0001712031225906685, 0.0000024812375158944633 ]
{ "id": 1, "code_window": [ " // TS verifies these\n", " 'consistent-return': 'off',\n", " 'no-dupe-class-members': 'off',\n", " 'no-unused-vars': 'off',\n", " // TODO: enable at some point\n", " '@typescript-eslint/no-explicit-any': 'off',\n", " '@typescript-eslint/no-non-null-assertion': 'off',\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " '@typescript-eslint/no-dynamic-delete': 'off',\n" ], "file_path": ".eslintrc.cjs", "type": "add", "edit_start_line_idx": 62 }
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* eslint-disable sort-keys */ const fs = require('fs'); const path = require('path'); const {sync: readPkg} = require('read-pkg'); function getPackages() { const PACKAGES_DIR = path.resolve(__dirname, 'packages'); const packages = fs .readdirSync(PACKAGES_DIR) .map(file => path.resolve(PACKAGES_DIR, file)) .filter(f => fs.lstatSync(path.resolve(f)).isDirectory()) .filter(f => fs.existsSync(path.join(path.resolve(f), 'package.json'))); return packages.map(packageDir => { const pkg = readPkg({cwd: packageDir}); return pkg.name; }); } module.exports = { env: { es2020: true, }, extends: [ 'eslint:recommended', 'plugin:markdown/recommended', 'plugin:import/errors', 'plugin:eslint-comments/recommended', 'plugin:prettier/recommended', ], globals: { console: 'readonly', }, overrides: [ { extends: [ 'plugin:@typescript-eslint/recommended', 'plugin:import/typescript', ], files: ['*.ts', '*.tsx'], plugins: ['@typescript-eslint/eslint-plugin', 'local'], rules: { '@typescript-eslint/array-type': ['error', {default: 'generic'}], '@typescript-eslint/ban-types': 'error', '@typescript-eslint/no-inferrable-types': 'error', '@typescript-eslint/no-unused-vars': [ 'error', {argsIgnorePattern: '^_'}, ], '@typescript-eslint/prefer-ts-expect-error': 'error', '@typescript-eslint/no-var-requires': 'off', // TS verifies these 'consistent-return': 'off', 'no-dupe-class-members': 'off', 'no-unused-vars': 'off', // TODO: enable at some point '@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-non-null-assertion': 'off', // TODO: part of "stylistic" rules, remove explicit activation when that lands '@typescript-eslint/no-empty-function': 'error', '@typescript-eslint/no-empty-interface': 'error', }, }, { files: [ 'packages/jest-jasmine2/src/jasmine/Env.ts', 'packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts', 'packages/jest-jasmine2/src/jasmine/Spec.ts', 'packages/jest-jasmine2/src/jasmine/SpyStrategy.ts', 'packages/jest-jasmine2/src/jasmine/Suite.ts', 'packages/jest-jasmine2/src/jasmine/createSpy.ts', 'packages/jest-jasmine2/src/jasmine/jasmineLight.ts', 'packages/jest-mock/src/__tests__/index.test.ts', 'packages/jest-mock/src/index.ts', 'packages/pretty-format/src/__tests__/Immutable.test.ts', 'packages/pretty-format/src/__tests__/prettyFormat.test.ts', ], rules: { 'local/prefer-rest-params-eventually': 'warn', 'prefer-rest-params': 'off', }, }, { files: [ 'packages/expect/src/index.ts', 'packages/jest-fake-timers/src/legacyFakeTimers.ts', 'packages/jest-jasmine2/src/jasmine/Env.ts', 'packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts', 'packages/jest-jasmine2/src/jasmine/Spec.ts', 'packages/jest-jasmine2/src/jasmine/Suite.ts', 'packages/jest-jasmine2/src/jasmine/jasmineLight.ts', 'packages/jest-jasmine2/src/jestExpect.ts', 'packages/jest-resolve/src/resolver.ts', ], rules: { 'local/prefer-spread-eventually': 'warn', 'prefer-spread': 'off', }, }, { files: [ 'e2e/babel-plugin-jest-hoist/__tests__/typescript.test.ts', 'e2e/coverage-remapping/covered.ts', 'packages/expect/src/matchers.ts', 'packages/expect/src/print.ts', 'packages/expect/src/toThrowMatchers.ts', 'packages/expect-utils/src/utils.ts', 'packages/jest-core/src/collectHandles.ts', 'packages/jest-core/src/plugins/UpdateSnapshotsInteractive.ts', 'packages/jest-jasmine2/src/jasmine/SpyStrategy.ts', 'packages/jest-jasmine2/src/jasmine/Suite.ts', 'packages/jest-leak-detector/src/index.ts', 'packages/jest-matcher-utils/src/index.ts', 'packages/jest-mock/src/__tests__/index.test.ts', 'packages/jest-mock/src/index.ts', 'packages/jest-snapshot/src/index.ts', 'packages/jest-snapshot/src/printSnapshot.ts', 'packages/jest-snapshot/src/types.ts', 'packages/jest-util/src/convertDescriptorToString.ts', 'packages/pretty-format/src/index.ts', 'packages/pretty-format/src/plugins/DOMCollection.ts', ], rules: { '@typescript-eslint/ban-types': [ 'error', // TODO: remove these overrides: https://github.com/jestjs/jest/issues/10177 {types: {Function: false, object: false, '{}': false}}, ], 'local/ban-types-eventually': [ 'warn', { types: { // none of these types are in use, so can be errored on Boolean: false, Number: false, Object: false, String: false, Symbol: false, }, }, ], }, }, // 'eslint-plugin-jest' rules for test and test related files { files: [ '**/__mocks__/**', '**/__tests__/**', '**/*.md/**', '**/*.test.*', 'e2e/babel-plugin-jest-hoist/mockFile.js', 'e2e/failures/macros.js', 'e2e/test-in-root/*.js', 'e2e/test-match/test-suites/*', 'packages/test-utils/src/ConditionalTest.ts', ], env: {'jest/globals': true}, excludedFiles: ['**/__typetests__/**'], extends: ['plugin:jest/style'], plugins: ['jest'], rules: { 'jest/no-alias-methods': 'error', 'jest/no-focused-tests': 'error', 'jest/no-identical-title': 'error', 'jest/require-to-throw-message': 'error', 'jest/valid-expect': 'error', }, }, { files: ['e2e/__tests__/*'], rules: { 'jest/no-restricted-jest-methods': [ 'error', { fn: 'Please use fixtures instead of mocks in the end-to-end tests.', mock: 'Please use fixtures instead of mocks in the end-to-end tests.', doMock: 'Please use fixtures instead of mocks in the end-to-end tests.', setMock: 'Please use fixtures instead of mocks in the end-to-end tests.', spyOn: 'Please use fixtures instead of mocks in the end-to-end tests.', }, ], }, }, // to make it more suitable for running on code examples in docs/ folder { files: ['**/*.md/**'], rules: { '@typescript-eslint/no-unused-vars': 'off', '@typescript-eslint/no-empty-function': 'off', '@typescript-eslint/no-namespace': 'off', '@typescript-eslint/no-empty-interface': 'off', 'consistent-return': 'off', 'import/export': 'off', 'import/no-extraneous-dependencies': 'off', 'import/no-unresolved': 'off', 'jest/no-focused-tests': 'off', 'jest/require-to-throw-message': 'off', 'no-console': 'off', 'no-undef': 'off', 'no-unused-vars': 'off', 'sort-keys': 'off', }, }, // demonstration of matchers usage { files: ['**/UsingMatchers.md/**'], rules: { 'jest/prefer-to-be': 'off', }, }, // demonstration of 'jest/valid-expect' rule { files: [ '**/2017-05-06-jest-20-delightful-testing-multi-project-runner.md/**', ], rules: { 'jest/valid-expect': 'off', }, }, // Jest 11 did not had `toHaveLength` matcher { files: ['**/2016-04-12-jest-11.md/**'], rules: { 'jest/prefer-to-have-length': 'off', }, }, // snapshot in an example needs to keep escapes { files: [ '**/2017-02-21-jest-19-immersive-watch-mode-test-platform-improvements.md/**', ], rules: { 'no-useless-escape': 'off', }, }, // snapshots in examples plus inline snapshots need to keep backtick { files: ['**/*.md/**', 'e2e/custom-inline-snapshot-matchers/__tests__/*'], rules: { quotes: [ 'error', 'single', {allowTemplateLiterals: true, avoidEscape: true}, ], }, }, { files: ['docs/**/*', 'website/**/*'], rules: { 'no-redeclare': 'off', 'import/order': 'off', 'import/sort-keys': 'off', 'no-restricted-globals': ['off'], 'sort-keys': 'off', }, }, { files: ['examples/**/*'], rules: { 'no-restricted-imports': 'off', }, }, { files: 'packages/**/*.ts', rules: { '@typescript-eslint/explicit-module-boundary-types': 'error', 'import/no-anonymous-default-export': [ 'error', { allowAnonymousClass: false, allowAnonymousFunction: false, allowArray: false, allowArrowFunction: false, allowCallExpression: false, allowLiteral: false, allowObject: true, }, ], }, }, { files: ['**/__tests__/**', '**/__mocks__/**'], rules: { '@typescript-eslint/ban-ts-comment': 'off', '@typescript-eslint/no-empty-function': 'off', }, }, { files: [ '**/__tests__/**', '**/__mocks__/**', 'packages/jest-jasmine2/src/jasmine/**/*', 'packages/expect/src/jasmineUtils.ts', '**/vendor/**/*', ], rules: { '@typescript-eslint/explicit-module-boundary-types': 'off', }, }, { files: [ 'packages/jest-jasmine2/src/jasmine/**/*', 'packages/expect-utils/src/jasmineUtils.ts', ], rules: { 'eslint-comments/disable-enable-pair': 'off', 'eslint-comments/no-unlimited-disable': 'off', }, }, { files: [ 'e2e/error-on-deprecated/__tests__/*', 'e2e/jasmine-async/__tests__/*', ], globals: { fail: 'readonly', jasmine: 'readonly', pending: 'readonly', }, }, { files: [ 'e2e/**', 'website/**', '**/__benchmarks__/**', '**/__tests__/**', 'packages/jest-types/**/*', '.eslintplugin/**', ], rules: { 'import/no-extraneous-dependencies': 'off', }, }, { files: ['**/__typetests__/**'], rules: { '@typescript-eslint/no-empty-function': 'off', }, }, { env: {node: true}, files: ['*.js', '*.jsx', '*.mjs', '*.cjs'], }, { files: [ 'scripts/*', 'packages/*/__benchmarks__/test.js', 'packages/create-jest/src/runCreate.ts', 'packages/jest-repl/src/cli/runtime-cli.ts', ], rules: { 'no-console': 'off', }, }, { files: [ 'e2e/**', 'examples/**', 'website/**', '**/__mocks__/**', '**/__tests__/**', '**/__typetests__/**', ], rules: { '@typescript-eslint/no-unused-vars': 'off', 'import/no-unresolved': 'off', 'no-console': 'off', 'no-unused-vars': 'off', }, }, ], parser: '@typescript-eslint/parser', parserOptions: { sourceType: 'module', }, plugins: ['import', 'jsdoc', 'unicorn'], rules: { 'accessor-pairs': ['warn', {setWithoutGet: true}], 'block-scoped-var': 'off', 'callback-return': 'off', camelcase: ['off', {properties: 'always'}], complexity: 'off', 'consistent-return': 'warn', 'consistent-this': ['off', 'self'], 'constructor-super': 'error', 'default-case': 'off', 'dot-notation': 'off', eqeqeq: ['off', 'allow-null'], 'eslint-comments/disable-enable-pair': ['error', {allowWholeFile: true}], 'eslint-comments/no-unused-disable': 'error', 'func-names': 'off', 'func-style': ['off', 'declaration'], 'global-require': 'off', 'guard-for-in': 'off', 'handle-callback-err': 'off', 'id-length': 'off', 'id-match': 'off', 'import/no-extraneous-dependencies': [ 'error', { devDependencies: [ '**/__mocks__/**', '**/__tests__/**', '**/__typetests__/**', '**/?(*.)(spec|test).js?(x)', 'scripts/**', 'babel.config.js', 'testSetupFile.js', '.eslintrc.cjs', ], }, ], 'import/no-unresolved': ['error', {ignore: ['fsevents']}], 'import/order': [ 'error', { alphabetize: { order: 'asc', }, // this is the default order except for added `internal` in the middle groups: [ 'builtin', 'external', 'internal', 'parent', 'sibling', 'index', ], 'newlines-between': 'never', }, ], 'init-declarations': 'off', 'jsdoc/check-alignment': 'error', 'lines-around-comment': 'off', 'max-depth': 'off', 'max-nested-callbacks': 'off', 'max-params': 'off', 'max-statements': 'off', 'new-cap': 'off', 'new-parens': 'error', 'newline-after-var': 'off', 'no-alert': 'off', 'no-array-constructor': 'error', 'no-bitwise': 'warn', 'no-caller': 'error', 'no-case-declarations': 'off', 'no-class-assign': 'warn', 'no-cond-assign': 'off', 'no-confusing-arrow': 'off', 'no-console': [ 'warn', {allow: ['warn', 'error', 'time', 'timeEnd', 'timeStamp']}, ], 'no-const-assign': 'error', 'no-constant-condition': 'off', 'no-continue': 'off', 'no-control-regex': 'off', 'no-debugger': 'error', 'no-delete-var': 'error', 'no-div-regex': 'off', 'no-dupe-args': 'error', 'no-dupe-class-members': 'error', 'no-dupe-keys': 'error', 'no-duplicate-case': 'error', 'no-duplicate-imports': 'error', 'no-else-return': 'off', 'no-empty': 'off', 'no-empty-character-class': 'warn', 'no-empty-pattern': 'warn', 'no-eq-null': 'off', 'no-eval': 'error', 'no-ex-assign': 'warn', 'no-extend-native': 'warn', 'no-extra-bind': 'warn', 'no-extra-boolean-cast': 'warn', 'no-fallthrough': 'warn', 'no-floating-decimal': 'error', 'no-func-assign': 'error', 'no-implicit-coercion': 'off', 'no-implied-eval': 'error', 'no-inline-comments': 'off', 'no-inner-declarations': 'off', 'no-invalid-regexp': 'warn', 'no-invalid-this': 'off', 'no-irregular-whitespace': 'error', 'no-iterator': 'off', 'no-label-var': 'warn', 'no-labels': ['error', {allowLoop: true, allowSwitch: true}], 'no-lonely-if': 'off', 'no-loop-func': 'off', 'no-magic-numbers': 'off', 'no-mixed-requires': 'off', 'no-mixed-spaces-and-tabs': 'error', 'no-multi-str': 'error', 'no-multiple-empty-lines': 'off', 'no-native-reassign': ['error', {exceptions: ['Map', 'Set']}], 'no-negated-condition': 'off', 'no-negated-in-lhs': 'error', 'no-nested-ternary': 'off', 'no-new': 'warn', 'no-new-func': 'error', 'no-new-object': 'warn', 'no-new-require': 'off', 'no-new-wrappers': 'warn', 'no-obj-calls': 'error', 'no-octal': 'warn', 'no-octal-escape': 'warn', 'no-param-reassign': 'off', 'no-plusplus': 'off', 'no-process-env': 'off', 'no-process-exit': 'off', 'no-proto': 'error', 'no-prototype-builtins': 'error', 'no-redeclare': 'warn', 'no-regex-spaces': 'warn', 'no-restricted-globals': [ 'error', {message: 'Use `globalThis` instead.', name: 'global'}, ], 'no-restricted-imports': [ 'error', {message: 'Please use graceful-fs instead.', name: 'fs'}, ], 'no-restricted-modules': 'off', 'no-restricted-syntax': 'off', 'no-return-assign': 'off', 'no-script-url': 'error', 'no-self-compare': 'warn', 'no-sequences': 'warn', 'no-shadow': 'off', 'no-shadow-restricted-names': 'warn', 'no-sparse-arrays': 'error', 'no-sync': 'off', 'no-ternary': 'off', 'no-this-before-super': 'error', 'no-throw-literal': 'error', 'no-undef': 'error', 'no-undef-init': 'off', 'no-undefined': 'off', 'no-underscore-dangle': 'off', 'no-unneeded-ternary': 'warn', 'no-unreachable': 'error', 'no-unused-expressions': 'off', 'no-unused-vars': ['error', {argsIgnorePattern: '^_'}], 'no-use-before-define': 'off', 'no-useless-call': 'error', 'no-useless-computed-key': 'error', 'no-useless-concat': 'error', 'no-var': 'error', 'no-void': 'off', 'no-warn-comments': 'off', 'no-with': 'off', 'object-shorthand': 'error', 'one-var': ['warn', {initialized: 'never'}], 'operator-assignment': ['warn', 'always'], 'operator-linebreak': 'off', 'padded-blocks': 'off', 'prefer-arrow-callback': ['error', {allowNamedFunctions: true}], 'prefer-const': 'error', 'prefer-template': 'error', quotes: [ 'error', 'single', {allowTemplateLiterals: false, avoidEscape: true}, ], radix: 'warn', 'require-jsdoc': 'off', 'require-yield': 'off', 'sort-imports': ['error', {ignoreDeclarationSort: true}], 'sort-keys': 'error', 'sort-vars': 'off', 'spaced-comment': ['off', 'always', {exceptions: ['eslint', 'global']}], strict: 'off', 'use-isnan': 'error', 'valid-jsdoc': 'off', 'valid-typeof': 'error', 'vars-on-top': 'off', 'wrap-iife': 'off', 'wrap-regex': 'off', yoda: 'off', 'unicorn/explicit-length-check': 'error', 'unicorn/no-array-for-each': 'error', 'unicorn/no-negated-condition': 'error', 'unicorn/prefer-default-parameters': 'error', 'unicorn/prefer-includes': 'error', 'unicorn/template-indent': 'error', }, settings: { 'import/ignore': ['react-native'], // using `new RegExp` makes sure to escape `/` 'import/internal-regex': new RegExp( getPackages() .map(pkg => `^${pkg}$`) .join('|'), ).source, 'import/resolver': { typescript: {}, }, }, };
.eslintrc.cjs
1
https://github.com/jestjs/jest/commit/bd2305b374ff976e67579f188559d25d69443c30
[ 0.9957634210586548, 0.03063035011291504, 0.0001626740413485095, 0.00016839918680489063, 0.16709347069263458 ]
{ "id": 1, "code_window": [ " // TS verifies these\n", " 'consistent-return': 'off',\n", " 'no-dupe-class-members': 'off',\n", " 'no-unused-vars': 'off',\n", " // TODO: enable at some point\n", " '@typescript-eslint/no-explicit-any': 'off',\n", " '@typescript-eslint/no-non-null-assertion': 'off',\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " '@typescript-eslint/no-dynamic-delete': 'off',\n" ], "file_path": ".eslintrc.cjs", "type": "add", "edit_start_line_idx": 62 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`rngBuilder creates a randomizer given seed 1 1`] = ` Array [ 0, 2, 4, 0, 2, 8, 5, 9, 9, 5, ] `; exports[`rngBuilder creates a randomizer given seed 2 1`] = ` Array [ 10, 1, 0, 7, 4, 4, 5, 0, 10, 3, ] `; exports[`rngBuilder creates a randomizer given seed 4 1`] = ` Array [ 8, 10, 3, 2, 5, 2, 3, 4, 8, 5, ] `; exports[`rngBuilder creates a randomizer given seed 8 1`] = ` Array [ 4, 6, 0, 5, 10, 0, 3, 9, 5, 6, ] `; exports[`rngBuilder creates a randomizer given seed 16 1`] = ` Array [ 7, 9, 3, 2, 8, 1, 6, 1, 10, 1, ] `; exports[`shuffleArray shuffles list ["a", "b", "c", "d"] 1`] = ` Array [ "c", "b", "a", "d", ] `; exports[`shuffleArray shuffles list ["a", "b", "c"] 1`] = ` Array [ "b", "a", "c", ] `; exports[`shuffleArray shuffles list ["a", "b"] 1`] = ` Array [ "a", "b", ] `; exports[`shuffleArray shuffles list ["a"] 1`] = ` Array [ "a", ] `;
packages/jest-circus/src/__tests__/__snapshots__/shuffleArray.test.ts.snap
0
https://github.com/jestjs/jest/commit/bd2305b374ff976e67579f188559d25d69443c30
[ 0.00017238687723875046, 0.00016783774481154978, 0.00016104565293062478, 0.000168551632668823, 0.0000030988367143436335 ]
{ "id": 1, "code_window": [ " // TS verifies these\n", " 'consistent-return': 'off',\n", " 'no-dupe-class-members': 'off',\n", " 'no-unused-vars': 'off',\n", " // TODO: enable at some point\n", " '@typescript-eslint/no-explicit-any': 'off',\n", " '@typescript-eslint/no-non-null-assertion': 'off',\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " '@typescript-eslint/no-dynamic-delete': 'off',\n" ], "file_path": ".eslintrc.cjs", "type": "add", "edit_start_line_idx": 62 }
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import type {Config, NewPlugin, Printer, Refs} from '../types'; import { printChildren, printElement, printElementAsLeaf, printProps, } from './lib/markup'; export type ReactTestObject = { $$typeof: symbol; type: string; props?: Record<string, unknown>; children?: null | Array<ReactTestChild>; }; // Child can be `number` in Stack renderer but not in Fiber renderer. type ReactTestChild = ReactTestObject | string | number; const testSymbol = typeof Symbol === 'function' && Symbol.for ? Symbol.for('react.test.json') : 0xea71357; const getPropKeys = (object: ReactTestObject) => { const {props} = object; return props ? Object.keys(props) .filter(key => props[key] !== undefined) .sort() : []; }; export const serialize: NewPlugin['serialize'] = ( object: ReactTestObject, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer, ) => ++depth > config.maxDepth ? printElementAsLeaf(object.type, config) : printElement( object.type, object.props ? printProps( getPropKeys(object), object.props, config, indentation + config.indent, depth, refs, printer, ) : '', object.children ? printChildren( object.children, config, indentation + config.indent, depth, refs, printer, ) : '', config, indentation, ); export const test: NewPlugin['test'] = val => val && val.$$typeof === testSymbol; const plugin: NewPlugin = {serialize, test}; export default plugin;
packages/pretty-format/src/plugins/ReactTestComponent.ts
0
https://github.com/jestjs/jest/commit/bd2305b374ff976e67579f188559d25d69443c30
[ 0.00017521750123705715, 0.0001721306616673246, 0.00016816315473988652, 0.0001725712209008634, 0.00000189201148259599 ]
{ "id": 1, "code_window": [ " // TS verifies these\n", " 'consistent-return': 'off',\n", " 'no-dupe-class-members': 'off',\n", " 'no-unused-vars': 'off',\n", " // TODO: enable at some point\n", " '@typescript-eslint/no-explicit-any': 'off',\n", " '@typescript-eslint/no-non-null-assertion': 'off',\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " '@typescript-eslint/no-dynamic-delete': 'off',\n" ], "file_path": ".eslintrc.cjs", "type": "add", "edit_start_line_idx": 62 }
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; const path = require('path'); let cacheKey; module.exports = { getCacheKey() { return cacheKey; }, getHasteName(filename) { if ( filename.includes('__mocks__') || filename.includes('NoHaste') || filename.includes(`${path.sep}module_dir${path.sep}`) || filename.includes(`${path.sep}sourcemaps${path.sep}`) ) { return undefined; } return filename .substr(filename.lastIndexOf(path.sep) + 1) .replace(/(\.(android|ios|native))?\.js$/, ''); }, setCacheKey(key) { cacheKey = key; }, };
packages/jest-haste-map/src/__tests__/haste_impl.js
0
https://github.com/jestjs/jest/commit/bd2305b374ff976e67579f188559d25d69443c30
[ 0.00017605620087124407, 0.0001722649030853063, 0.0001660542911849916, 0.00017347456014249474, 0.000003873046807711944 ]
{ "id": 2, "code_window": [ " // TODO: enable at some point\n", " '@typescript-eslint/no-explicit-any': 'off',\n", " '@typescript-eslint/no-non-null-assertion': 'off',\n", "\n", " // TODO: part of \"stylistic\" rules, remove explicit activation when that lands\n", " '@typescript-eslint/no-empty-function': 'error',\n", " '@typescript-eslint/no-empty-interface': 'error',\n", " },\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " '@typescript-eslint/no-invalid-void-type': 'off',\n" ], "file_path": ".eslintrc.cjs", "type": "add", "edit_start_line_idx": 65 }
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* eslint-disable local/ban-types-eventually, local/prefer-rest-params-eventually */ import {isPromise} from 'jest-util'; export type MockMetadataType = | 'object' | 'array' | 'regexp' | 'function' | 'constant' | 'collection' | 'null' | 'undefined'; // TODO remove re-export in Jest 30 export type MockFunctionMetadataType = MockMetadataType; export type MockMetadata<T, MetadataType = MockMetadataType> = { ref?: number; members?: Record<string, MockMetadata<T>>; mockImpl?: T; name?: string; refID?: number; type?: MetadataType; value?: T; length?: number; }; // TODO remove re-export in Jest 30 export type MockFunctionMetadata< T = unknown, MetadataType = MockMetadataType, > = MockMetadata<T, MetadataType>; export type ClassLike = {new (...args: any): any}; export type FunctionLike = (...args: any) => any; export type ConstructorLikeKeys<T> = keyof { [K in keyof T as Required<T>[K] extends ClassLike ? K : never]: T[K]; }; export type MethodLikeKeys<T> = keyof { [K in keyof T as Required<T>[K] extends FunctionLike ? K : never]: T[K]; }; export type PropertyLikeKeys<T> = Exclude< keyof T, ConstructorLikeKeys<T> | MethodLikeKeys<T> >; export type MockedClass<T extends ClassLike> = MockInstance< (...args: ConstructorParameters<T>) => Mocked<InstanceType<T>> > & MockedObject<T>; export type MockedFunction<T extends FunctionLike> = MockInstance<T> & MockedObject<T>; type MockedFunctionShallow<T extends FunctionLike> = MockInstance<T> & T; export type MockedObject<T extends object> = { [K in keyof T]: T[K] extends ClassLike ? MockedClass<T[K]> : T[K] extends FunctionLike ? MockedFunction<T[K]> : T[K] extends object ? MockedObject<T[K]> : T[K]; } & T; type MockedObjectShallow<T extends object> = { [K in keyof T]: T[K] extends ClassLike ? MockedClass<T[K]> : T[K] extends FunctionLike ? MockedFunctionShallow<T[K]> : T[K]; } & T; export type Mocked<T> = T extends ClassLike ? MockedClass<T> : T extends FunctionLike ? MockedFunction<T> : T extends object ? MockedObject<T> : T; export type MockedShallow<T> = T extends ClassLike ? MockedClass<T> : T extends FunctionLike ? MockedFunctionShallow<T> : T extends object ? MockedObjectShallow<T> : T; export type UnknownFunction = (...args: Array<unknown>) => unknown; export type UnknownClass = {new (...args: Array<unknown>): unknown}; export type SpiedClass<T extends ClassLike = UnknownClass> = MockInstance< (...args: ConstructorParameters<T>) => InstanceType<T> >; export type SpiedFunction<T extends FunctionLike = UnknownFunction> = MockInstance<(...args: Parameters<T>) => ReturnType<T>>; export type SpiedGetter<T> = MockInstance<() => T>; export type SpiedSetter<T> = MockInstance<(arg: T) => void>; export type Spied<T extends ClassLike | FunctionLike> = T extends ClassLike ? SpiedClass<T> : T extends FunctionLike ? SpiedFunction<T> : never; // TODO in Jest 30 remove `SpyInstance` in favour of `Spied` // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface SpyInstance<T extends FunctionLike = UnknownFunction> extends MockInstance<T> {} /** * All what the internal typings need is to be sure that we have any-function. * `FunctionLike` type ensures that and helps to constrain the type as well. * The default of `UnknownFunction` makes sure that `any`s do not leak to the * user side. For instance, calling `fn()` without implementation will return * a mock of `(...args: Array<unknown>) => unknown` type. If implementation * is provided, its typings are inferred correctly. */ export interface Mock<T extends FunctionLike = UnknownFunction> extends Function, MockInstance<T> { new (...args: Parameters<T>): ReturnType<T>; (...args: Parameters<T>): ReturnType<T>; } type ResolveType<T extends FunctionLike> = ReturnType<T> extends PromiseLike< infer U > ? U : never; type RejectType<T extends FunctionLike> = ReturnType<T> extends PromiseLike<any> ? unknown : never; export interface MockInstance<T extends FunctionLike = UnknownFunction> { _isMockFunction: true; _protoImpl: Function; getMockImplementation(): T | undefined; getMockName(): string; mock: MockFunctionState<T>; mockClear(): this; mockReset(): this; mockRestore(): void; mockImplementation(fn: T): this; mockImplementationOnce(fn: T): this; withImplementation(fn: T, callback: () => Promise<unknown>): Promise<void>; withImplementation(fn: T, callback: () => void): void; mockName(name: string): this; mockReturnThis(): this; mockReturnValue(value: ReturnType<T>): this; mockReturnValueOnce(value: ReturnType<T>): this; mockResolvedValue(value: ResolveType<T>): this; mockResolvedValueOnce(value: ResolveType<T>): this; mockRejectedValue(value: RejectType<T>): this; mockRejectedValueOnce(value: RejectType<T>): this; } export interface Replaced<T = unknown> { /** * Restore property to its original value known at the time of mocking. */ restore(): void; /** * Change the value of the property. */ replaceValue(value: T): this; } type ReplacedPropertyRestorer<T extends object, K extends keyof T> = { (): void; object: T; property: K; replaced: Replaced<T[K]>; }; type MockFunctionResultIncomplete = { type: 'incomplete'; /** * Result of a single call to a mock function that has not yet completed. * This occurs if you test the result from within the mock function itself, * or from within a function that was called by the mock. */ value: undefined; }; type MockFunctionResultReturn<T extends FunctionLike = UnknownFunction> = { type: 'return'; /** * Result of a single call to a mock function that returned. */ value: ReturnType<T>; }; type MockFunctionResultThrow = { type: 'throw'; /** * Result of a single call to a mock function that threw. */ value: unknown; }; type MockFunctionResult<T extends FunctionLike = UnknownFunction> = | MockFunctionResultIncomplete | MockFunctionResultReturn<T> | MockFunctionResultThrow; type MockFunctionState<T extends FunctionLike = UnknownFunction> = { /** * List of the call arguments of all calls that have been made to the mock. */ calls: Array<Parameters<T>>; /** * List of all the object instances that have been instantiated from the mock. */ instances: Array<ReturnType<T>>; /** * List of all the function contexts that have been applied to calls to the mock. */ contexts: Array<ThisParameterType<T>>; /** * List of the call order indexes of the mock. Jest is indexing the order of * invocations of all mocks in a test file. The index is starting with `1`. */ invocationCallOrder: Array<number>; /** * List of the call arguments of the last call that was made to the mock. * If the function was not called, it will return `undefined`. */ lastCall?: Parameters<T>; /** * List of the results of all calls that have been made to the mock. */ results: Array<MockFunctionResult<T>>; }; type MockFunctionConfig = { mockImpl: Function | undefined; mockName: string; specificMockImpls: Array<Function>; }; const MOCK_CONSTRUCTOR_NAME = 'mockConstructor'; const FUNCTION_NAME_RESERVED_PATTERN = /[\s!-/:-@[-`{-~]/; const FUNCTION_NAME_RESERVED_REPLACE = new RegExp( FUNCTION_NAME_RESERVED_PATTERN.source, 'g', ); const RESERVED_KEYWORDS = new Set([ 'arguments', 'await', 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'enum', 'eval', 'export', 'extends', 'false', 'finally', 'for', 'function', 'if', 'implements', 'import', 'in', 'instanceof', 'interface', 'let', 'new', 'null', 'package', 'private', 'protected', 'public', 'return', 'static', 'super', 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'var', 'void', 'while', 'with', 'yield', ]); function matchArity(fn: Function, length: number): Function { let mockConstructor; switch (length) { case 1: mockConstructor = function (this: unknown, _a: unknown) { return fn.apply(this, arguments); }; break; case 2: mockConstructor = function (this: unknown, _a: unknown, _b: unknown) { return fn.apply(this, arguments); }; break; case 3: mockConstructor = function ( this: unknown, _a: unknown, _b: unknown, _c: unknown, ) { return fn.apply(this, arguments); }; break; case 4: mockConstructor = function ( this: unknown, _a: unknown, _b: unknown, _c: unknown, _d: unknown, ) { return fn.apply(this, arguments); }; break; case 5: mockConstructor = function ( this: unknown, _a: unknown, _b: unknown, _c: unknown, _d: unknown, _e: unknown, ) { return fn.apply(this, arguments); }; break; case 6: mockConstructor = function ( this: unknown, _a: unknown, _b: unknown, _c: unknown, _d: unknown, _e: unknown, _f: unknown, ) { return fn.apply(this, arguments); }; break; case 7: mockConstructor = function ( this: unknown, _a: unknown, _b: unknown, _c: unknown, _d: unknown, _e: unknown, _f: unknown, _g: unknown, ) { return fn.apply(this, arguments); }; break; case 8: mockConstructor = function ( this: unknown, _a: unknown, _b: unknown, _c: unknown, _d: unknown, _e: unknown, _f: unknown, _g: unknown, _h: unknown, ) { return fn.apply(this, arguments); }; break; case 9: mockConstructor = function ( this: unknown, _a: unknown, _b: unknown, _c: unknown, _d: unknown, _e: unknown, _f: unknown, _g: unknown, _h: unknown, _i: unknown, ) { return fn.apply(this, arguments); }; break; default: mockConstructor = function (this: unknown) { return fn.apply(this, arguments); }; break; } return mockConstructor; } function getObjectType(value: unknown): string { return Object.prototype.toString.apply(value).slice(8, -1); } function getType(ref?: unknown): MockMetadataType | null { const typeName = getObjectType(ref); if ( typeName === 'Function' || typeName === 'AsyncFunction' || typeName === 'GeneratorFunction' || typeName === 'AsyncGeneratorFunction' ) { return 'function'; } else if (Array.isArray(ref)) { return 'array'; } else if (typeName === 'Object' || typeName === 'Module') { return 'object'; } else if ( typeName === 'Number' || typeName === 'String' || typeName === 'Boolean' || typeName === 'Symbol' ) { return 'constant'; } else if ( typeName === 'Map' || typeName === 'WeakMap' || typeName === 'Set' ) { return 'collection'; } else if (typeName === 'RegExp') { return 'regexp'; } else if (ref === undefined) { return 'undefined'; } else if (ref === null) { return 'null'; } else { return null; } } function isReadonlyProp(object: unknown, prop: string): boolean { if ( prop === 'arguments' || prop === 'caller' || prop === 'callee' || prop === 'name' || prop === 'length' ) { const typeName = getObjectType(object); return ( typeName === 'Function' || typeName === 'AsyncFunction' || typeName === 'GeneratorFunction' || typeName === 'AsyncGeneratorFunction' ); } if ( prop === 'source' || prop === 'global' || prop === 'ignoreCase' || prop === 'multiline' ) { return getObjectType(object) === 'RegExp'; } return false; } export class ModuleMocker { private readonly _environmentGlobal: typeof globalThis; private _mockState: WeakMap<Mock, MockFunctionState>; private _mockConfigRegistry: WeakMap<Function, MockFunctionConfig>; private _spyState: Set<() => void>; private _invocationCallCounter: number; /** * @see README.md * @param global Global object of the test environment, used to create * mocks */ constructor(global: typeof globalThis) { this._environmentGlobal = global; this._mockState = new WeakMap(); this._mockConfigRegistry = new WeakMap(); this._spyState = new Set(); this._invocationCallCounter = 1; } private _getSlots(object?: Record<string, any>): Array<string> { if (!object) { return []; } const slots = new Set<string>(); const EnvObjectProto = this._environmentGlobal.Object.prototype; const EnvFunctionProto = this._environmentGlobal.Function.prototype; const EnvRegExpProto = this._environmentGlobal.RegExp.prototype; // Also check the builtins in the current context as they leak through // core node modules. const ObjectProto = Object.prototype; const FunctionProto = Function.prototype; const RegExpProto = RegExp.prototype; // Properties of Object.prototype, Function.prototype and RegExp.prototype // are never reported as slots while ( object != null && object !== EnvObjectProto && object !== EnvFunctionProto && object !== EnvRegExpProto && object !== ObjectProto && object !== FunctionProto && object !== RegExpProto ) { const ownNames = Object.getOwnPropertyNames(object); for (let i = 0; i < ownNames.length; i++) { const prop = ownNames[i]; if (!isReadonlyProp(object, prop)) { const propDesc = Object.getOwnPropertyDescriptor(object, prop); if ((propDesc !== undefined && !propDesc.get) || object.__esModule) { slots.add(prop); } } } object = Object.getPrototypeOf(object); } return Array.from(slots); } private _ensureMockConfig(f: Mock): MockFunctionConfig { let config = this._mockConfigRegistry.get(f); if (!config) { config = this._defaultMockConfig(); this._mockConfigRegistry.set(f, config); } return config; } private _ensureMockState<T extends UnknownFunction>( f: Mock<T>, ): MockFunctionState<T> { let state = this._mockState.get(f); if (!state) { state = this._defaultMockState(); this._mockState.set(f, state); } if (state.calls.length > 0) { state.lastCall = state.calls[state.calls.length - 1]; } return state; } private _defaultMockConfig(): MockFunctionConfig { return { mockImpl: undefined, mockName: 'jest.fn()', specificMockImpls: [], }; } private _defaultMockState(): MockFunctionState { return { calls: [], contexts: [], instances: [], invocationCallOrder: [], results: [], }; } private _makeComponent<T extends Record<string, any>>( metadata: MockMetadata<T, 'object'>, restore?: () => void, ): T; private _makeComponent<T extends Array<unknown>>( metadata: MockMetadata<T, 'array'>, restore?: () => void, ): T; private _makeComponent<T extends RegExp>( metadata: MockMetadata<T, 'regexp'>, restore?: () => void, ): T; private _makeComponent<T>( metadata: MockMetadata<T, 'constant' | 'collection' | 'null' | 'undefined'>, restore?: () => void, ): T; private _makeComponent<T extends UnknownFunction>( metadata: MockMetadata<T, 'function'>, restore?: () => void, ): Mock<T>; private _makeComponent<T extends UnknownFunction>( metadata: MockMetadata<T>, restore?: () => void, ): Record<string, any> | Array<unknown> | RegExp | T | Mock | undefined { if (metadata.type === 'object') { return new this._environmentGlobal.Object(); } else if (metadata.type === 'array') { return new this._environmentGlobal.Array(); } else if (metadata.type === 'regexp') { return new this._environmentGlobal.RegExp(''); } else if ( metadata.type === 'constant' || metadata.type === 'collection' || metadata.type === 'null' || metadata.type === 'undefined' ) { return metadata.value; } else if (metadata.type === 'function') { const prototype = (metadata.members && metadata.members.prototype && metadata.members.prototype.members) || {}; const prototypeSlots = this._getSlots(prototype); // eslint-disable-next-line @typescript-eslint/no-this-alias const mocker = this; const mockConstructor = matchArity(function ( this: ReturnType<T>, ...args: Parameters<T> ) { const mockState = mocker._ensureMockState(f); const mockConfig = mocker._ensureMockConfig(f); mockState.instances.push(this); mockState.contexts.push(this); mockState.calls.push(args); // Create and record an "incomplete" mock result immediately upon // calling rather than waiting for the mock to return. This avoids // issues caused by recursion where results can be recorded in the // wrong order. const mockResult: MockFunctionResult = { type: 'incomplete', value: undefined, }; mockState.results.push(mockResult); mockState.invocationCallOrder.push(mocker._invocationCallCounter++); // Will be set to the return value of the mock if an error is not thrown let finalReturnValue; // Will be set to the error that is thrown by the mock (if it throws) let thrownError; // Will be set to true if the mock throws an error. The presence of a // value in `thrownError` is not a 100% reliable indicator because a // function could throw a value of undefined. let callDidThrowError = false; try { // The bulk of the implementation is wrapped in an immediately // executed arrow function so the return value of the mock function // can be easily captured and recorded, despite the many separate // return points within the logic. finalReturnValue = (() => { if (this instanceof f) { // This is probably being called as a constructor for (const slot of prototypeSlots) { // Copy prototype methods to the instance to make // it easier to interact with mock instance call and // return values if (prototype[slot].type === 'function') { // @ts-expect-error no index signature const protoImpl = this[slot]; // @ts-expect-error no index signature this[slot] = mocker.generateFromMetadata(prototype[slot]); // @ts-expect-error no index signature this[slot]._protoImpl = protoImpl; } } // Run the mock constructor implementation const mockImpl = mockConfig.specificMockImpls.length > 0 ? mockConfig.specificMockImpls.shift() : mockConfig.mockImpl; return mockImpl && mockImpl.apply(this, arguments); } // If mockImplementationOnce()/mockImplementation() is last set, // implementation use the mock let specificMockImpl = mockConfig.specificMockImpls.shift(); if (specificMockImpl === undefined) { specificMockImpl = mockConfig.mockImpl; } if (specificMockImpl) { return specificMockImpl.apply(this, arguments); } // Otherwise use prototype implementation if (f._protoImpl) { return f._protoImpl.apply(this, arguments); } return undefined; })(); } catch (error) { // Store the thrown error so we can record it, then re-throw it. thrownError = error; callDidThrowError = true; throw error; } finally { // Record the result of the function. // NOTE: Intentionally NOT pushing/indexing into the array of mock // results here to avoid corrupting results data if mockClear() // is called during the execution of the mock. // @ts-expect-error reassigning 'incomplete' mockResult.type = callDidThrowError ? 'throw' : 'return'; mockResult.value = callDidThrowError ? thrownError : finalReturnValue; } return finalReturnValue; }, metadata.length || 0); const f = this._createMockFunction(metadata, mockConstructor) as Mock; f._isMockFunction = true; f.getMockImplementation = () => this._ensureMockConfig(f).mockImpl as T; if (typeof restore === 'function') { this._spyState.add(restore); } this._mockState.set(f, this._defaultMockState()); this._mockConfigRegistry.set(f, this._defaultMockConfig()); Object.defineProperty(f, 'mock', { configurable: false, enumerable: true, get: () => this._ensureMockState(f), set: val => this._mockState.set(f, val), }); f.mockClear = () => { this._mockState.delete(f); return f; }; f.mockReset = () => { f.mockClear(); this._mockConfigRegistry.delete(f); return f; }; f.mockRestore = () => { f.mockReset(); return restore ? restore() : undefined; }; f.mockReturnValueOnce = (value: ReturnType<T>) => // next function call will return this value or default return value f.mockImplementationOnce(() => value); f.mockResolvedValueOnce = (value: ResolveType<T>) => f.mockImplementationOnce(() => this._environmentGlobal.Promise.resolve(value), ); f.mockRejectedValueOnce = (value: unknown) => f.mockImplementationOnce(() => this._environmentGlobal.Promise.reject(value), ); f.mockReturnValue = (value: ReturnType<T>) => // next function call will return specified return value or this one f.mockImplementation(() => value); f.mockResolvedValue = (value: ResolveType<T>) => f.mockImplementation(() => this._environmentGlobal.Promise.resolve(value), ); f.mockRejectedValue = (value: unknown) => f.mockImplementation(() => this._environmentGlobal.Promise.reject(value), ); f.mockImplementationOnce = (fn: T) => { // next function call will use this mock implementation return value // or default mock implementation return value const mockConfig = this._ensureMockConfig(f); mockConfig.specificMockImpls.push(fn); return f; }; f.withImplementation = withImplementation.bind(this); function withImplementation(fn: T, callback: () => void): void; function withImplementation( fn: T, callback: () => Promise<unknown>, ): Promise<void>; function withImplementation( this: ModuleMocker, fn: T, callback: (() => void) | (() => Promise<unknown>), ): void | Promise<void> { // Remember previous mock implementation, then set new one const mockConfig = this._ensureMockConfig(f); const previousImplementation = mockConfig.mockImpl; const previousSpecificImplementations = mockConfig.specificMockImpls; mockConfig.mockImpl = fn; mockConfig.specificMockImpls = []; const returnedValue = callback(); if (isPromise(returnedValue)) { return returnedValue.then(() => { mockConfig.mockImpl = previousImplementation; mockConfig.specificMockImpls = previousSpecificImplementations; }); } else { mockConfig.mockImpl = previousImplementation; mockConfig.specificMockImpls = previousSpecificImplementations; } } f.mockImplementation = (fn: T) => { // next function call will use mock implementation return value const mockConfig = this._ensureMockConfig(f); mockConfig.mockImpl = fn; return f; }; f.mockReturnThis = () => f.mockImplementation(function (this: ReturnType<T>) { return this; }); f.mockName = (name: string) => { if (name) { const mockConfig = this._ensureMockConfig(f); mockConfig.mockName = name; } return f; }; f.getMockName = () => { const mockConfig = this._ensureMockConfig(f); return mockConfig.mockName || 'jest.fn()'; }; if (metadata.mockImpl) { f.mockImplementation(metadata.mockImpl); } return f; } else { const unknownType = metadata.type || 'undefined type'; throw new Error(`Unrecognized type ${unknownType}`); } } private _createMockFunction<T extends UnknownFunction>( metadata: MockMetadata<T>, mockConstructor: Function, ): Function { let name = metadata.name; if (!name) { return mockConstructor; } // Preserve `name` property of mocked function. const boundFunctionPrefix = 'bound '; let bindCall = ''; // if-do-while for perf reasons. The common case is for the if to fail. if (name.startsWith(boundFunctionPrefix)) { do { name = name.substring(boundFunctionPrefix.length); // Call bind() just to alter the function name. bindCall = '.bind(null)'; } while (name && name.startsWith(boundFunctionPrefix)); } // Special case functions named `mockConstructor` to guard for infinite loops if (name === MOCK_CONSTRUCTOR_NAME) { return mockConstructor; } if ( // It's a syntax error to define functions with a reserved keyword as name RESERVED_KEYWORDS.has(name) || // It's also a syntax error to define functions with a name that starts with a number /^\d/.test(name) ) { name = `$${name}`; } // It's also a syntax error to define a function with a reserved character // as part of it's name. if (FUNCTION_NAME_RESERVED_PATTERN.test(name)) { name = name.replace(FUNCTION_NAME_RESERVED_REPLACE, '$'); } const body = `return function ${name}() {` + ` return ${MOCK_CONSTRUCTOR_NAME}.apply(this,arguments);` + `}${bindCall}`; const createConstructor = new this._environmentGlobal.Function( MOCK_CONSTRUCTOR_NAME, body, ); return createConstructor(mockConstructor); } private _generateMock<T>( metadata: MockMetadata<T>, callbacks: Array<Function>, refs: Record< number, Record<string, any> | Array<unknown> | RegExp | T | Mock | undefined >, ): Mocked<T> { // metadata not compatible but it's the same type, maybe problem with // overloading of _makeComponent and not _generateMock? // @ts-expect-error - unsure why TSC complains here? const mock = this._makeComponent(metadata); if (metadata.refID != null) { refs[metadata.refID] = mock; } for (const slot of this._getSlots(metadata.members)) { const slotMetadata = (metadata.members && metadata.members[slot]) || {}; if (slotMetadata.ref == null) { mock[slot] = this._generateMock(slotMetadata, callbacks, refs); } else { callbacks.push( (function (ref) { return () => (mock[slot] = refs[ref]); })(slotMetadata.ref), ); } } if ( metadata.type !== 'undefined' && metadata.type !== 'null' && mock.prototype && typeof mock.prototype === 'object' ) { mock.prototype.constructor = mock; } return mock as Mocked<T>; } /** * Check whether the given property of an object has been already replaced. */ private _findReplacedProperty<T extends object, K extends keyof T>( object: T, propertyKey: K, ): ReplacedPropertyRestorer<T, K> | undefined { for (const spyState of this._spyState) { if ( 'object' in spyState && 'property' in spyState && spyState.object === object && spyState.property === propertyKey ) { return spyState as ReplacedPropertyRestorer<T, K>; } } return; } /** * @see README.md * @param metadata Metadata for the mock in the schema returned by the * getMetadata method of this module. */ generateFromMetadata<T>(metadata: MockMetadata<T>): Mocked<T> { const callbacks: Array<Function> = []; const refs = {}; const mock = this._generateMock<T>(metadata, callbacks, refs); for (const setter of callbacks) setter(); return mock; } /** * @see README.md * @param component The component for which to retrieve metadata. */ getMetadata<T = unknown>( component: T, _refs?: Map<T, number>, ): MockMetadata<T> | null { const refs = _refs || new Map<T, number>(); const ref = refs.get(component); if (ref != null) { return {ref}; } const type = getType(component); if (!type) { return null; } const metadata: MockMetadata<T> = {type}; if ( type === 'constant' || type === 'collection' || type === 'undefined' || type === 'null' ) { metadata.value = component; return metadata; } else if (type === 'function') { // @ts-expect-error component is a function so it has a name, but not // necessarily a string: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#function_names_in_classes const componentName = component.name; if (typeof componentName === 'string') { metadata.name = componentName; } if (this.isMockFunction(component)) { metadata.mockImpl = component.getMockImplementation() as T; } } metadata.refID = refs.size; refs.set(component, metadata.refID); let members: Record<string, MockMetadata<T>> | null = null; // Leave arrays alone if (type !== 'array') { // @ts-expect-error component is object for (const slot of this._getSlots(component)) { if ( type === 'function' && this.isMockFunction(component) && slot.match(/^mock/) ) { continue; } // @ts-expect-error no index signature const slotMetadata = this.getMetadata<T>(component[slot], refs); if (slotMetadata) { if (!members) { members = {}; } members[slot] = slotMetadata; } } } if (members) { metadata.members = members; } return metadata; } isMockFunction<T extends FunctionLike = UnknownFunction>( fn: MockInstance<T>, ): fn is MockInstance<T>; isMockFunction<P extends Array<unknown>, R>( fn: (...args: P) => R, ): fn is Mock<(...args: P) => R>; isMockFunction(fn: unknown): fn is Mock<UnknownFunction>; isMockFunction(fn: unknown): fn is Mock<UnknownFunction> { return fn != null && (fn as Mock)._isMockFunction === true; } fn<T extends FunctionLike = UnknownFunction>(implementation?: T): Mock<T> { const length = implementation ? implementation.length : 0; const fn = this._makeComponent<T>({ length, type: 'function', }); if (implementation) { fn.mockImplementation(implementation); } return fn; } spyOn< T extends object, K extends PropertyLikeKeys<T>, V extends Required<T>[K], A extends 'get' | 'set', >( object: T, methodKey: K, accessType: A, ): A extends 'get' ? SpiedGetter<V> : A extends 'set' ? SpiedSetter<V> : never; spyOn< T extends object, K extends ConstructorLikeKeys<T> | MethodLikeKeys<T>, V extends Required<T>[K], >( object: T, methodKey: K, ): V extends ClassLike | FunctionLike ? Spied<V> : never; spyOn<T extends object>( object: T, methodKey: keyof T, accessType?: 'get' | 'set', ): MockInstance { if ( object == null || (typeof object !== 'object' && typeof object !== 'function') ) { throw new Error( `Cannot use spyOn on a primitive value; ${this._typeOf(object)} given`, ); } if (methodKey == null) { throw new Error('No property name supplied'); } if (accessType) { return this._spyOnProperty(object, methodKey, accessType); } const original = object[methodKey]; if (!original) { throw new Error( `Property \`${String( methodKey, )}\` does not exist in the provided object`, ); } if (!this.isMockFunction(original)) { if (typeof original !== 'function') { throw new Error( `Cannot spy on the \`${String( methodKey, )}\` property because it is not a function; ${this._typeOf( original, )} given instead.${ typeof original === 'object' ? '' : ` If you are trying to mock a property, use \`jest.replaceProperty(object, '${String( methodKey, )}', value)\` instead.` }`, ); } const isMethodOwner = Object.prototype.hasOwnProperty.call( object, methodKey, ); let descriptor = Object.getOwnPropertyDescriptor(object, methodKey); let proto = Object.getPrototypeOf(object); while (!descriptor && proto !== null) { descriptor = Object.getOwnPropertyDescriptor(proto, methodKey); proto = Object.getPrototypeOf(proto); } let mock: Mock; if (descriptor && descriptor.get) { const originalGet = descriptor.get; mock = this._makeComponent({type: 'function'}, () => { descriptor!.get = originalGet; Object.defineProperty(object, methodKey, descriptor!); }); descriptor.get = () => mock; Object.defineProperty(object, methodKey, descriptor); } else { mock = this._makeComponent({type: 'function'}, () => { if (isMethodOwner) { object[methodKey] = original; } else { delete object[methodKey]; } }); // @ts-expect-error overriding original method with a Mock object[methodKey] = mock; } mock.mockImplementation(function (this: unknown) { return original.apply(this, arguments); }); } return object[methodKey] as Mock; } private _spyOnProperty<T extends object>( object: T, propertyKey: keyof T, accessType: 'get' | 'set', ): MockInstance { let descriptor = Object.getOwnPropertyDescriptor(object, propertyKey); let proto = Object.getPrototypeOf(object); while (!descriptor && proto !== null) { descriptor = Object.getOwnPropertyDescriptor(proto, propertyKey); proto = Object.getPrototypeOf(proto); } if (!descriptor) { throw new Error( `Property \`${String( propertyKey, )}\` does not exist in the provided object`, ); } if (!descriptor.configurable) { throw new Error( `Property \`${String(propertyKey)}\` is not declared configurable`, ); } if (!descriptor[accessType]) { throw new Error( `Property \`${String( propertyKey, )}\` does not have access type ${accessType}`, ); } const original = descriptor[accessType]; if (!this.isMockFunction(original)) { if (typeof original !== 'function') { throw new Error( `Cannot spy on the ${String( propertyKey, )} property because it is not a function; ${this._typeOf( original, )} given instead.${ typeof original === 'object' ? '' : ` If you are trying to mock a property, use \`jest.replaceProperty(object, '${String( propertyKey, )}', value)\` instead.` }`, ); } descriptor[accessType] = this._makeComponent({type: 'function'}, () => { // @ts-expect-error: mock is assignable descriptor![accessType] = original; Object.defineProperty(object, propertyKey, descriptor!); }); (descriptor[accessType] as Mock).mockImplementation(function ( this: unknown, ) { // @ts-expect-error - wrong context return original.apply(this, arguments); }); } Object.defineProperty(object, propertyKey, descriptor); return descriptor[accessType] as Mock; } replaceProperty<T extends object, K extends keyof T>( object: T, propertyKey: K, value: T[K], ): Replaced<T[K]> { if ( object == null || (typeof object !== 'object' && typeof object !== 'function') ) { throw new Error( `Cannot use replaceProperty on a primitive value; ${this._typeOf( object, )} given`, ); } if (propertyKey == null) { throw new Error('No property name supplied'); } let descriptor = Object.getOwnPropertyDescriptor(object, propertyKey); let proto = Object.getPrototypeOf(object); while (!descriptor && proto !== null) { descriptor = Object.getOwnPropertyDescriptor(proto, propertyKey); proto = Object.getPrototypeOf(proto); } if (!descriptor) { throw new Error( `Property \`${String( propertyKey, )}\` does not exist in the provided object`, ); } if (!descriptor.configurable) { throw new Error( `Property \`${String(propertyKey)}\` is not declared configurable`, ); } if (descriptor.get !== undefined) { throw new Error( `Cannot replace the \`${String( propertyKey, )}\` property because it has a getter. Use \`jest.spyOn(object, '${String( propertyKey, )}', 'get').mockReturnValue(value)\` instead.`, ); } if (descriptor.set !== undefined) { throw new Error( `Cannot replace the \`${String( propertyKey, )}\` property because it has a setter. Use \`jest.spyOn(object, '${String( propertyKey, )}', 'set').mockReturnValue(value)\` instead.`, ); } if (typeof descriptor.value === 'function') { throw new Error( `Cannot replace the \`${String( propertyKey, )}\` property because it is a function. Use \`jest.spyOn(object, '${String( propertyKey, )}')\` instead.`, ); } const existingRestore = this._findReplacedProperty(object, propertyKey); if (existingRestore) { return existingRestore.replaced.replaceValue(value); } const isPropertyOwner = Object.prototype.hasOwnProperty.call( object, propertyKey, ); const originalValue = descriptor.value; const restore: ReplacedPropertyRestorer<T, K> = () => { if (isPropertyOwner) { object[propertyKey] = originalValue; } else { delete object[propertyKey]; } }; const replaced: Replaced<T[K]> = { replaceValue: value => { object[propertyKey] = value; return replaced; }, restore: () => { restore(); this._spyState.delete(restore); }, }; restore.object = object; restore.property = propertyKey; restore.replaced = replaced; this._spyState.add(restore); return replaced.replaceValue(value); } clearAllMocks(): void { this._mockState = new WeakMap(); } resetAllMocks(): void { this._mockConfigRegistry = new WeakMap(); this._mockState = new WeakMap(); } restoreAllMocks(): void { for (const restore of this._spyState) restore(); this._spyState = new Set(); } private _typeOf(value: unknown): string { return value == null ? `${value}` : typeof value; } mocked<T extends object>(source: T, options?: {shallow: false}): Mocked<T>; mocked<T extends object>( source: T, options: {shallow: true}, ): MockedShallow<T>; mocked<T extends object>( source: T, _options?: {shallow: boolean}, ): Mocked<T> | MockedShallow<T> { return source as Mocked<T> | MockedShallow<T>; } } const JestMock = new ModuleMocker(globalThis); export const fn = JestMock.fn.bind(JestMock); export const spyOn = JestMock.spyOn.bind(JestMock); export const mocked = JestMock.mocked.bind(JestMock); export const replaceProperty = JestMock.replaceProperty.bind(JestMock);
packages/jest-mock/src/index.ts
1
https://github.com/jestjs/jest/commit/bd2305b374ff976e67579f188559d25d69443c30
[ 0.0014157143887132406, 0.0001845149090513587, 0.00016316572146024555, 0.00016968250565696508, 0.00012167097884230316 ]
{ "id": 2, "code_window": [ " // TODO: enable at some point\n", " '@typescript-eslint/no-explicit-any': 'off',\n", " '@typescript-eslint/no-non-null-assertion': 'off',\n", "\n", " // TODO: part of \"stylistic\" rules, remove explicit activation when that lands\n", " '@typescript-eslint/no-empty-function': 'error',\n", " '@typescript-eslint/no-empty-interface': 'error',\n", " },\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " '@typescript-eslint/no-invalid-void-type': 'off',\n" ], "file_path": ".eslintrc.cjs", "type": "add", "edit_start_line_idx": 65 }
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const phrase = require('../common-file'); test('B', () => { expect(phrase).toBe('hello'); });
e2e/transform/cache/__tests__/bTests.js
0
https://github.com/jestjs/jest/commit/bd2305b374ff976e67579f188559d25d69443c30
[ 0.00017541642591822892, 0.00017363371443934739, 0.00017185101751238108, 0.00017363371443934739, 0.0000017827042029239237 ]
{ "id": 2, "code_window": [ " // TODO: enable at some point\n", " '@typescript-eslint/no-explicit-any': 'off',\n", " '@typescript-eslint/no-non-null-assertion': 'off',\n", "\n", " // TODO: part of \"stylistic\" rules, remove explicit activation when that lands\n", " '@typescript-eslint/no-empty-function': 'error',\n", " '@typescript-eslint/no-empty-interface': 'error',\n", " },\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " '@typescript-eslint/no-invalid-void-type': 'off',\n" ], "file_path": ".eslintrc.cjs", "type": "add", "edit_start_line_idx": 65 }
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ test('basic test', () => { expect(true).toBeTruthy(); });
e2e/worker-restarting/__tests__/test2.js
0
https://github.com/jestjs/jest/commit/bd2305b374ff976e67579f188559d25d69443c30
[ 0.00017386843683198094, 0.00017281697364524007, 0.0001717655104584992, 0.00017281697364524007, 0.0000010514631867408752 ]
{ "id": 2, "code_window": [ " // TODO: enable at some point\n", " '@typescript-eslint/no-explicit-any': 'off',\n", " '@typescript-eslint/no-non-null-assertion': 'off',\n", "\n", " // TODO: part of \"stylistic\" rules, remove explicit activation when that lands\n", " '@typescript-eslint/no-empty-function': 'error',\n", " '@typescript-eslint/no-empty-interface': 'error',\n", " },\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " '@typescript-eslint/no-invalid-void-type': 'off',\n" ], "file_path": ".eslintrc.cjs", "type": "add", "edit_start_line_idx": 65 }
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ 'use strict'; import * as path from 'path'; import getMockName from '../getMockName'; describe('getMockName', () => { it('extracts mock name from file path', () => { expect(getMockName(path.join('a', '__mocks__', 'c.js'))).toBe('c'); expect(getMockName(path.join('a', '__mocks__', 'c', 'd.js'))).toBe( path.join('c', 'd').replace(/\\/g, '/'), ); }); });
packages/jest-haste-map/src/__tests__/get_mock_name.test.js
0
https://github.com/jestjs/jest/commit/bd2305b374ff976e67579f188559d25d69443c30
[ 0.00017349814879707992, 0.00017226611089427024, 0.00017005893460009247, 0.00017324124928563833, 0.0000015642293647033512 ]
{ "id": 3, "code_window": [ " },\n", " {\n", " files: ['**/__typetests__/**'],\n", " rules: {\n", " '@typescript-eslint/no-empty-function': 'off',\n", " },\n", " },\n", " {\n", " env: {node: true},\n", " files: ['*.js', '*.jsx', '*.mjs', '*.cjs'],\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " '@typescript-eslint/no-invalid-void-type': 'off',\n", " '@typescript-eslint/no-useless-constructor': 'off',\n" ], "file_path": ".eslintrc.cjs", "type": "add", "edit_start_line_idx": 352 }
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* eslint-disable sort-keys */ const fs = require('fs'); const path = require('path'); const {sync: readPkg} = require('read-pkg'); function getPackages() { const PACKAGES_DIR = path.resolve(__dirname, 'packages'); const packages = fs .readdirSync(PACKAGES_DIR) .map(file => path.resolve(PACKAGES_DIR, file)) .filter(f => fs.lstatSync(path.resolve(f)).isDirectory()) .filter(f => fs.existsSync(path.join(path.resolve(f), 'package.json'))); return packages.map(packageDir => { const pkg = readPkg({cwd: packageDir}); return pkg.name; }); } module.exports = { env: { es2020: true, }, extends: [ 'eslint:recommended', 'plugin:markdown/recommended', 'plugin:import/errors', 'plugin:eslint-comments/recommended', 'plugin:prettier/recommended', ], globals: { console: 'readonly', }, overrides: [ { extends: [ 'plugin:@typescript-eslint/recommended', 'plugin:import/typescript', ], files: ['*.ts', '*.tsx'], plugins: ['@typescript-eslint/eslint-plugin', 'local'], rules: { '@typescript-eslint/array-type': ['error', {default: 'generic'}], '@typescript-eslint/ban-types': 'error', '@typescript-eslint/no-inferrable-types': 'error', '@typescript-eslint/no-unused-vars': [ 'error', {argsIgnorePattern: '^_'}, ], '@typescript-eslint/prefer-ts-expect-error': 'error', '@typescript-eslint/no-var-requires': 'off', // TS verifies these 'consistent-return': 'off', 'no-dupe-class-members': 'off', 'no-unused-vars': 'off', // TODO: enable at some point '@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-non-null-assertion': 'off', // TODO: part of "stylistic" rules, remove explicit activation when that lands '@typescript-eslint/no-empty-function': 'error', '@typescript-eslint/no-empty-interface': 'error', }, }, { files: [ 'packages/jest-jasmine2/src/jasmine/Env.ts', 'packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts', 'packages/jest-jasmine2/src/jasmine/Spec.ts', 'packages/jest-jasmine2/src/jasmine/SpyStrategy.ts', 'packages/jest-jasmine2/src/jasmine/Suite.ts', 'packages/jest-jasmine2/src/jasmine/createSpy.ts', 'packages/jest-jasmine2/src/jasmine/jasmineLight.ts', 'packages/jest-mock/src/__tests__/index.test.ts', 'packages/jest-mock/src/index.ts', 'packages/pretty-format/src/__tests__/Immutable.test.ts', 'packages/pretty-format/src/__tests__/prettyFormat.test.ts', ], rules: { 'local/prefer-rest-params-eventually': 'warn', 'prefer-rest-params': 'off', }, }, { files: [ 'packages/expect/src/index.ts', 'packages/jest-fake-timers/src/legacyFakeTimers.ts', 'packages/jest-jasmine2/src/jasmine/Env.ts', 'packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts', 'packages/jest-jasmine2/src/jasmine/Spec.ts', 'packages/jest-jasmine2/src/jasmine/Suite.ts', 'packages/jest-jasmine2/src/jasmine/jasmineLight.ts', 'packages/jest-jasmine2/src/jestExpect.ts', 'packages/jest-resolve/src/resolver.ts', ], rules: { 'local/prefer-spread-eventually': 'warn', 'prefer-spread': 'off', }, }, { files: [ 'e2e/babel-plugin-jest-hoist/__tests__/typescript.test.ts', 'e2e/coverage-remapping/covered.ts', 'packages/expect/src/matchers.ts', 'packages/expect/src/print.ts', 'packages/expect/src/toThrowMatchers.ts', 'packages/expect-utils/src/utils.ts', 'packages/jest-core/src/collectHandles.ts', 'packages/jest-core/src/plugins/UpdateSnapshotsInteractive.ts', 'packages/jest-jasmine2/src/jasmine/SpyStrategy.ts', 'packages/jest-jasmine2/src/jasmine/Suite.ts', 'packages/jest-leak-detector/src/index.ts', 'packages/jest-matcher-utils/src/index.ts', 'packages/jest-mock/src/__tests__/index.test.ts', 'packages/jest-mock/src/index.ts', 'packages/jest-snapshot/src/index.ts', 'packages/jest-snapshot/src/printSnapshot.ts', 'packages/jest-snapshot/src/types.ts', 'packages/jest-util/src/convertDescriptorToString.ts', 'packages/pretty-format/src/index.ts', 'packages/pretty-format/src/plugins/DOMCollection.ts', ], rules: { '@typescript-eslint/ban-types': [ 'error', // TODO: remove these overrides: https://github.com/jestjs/jest/issues/10177 {types: {Function: false, object: false, '{}': false}}, ], 'local/ban-types-eventually': [ 'warn', { types: { // none of these types are in use, so can be errored on Boolean: false, Number: false, Object: false, String: false, Symbol: false, }, }, ], }, }, // 'eslint-plugin-jest' rules for test and test related files { files: [ '**/__mocks__/**', '**/__tests__/**', '**/*.md/**', '**/*.test.*', 'e2e/babel-plugin-jest-hoist/mockFile.js', 'e2e/failures/macros.js', 'e2e/test-in-root/*.js', 'e2e/test-match/test-suites/*', 'packages/test-utils/src/ConditionalTest.ts', ], env: {'jest/globals': true}, excludedFiles: ['**/__typetests__/**'], extends: ['plugin:jest/style'], plugins: ['jest'], rules: { 'jest/no-alias-methods': 'error', 'jest/no-focused-tests': 'error', 'jest/no-identical-title': 'error', 'jest/require-to-throw-message': 'error', 'jest/valid-expect': 'error', }, }, { files: ['e2e/__tests__/*'], rules: { 'jest/no-restricted-jest-methods': [ 'error', { fn: 'Please use fixtures instead of mocks in the end-to-end tests.', mock: 'Please use fixtures instead of mocks in the end-to-end tests.', doMock: 'Please use fixtures instead of mocks in the end-to-end tests.', setMock: 'Please use fixtures instead of mocks in the end-to-end tests.', spyOn: 'Please use fixtures instead of mocks in the end-to-end tests.', }, ], }, }, // to make it more suitable for running on code examples in docs/ folder { files: ['**/*.md/**'], rules: { '@typescript-eslint/no-unused-vars': 'off', '@typescript-eslint/no-empty-function': 'off', '@typescript-eslint/no-namespace': 'off', '@typescript-eslint/no-empty-interface': 'off', 'consistent-return': 'off', 'import/export': 'off', 'import/no-extraneous-dependencies': 'off', 'import/no-unresolved': 'off', 'jest/no-focused-tests': 'off', 'jest/require-to-throw-message': 'off', 'no-console': 'off', 'no-undef': 'off', 'no-unused-vars': 'off', 'sort-keys': 'off', }, }, // demonstration of matchers usage { files: ['**/UsingMatchers.md/**'], rules: { 'jest/prefer-to-be': 'off', }, }, // demonstration of 'jest/valid-expect' rule { files: [ '**/2017-05-06-jest-20-delightful-testing-multi-project-runner.md/**', ], rules: { 'jest/valid-expect': 'off', }, }, // Jest 11 did not had `toHaveLength` matcher { files: ['**/2016-04-12-jest-11.md/**'], rules: { 'jest/prefer-to-have-length': 'off', }, }, // snapshot in an example needs to keep escapes { files: [ '**/2017-02-21-jest-19-immersive-watch-mode-test-platform-improvements.md/**', ], rules: { 'no-useless-escape': 'off', }, }, // snapshots in examples plus inline snapshots need to keep backtick { files: ['**/*.md/**', 'e2e/custom-inline-snapshot-matchers/__tests__/*'], rules: { quotes: [ 'error', 'single', {allowTemplateLiterals: true, avoidEscape: true}, ], }, }, { files: ['docs/**/*', 'website/**/*'], rules: { 'no-redeclare': 'off', 'import/order': 'off', 'import/sort-keys': 'off', 'no-restricted-globals': ['off'], 'sort-keys': 'off', }, }, { files: ['examples/**/*'], rules: { 'no-restricted-imports': 'off', }, }, { files: 'packages/**/*.ts', rules: { '@typescript-eslint/explicit-module-boundary-types': 'error', 'import/no-anonymous-default-export': [ 'error', { allowAnonymousClass: false, allowAnonymousFunction: false, allowArray: false, allowArrowFunction: false, allowCallExpression: false, allowLiteral: false, allowObject: true, }, ], }, }, { files: ['**/__tests__/**', '**/__mocks__/**'], rules: { '@typescript-eslint/ban-ts-comment': 'off', '@typescript-eslint/no-empty-function': 'off', }, }, { files: [ '**/__tests__/**', '**/__mocks__/**', 'packages/jest-jasmine2/src/jasmine/**/*', 'packages/expect/src/jasmineUtils.ts', '**/vendor/**/*', ], rules: { '@typescript-eslint/explicit-module-boundary-types': 'off', }, }, { files: [ 'packages/jest-jasmine2/src/jasmine/**/*', 'packages/expect-utils/src/jasmineUtils.ts', ], rules: { 'eslint-comments/disable-enable-pair': 'off', 'eslint-comments/no-unlimited-disable': 'off', }, }, { files: [ 'e2e/error-on-deprecated/__tests__/*', 'e2e/jasmine-async/__tests__/*', ], globals: { fail: 'readonly', jasmine: 'readonly', pending: 'readonly', }, }, { files: [ 'e2e/**', 'website/**', '**/__benchmarks__/**', '**/__tests__/**', 'packages/jest-types/**/*', '.eslintplugin/**', ], rules: { 'import/no-extraneous-dependencies': 'off', }, }, { files: ['**/__typetests__/**'], rules: { '@typescript-eslint/no-empty-function': 'off', }, }, { env: {node: true}, files: ['*.js', '*.jsx', '*.mjs', '*.cjs'], }, { files: [ 'scripts/*', 'packages/*/__benchmarks__/test.js', 'packages/create-jest/src/runCreate.ts', 'packages/jest-repl/src/cli/runtime-cli.ts', ], rules: { 'no-console': 'off', }, }, { files: [ 'e2e/**', 'examples/**', 'website/**', '**/__mocks__/**', '**/__tests__/**', '**/__typetests__/**', ], rules: { '@typescript-eslint/no-unused-vars': 'off', 'import/no-unresolved': 'off', 'no-console': 'off', 'no-unused-vars': 'off', }, }, ], parser: '@typescript-eslint/parser', parserOptions: { sourceType: 'module', }, plugins: ['import', 'jsdoc', 'unicorn'], rules: { 'accessor-pairs': ['warn', {setWithoutGet: true}], 'block-scoped-var': 'off', 'callback-return': 'off', camelcase: ['off', {properties: 'always'}], complexity: 'off', 'consistent-return': 'warn', 'consistent-this': ['off', 'self'], 'constructor-super': 'error', 'default-case': 'off', 'dot-notation': 'off', eqeqeq: ['off', 'allow-null'], 'eslint-comments/disable-enable-pair': ['error', {allowWholeFile: true}], 'eslint-comments/no-unused-disable': 'error', 'func-names': 'off', 'func-style': ['off', 'declaration'], 'global-require': 'off', 'guard-for-in': 'off', 'handle-callback-err': 'off', 'id-length': 'off', 'id-match': 'off', 'import/no-extraneous-dependencies': [ 'error', { devDependencies: [ '**/__mocks__/**', '**/__tests__/**', '**/__typetests__/**', '**/?(*.)(spec|test).js?(x)', 'scripts/**', 'babel.config.js', 'testSetupFile.js', '.eslintrc.cjs', ], }, ], 'import/no-unresolved': ['error', {ignore: ['fsevents']}], 'import/order': [ 'error', { alphabetize: { order: 'asc', }, // this is the default order except for added `internal` in the middle groups: [ 'builtin', 'external', 'internal', 'parent', 'sibling', 'index', ], 'newlines-between': 'never', }, ], 'init-declarations': 'off', 'jsdoc/check-alignment': 'error', 'lines-around-comment': 'off', 'max-depth': 'off', 'max-nested-callbacks': 'off', 'max-params': 'off', 'max-statements': 'off', 'new-cap': 'off', 'new-parens': 'error', 'newline-after-var': 'off', 'no-alert': 'off', 'no-array-constructor': 'error', 'no-bitwise': 'warn', 'no-caller': 'error', 'no-case-declarations': 'off', 'no-class-assign': 'warn', 'no-cond-assign': 'off', 'no-confusing-arrow': 'off', 'no-console': [ 'warn', {allow: ['warn', 'error', 'time', 'timeEnd', 'timeStamp']}, ], 'no-const-assign': 'error', 'no-constant-condition': 'off', 'no-continue': 'off', 'no-control-regex': 'off', 'no-debugger': 'error', 'no-delete-var': 'error', 'no-div-regex': 'off', 'no-dupe-args': 'error', 'no-dupe-class-members': 'error', 'no-dupe-keys': 'error', 'no-duplicate-case': 'error', 'no-duplicate-imports': 'error', 'no-else-return': 'off', 'no-empty': 'off', 'no-empty-character-class': 'warn', 'no-empty-pattern': 'warn', 'no-eq-null': 'off', 'no-eval': 'error', 'no-ex-assign': 'warn', 'no-extend-native': 'warn', 'no-extra-bind': 'warn', 'no-extra-boolean-cast': 'warn', 'no-fallthrough': 'warn', 'no-floating-decimal': 'error', 'no-func-assign': 'error', 'no-implicit-coercion': 'off', 'no-implied-eval': 'error', 'no-inline-comments': 'off', 'no-inner-declarations': 'off', 'no-invalid-regexp': 'warn', 'no-invalid-this': 'off', 'no-irregular-whitespace': 'error', 'no-iterator': 'off', 'no-label-var': 'warn', 'no-labels': ['error', {allowLoop: true, allowSwitch: true}], 'no-lonely-if': 'off', 'no-loop-func': 'off', 'no-magic-numbers': 'off', 'no-mixed-requires': 'off', 'no-mixed-spaces-and-tabs': 'error', 'no-multi-str': 'error', 'no-multiple-empty-lines': 'off', 'no-native-reassign': ['error', {exceptions: ['Map', 'Set']}], 'no-negated-condition': 'off', 'no-negated-in-lhs': 'error', 'no-nested-ternary': 'off', 'no-new': 'warn', 'no-new-func': 'error', 'no-new-object': 'warn', 'no-new-require': 'off', 'no-new-wrappers': 'warn', 'no-obj-calls': 'error', 'no-octal': 'warn', 'no-octal-escape': 'warn', 'no-param-reassign': 'off', 'no-plusplus': 'off', 'no-process-env': 'off', 'no-process-exit': 'off', 'no-proto': 'error', 'no-prototype-builtins': 'error', 'no-redeclare': 'warn', 'no-regex-spaces': 'warn', 'no-restricted-globals': [ 'error', {message: 'Use `globalThis` instead.', name: 'global'}, ], 'no-restricted-imports': [ 'error', {message: 'Please use graceful-fs instead.', name: 'fs'}, ], 'no-restricted-modules': 'off', 'no-restricted-syntax': 'off', 'no-return-assign': 'off', 'no-script-url': 'error', 'no-self-compare': 'warn', 'no-sequences': 'warn', 'no-shadow': 'off', 'no-shadow-restricted-names': 'warn', 'no-sparse-arrays': 'error', 'no-sync': 'off', 'no-ternary': 'off', 'no-this-before-super': 'error', 'no-throw-literal': 'error', 'no-undef': 'error', 'no-undef-init': 'off', 'no-undefined': 'off', 'no-underscore-dangle': 'off', 'no-unneeded-ternary': 'warn', 'no-unreachable': 'error', 'no-unused-expressions': 'off', 'no-unused-vars': ['error', {argsIgnorePattern: '^_'}], 'no-use-before-define': 'off', 'no-useless-call': 'error', 'no-useless-computed-key': 'error', 'no-useless-concat': 'error', 'no-var': 'error', 'no-void': 'off', 'no-warn-comments': 'off', 'no-with': 'off', 'object-shorthand': 'error', 'one-var': ['warn', {initialized: 'never'}], 'operator-assignment': ['warn', 'always'], 'operator-linebreak': 'off', 'padded-blocks': 'off', 'prefer-arrow-callback': ['error', {allowNamedFunctions: true}], 'prefer-const': 'error', 'prefer-template': 'error', quotes: [ 'error', 'single', {allowTemplateLiterals: false, avoidEscape: true}, ], radix: 'warn', 'require-jsdoc': 'off', 'require-yield': 'off', 'sort-imports': ['error', {ignoreDeclarationSort: true}], 'sort-keys': 'error', 'sort-vars': 'off', 'spaced-comment': ['off', 'always', {exceptions: ['eslint', 'global']}], strict: 'off', 'use-isnan': 'error', 'valid-jsdoc': 'off', 'valid-typeof': 'error', 'vars-on-top': 'off', 'wrap-iife': 'off', 'wrap-regex': 'off', yoda: 'off', 'unicorn/explicit-length-check': 'error', 'unicorn/no-array-for-each': 'error', 'unicorn/no-negated-condition': 'error', 'unicorn/prefer-default-parameters': 'error', 'unicorn/prefer-includes': 'error', 'unicorn/template-indent': 'error', }, settings: { 'import/ignore': ['react-native'], // using `new RegExp` makes sure to escape `/` 'import/internal-regex': new RegExp( getPackages() .map(pkg => `^${pkg}$`) .join('|'), ).source, 'import/resolver': { typescript: {}, }, }, };
.eslintrc.cjs
1
https://github.com/jestjs/jest/commit/bd2305b374ff976e67579f188559d25d69443c30
[ 0.8512586355209351, 0.016100797802209854, 0.00016359193250536919, 0.00016915833111852407, 0.10735416412353516 ]
{ "id": 3, "code_window": [ " },\n", " {\n", " files: ['**/__typetests__/**'],\n", " rules: {\n", " '@typescript-eslint/no-empty-function': 'off',\n", " },\n", " },\n", " {\n", " env: {node: true},\n", " files: ['*.js', '*.jsx', '*.mjs', '*.cjs'],\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " '@typescript-eslint/no-invalid-void-type': 'off',\n", " '@typescript-eslint/no-useless-constructor': 'off',\n" ], "file_path": ".eslintrc.cjs", "type": "add", "edit_start_line_idx": 352 }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const Handlebars = require('handlebars/dist/cjs/handlebars.js'); const {SourceMapConsumer, SourceNode} = require('source-map'); exports.process = (code, filename) => { const pc = Handlebars.precompile(code, {srcName: filename}); const out = new SourceNode(null, null, null, [ 'const Handlebars = require("handlebars/dist/cjs/handlebars.runtime.js");\n', 'module.exports = Handlebars.template(', SourceNode.fromStringWithSourceMap(pc.code, new SourceMapConsumer(pc.map)), ');\n', ]).toStringWithSourceMap(); return {code: out.code, map: out.map.toString()}; };
e2e/coverage-handlebars/transform-handlebars.js
0
https://github.com/jestjs/jest/commit/bd2305b374ff976e67579f188559d25d69443c30
[ 0.00016888834943529218, 0.00016807981592137367, 0.00016759487334638834, 0.00016775619587861001, 5.755072152169305e-7 ]
{ "id": 3, "code_window": [ " },\n", " {\n", " files: ['**/__typetests__/**'],\n", " rules: {\n", " '@typescript-eslint/no-empty-function': 'off',\n", " },\n", " },\n", " {\n", " env: {node: true},\n", " files: ['*.js', '*.jsx', '*.mjs', '*.cjs'],\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " '@typescript-eslint/no-invalid-void-type': 'off',\n", " '@typescript-eslint/no-useless-constructor': 'off',\n" ], "file_path": ".eslintrc.cjs", "type": "add", "edit_start_line_idx": 352 }
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {KEYS} from '../constants'; import type {ScrollOptions} from '../types'; export default class Prompt { private _entering: boolean; private _value: string; private _onChange: () => void; private _onSuccess: (value: string) => void; private _onCancel: (value: string) => void; private _offset: number; private _promptLength: number; private _selection: string | null; constructor() { // Copied from `enter` to satisfy TS this._entering = true; this._value = ''; this._selection = null; this._offset = -1; this._promptLength = 0; /* eslint-disable @typescript-eslint/no-empty-function */ this._onChange = () => {}; this._onSuccess = () => {}; this._onCancel = () => {}; /* eslint-enable */ } private readonly _onResize = (): void => { this._onChange(); }; enter( onChange: (pattern: string, options: ScrollOptions) => void, onSuccess: (pattern: string) => void, onCancel: () => void, ): void { this._entering = true; this._value = ''; this._onSuccess = onSuccess; this._onCancel = onCancel; this._selection = null; this._offset = -1; this._promptLength = 0; this._onChange = () => onChange(this._value, { max: 10, offset: this._offset, }); this._onChange(); process.stdout.on('resize', this._onResize); } setPromptLength(length: number): void { this._promptLength = length; } setPromptSelection(selected: string): void { this._selection = selected; } put(key: string): void { switch (key) { case KEYS.ENTER: this._entering = false; this._onSuccess(this._selection ?? this._value); this.abort(); break; case KEYS.ESCAPE: this._entering = false; this._onCancel(this._value); this.abort(); break; case KEYS.ARROW_DOWN: this._offset = Math.min(this._offset + 1, this._promptLength - 1); this._onChange(); break; case KEYS.ARROW_UP: this._offset = Math.max(this._offset - 1, -1); this._onChange(); break; case KEYS.ARROW_LEFT: case KEYS.ARROW_RIGHT: break; case KEYS.CONTROL_U: this._value = ''; this._offset = -1; this._selection = null; this._onChange(); break; default: this._value = key === KEYS.BACKSPACE ? this._value.slice(0, -1) : this._value + key; this._offset = -1; this._selection = null; this._onChange(); break; } } abort(): void { this._entering = false; this._value = ''; process.stdout.removeListener('resize', this._onResize); } isEntering(): boolean { return this._entering; } }
packages/jest-watcher/src/lib/Prompt.ts
0
https://github.com/jestjs/jest/commit/bd2305b374ff976e67579f188559d25d69443c30
[ 0.00017153161752503365, 0.00016862618213053793, 0.0001644820731598884, 0.0001688904594630003, 0.0000018058419755107025 ]
{ "id": 3, "code_window": [ " },\n", " {\n", " files: ['**/__typetests__/**'],\n", " rules: {\n", " '@typescript-eslint/no-empty-function': 'off',\n", " },\n", " },\n", " {\n", " env: {node: true},\n", " files: ['*.js', '*.jsx', '*.mjs', '*.cjs'],\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " '@typescript-eslint/no-invalid-void-type': 'off',\n", " '@typescript-eslint/no-useless-constructor': 'off',\n" ], "file_path": ".eslintrc.cjs", "type": "add", "edit_start_line_idx": 352 }
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ import {spawnSync} from 'child_process'; import * as path from 'path'; const JEST_RUNTIME = require.resolve('../../bin/jest-repl.js'); describe('Repl', () => { describe('cli', () => { it('runs without errors', () => { let command = JEST_RUNTIME; const args = []; // Windows can't handle hashbangs, so is the best we can do if (process.platform === 'win32') { args.push(command); command = 'node'; } const output = spawnSync(command, args, { cwd: process.cwd(), encoding: 'utf8', env: process.env, }); expect(output.stderr.trim()).toBe(''); expect(output.stdout.trim()).toMatch(/›/u); }); }); });
packages/jest-repl/src/__tests__/jest_repl.test.js
0
https://github.com/jestjs/jest/commit/bd2305b374ff976e67579f188559d25d69443c30
[ 0.0002459360403008759, 0.00019038614118471742, 0.00016994302859529853, 0.00017283274792134762, 0.0000320970248139929 ]
{ "id": 4, "code_window": [ " '**/__mocks__/**',\n", " '**/__tests__/**',\n", " '**/__typetests__/**',\n", " ],\n", " rules: {\n", " '@typescript-eslint/no-unused-vars': 'off',\n", " 'import/no-unresolved': 'off',\n", " 'no-console': 'off',\n", " 'no-unused-vars': 'off',\n", " },\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " '@typescript-eslint/no-extraneous-class': 'off',\n" ], "file_path": ".eslintrc.cjs", "type": "add", "edit_start_line_idx": 379 }
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* eslint-disable sort-keys */ const fs = require('fs'); const path = require('path'); const {sync: readPkg} = require('read-pkg'); function getPackages() { const PACKAGES_DIR = path.resolve(__dirname, 'packages'); const packages = fs .readdirSync(PACKAGES_DIR) .map(file => path.resolve(PACKAGES_DIR, file)) .filter(f => fs.lstatSync(path.resolve(f)).isDirectory()) .filter(f => fs.existsSync(path.join(path.resolve(f), 'package.json'))); return packages.map(packageDir => { const pkg = readPkg({cwd: packageDir}); return pkg.name; }); } module.exports = { env: { es2020: true, }, extends: [ 'eslint:recommended', 'plugin:markdown/recommended', 'plugin:import/errors', 'plugin:eslint-comments/recommended', 'plugin:prettier/recommended', ], globals: { console: 'readonly', }, overrides: [ { extends: [ 'plugin:@typescript-eslint/recommended', 'plugin:import/typescript', ], files: ['*.ts', '*.tsx'], plugins: ['@typescript-eslint/eslint-plugin', 'local'], rules: { '@typescript-eslint/array-type': ['error', {default: 'generic'}], '@typescript-eslint/ban-types': 'error', '@typescript-eslint/no-inferrable-types': 'error', '@typescript-eslint/no-unused-vars': [ 'error', {argsIgnorePattern: '^_'}, ], '@typescript-eslint/prefer-ts-expect-error': 'error', '@typescript-eslint/no-var-requires': 'off', // TS verifies these 'consistent-return': 'off', 'no-dupe-class-members': 'off', 'no-unused-vars': 'off', // TODO: enable at some point '@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-non-null-assertion': 'off', // TODO: part of "stylistic" rules, remove explicit activation when that lands '@typescript-eslint/no-empty-function': 'error', '@typescript-eslint/no-empty-interface': 'error', }, }, { files: [ 'packages/jest-jasmine2/src/jasmine/Env.ts', 'packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts', 'packages/jest-jasmine2/src/jasmine/Spec.ts', 'packages/jest-jasmine2/src/jasmine/SpyStrategy.ts', 'packages/jest-jasmine2/src/jasmine/Suite.ts', 'packages/jest-jasmine2/src/jasmine/createSpy.ts', 'packages/jest-jasmine2/src/jasmine/jasmineLight.ts', 'packages/jest-mock/src/__tests__/index.test.ts', 'packages/jest-mock/src/index.ts', 'packages/pretty-format/src/__tests__/Immutable.test.ts', 'packages/pretty-format/src/__tests__/prettyFormat.test.ts', ], rules: { 'local/prefer-rest-params-eventually': 'warn', 'prefer-rest-params': 'off', }, }, { files: [ 'packages/expect/src/index.ts', 'packages/jest-fake-timers/src/legacyFakeTimers.ts', 'packages/jest-jasmine2/src/jasmine/Env.ts', 'packages/jest-jasmine2/src/jasmine/ReportDispatcher.ts', 'packages/jest-jasmine2/src/jasmine/Spec.ts', 'packages/jest-jasmine2/src/jasmine/Suite.ts', 'packages/jest-jasmine2/src/jasmine/jasmineLight.ts', 'packages/jest-jasmine2/src/jestExpect.ts', 'packages/jest-resolve/src/resolver.ts', ], rules: { 'local/prefer-spread-eventually': 'warn', 'prefer-spread': 'off', }, }, { files: [ 'e2e/babel-plugin-jest-hoist/__tests__/typescript.test.ts', 'e2e/coverage-remapping/covered.ts', 'packages/expect/src/matchers.ts', 'packages/expect/src/print.ts', 'packages/expect/src/toThrowMatchers.ts', 'packages/expect-utils/src/utils.ts', 'packages/jest-core/src/collectHandles.ts', 'packages/jest-core/src/plugins/UpdateSnapshotsInteractive.ts', 'packages/jest-jasmine2/src/jasmine/SpyStrategy.ts', 'packages/jest-jasmine2/src/jasmine/Suite.ts', 'packages/jest-leak-detector/src/index.ts', 'packages/jest-matcher-utils/src/index.ts', 'packages/jest-mock/src/__tests__/index.test.ts', 'packages/jest-mock/src/index.ts', 'packages/jest-snapshot/src/index.ts', 'packages/jest-snapshot/src/printSnapshot.ts', 'packages/jest-snapshot/src/types.ts', 'packages/jest-util/src/convertDescriptorToString.ts', 'packages/pretty-format/src/index.ts', 'packages/pretty-format/src/plugins/DOMCollection.ts', ], rules: { '@typescript-eslint/ban-types': [ 'error', // TODO: remove these overrides: https://github.com/jestjs/jest/issues/10177 {types: {Function: false, object: false, '{}': false}}, ], 'local/ban-types-eventually': [ 'warn', { types: { // none of these types are in use, so can be errored on Boolean: false, Number: false, Object: false, String: false, Symbol: false, }, }, ], }, }, // 'eslint-plugin-jest' rules for test and test related files { files: [ '**/__mocks__/**', '**/__tests__/**', '**/*.md/**', '**/*.test.*', 'e2e/babel-plugin-jest-hoist/mockFile.js', 'e2e/failures/macros.js', 'e2e/test-in-root/*.js', 'e2e/test-match/test-suites/*', 'packages/test-utils/src/ConditionalTest.ts', ], env: {'jest/globals': true}, excludedFiles: ['**/__typetests__/**'], extends: ['plugin:jest/style'], plugins: ['jest'], rules: { 'jest/no-alias-methods': 'error', 'jest/no-focused-tests': 'error', 'jest/no-identical-title': 'error', 'jest/require-to-throw-message': 'error', 'jest/valid-expect': 'error', }, }, { files: ['e2e/__tests__/*'], rules: { 'jest/no-restricted-jest-methods': [ 'error', { fn: 'Please use fixtures instead of mocks in the end-to-end tests.', mock: 'Please use fixtures instead of mocks in the end-to-end tests.', doMock: 'Please use fixtures instead of mocks in the end-to-end tests.', setMock: 'Please use fixtures instead of mocks in the end-to-end tests.', spyOn: 'Please use fixtures instead of mocks in the end-to-end tests.', }, ], }, }, // to make it more suitable for running on code examples in docs/ folder { files: ['**/*.md/**'], rules: { '@typescript-eslint/no-unused-vars': 'off', '@typescript-eslint/no-empty-function': 'off', '@typescript-eslint/no-namespace': 'off', '@typescript-eslint/no-empty-interface': 'off', 'consistent-return': 'off', 'import/export': 'off', 'import/no-extraneous-dependencies': 'off', 'import/no-unresolved': 'off', 'jest/no-focused-tests': 'off', 'jest/require-to-throw-message': 'off', 'no-console': 'off', 'no-undef': 'off', 'no-unused-vars': 'off', 'sort-keys': 'off', }, }, // demonstration of matchers usage { files: ['**/UsingMatchers.md/**'], rules: { 'jest/prefer-to-be': 'off', }, }, // demonstration of 'jest/valid-expect' rule { files: [ '**/2017-05-06-jest-20-delightful-testing-multi-project-runner.md/**', ], rules: { 'jest/valid-expect': 'off', }, }, // Jest 11 did not had `toHaveLength` matcher { files: ['**/2016-04-12-jest-11.md/**'], rules: { 'jest/prefer-to-have-length': 'off', }, }, // snapshot in an example needs to keep escapes { files: [ '**/2017-02-21-jest-19-immersive-watch-mode-test-platform-improvements.md/**', ], rules: { 'no-useless-escape': 'off', }, }, // snapshots in examples plus inline snapshots need to keep backtick { files: ['**/*.md/**', 'e2e/custom-inline-snapshot-matchers/__tests__/*'], rules: { quotes: [ 'error', 'single', {allowTemplateLiterals: true, avoidEscape: true}, ], }, }, { files: ['docs/**/*', 'website/**/*'], rules: { 'no-redeclare': 'off', 'import/order': 'off', 'import/sort-keys': 'off', 'no-restricted-globals': ['off'], 'sort-keys': 'off', }, }, { files: ['examples/**/*'], rules: { 'no-restricted-imports': 'off', }, }, { files: 'packages/**/*.ts', rules: { '@typescript-eslint/explicit-module-boundary-types': 'error', 'import/no-anonymous-default-export': [ 'error', { allowAnonymousClass: false, allowAnonymousFunction: false, allowArray: false, allowArrowFunction: false, allowCallExpression: false, allowLiteral: false, allowObject: true, }, ], }, }, { files: ['**/__tests__/**', '**/__mocks__/**'], rules: { '@typescript-eslint/ban-ts-comment': 'off', '@typescript-eslint/no-empty-function': 'off', }, }, { files: [ '**/__tests__/**', '**/__mocks__/**', 'packages/jest-jasmine2/src/jasmine/**/*', 'packages/expect/src/jasmineUtils.ts', '**/vendor/**/*', ], rules: { '@typescript-eslint/explicit-module-boundary-types': 'off', }, }, { files: [ 'packages/jest-jasmine2/src/jasmine/**/*', 'packages/expect-utils/src/jasmineUtils.ts', ], rules: { 'eslint-comments/disable-enable-pair': 'off', 'eslint-comments/no-unlimited-disable': 'off', }, }, { files: [ 'e2e/error-on-deprecated/__tests__/*', 'e2e/jasmine-async/__tests__/*', ], globals: { fail: 'readonly', jasmine: 'readonly', pending: 'readonly', }, }, { files: [ 'e2e/**', 'website/**', '**/__benchmarks__/**', '**/__tests__/**', 'packages/jest-types/**/*', '.eslintplugin/**', ], rules: { 'import/no-extraneous-dependencies': 'off', }, }, { files: ['**/__typetests__/**'], rules: { '@typescript-eslint/no-empty-function': 'off', }, }, { env: {node: true}, files: ['*.js', '*.jsx', '*.mjs', '*.cjs'], }, { files: [ 'scripts/*', 'packages/*/__benchmarks__/test.js', 'packages/create-jest/src/runCreate.ts', 'packages/jest-repl/src/cli/runtime-cli.ts', ], rules: { 'no-console': 'off', }, }, { files: [ 'e2e/**', 'examples/**', 'website/**', '**/__mocks__/**', '**/__tests__/**', '**/__typetests__/**', ], rules: { '@typescript-eslint/no-unused-vars': 'off', 'import/no-unresolved': 'off', 'no-console': 'off', 'no-unused-vars': 'off', }, }, ], parser: '@typescript-eslint/parser', parserOptions: { sourceType: 'module', }, plugins: ['import', 'jsdoc', 'unicorn'], rules: { 'accessor-pairs': ['warn', {setWithoutGet: true}], 'block-scoped-var': 'off', 'callback-return': 'off', camelcase: ['off', {properties: 'always'}], complexity: 'off', 'consistent-return': 'warn', 'consistent-this': ['off', 'self'], 'constructor-super': 'error', 'default-case': 'off', 'dot-notation': 'off', eqeqeq: ['off', 'allow-null'], 'eslint-comments/disable-enable-pair': ['error', {allowWholeFile: true}], 'eslint-comments/no-unused-disable': 'error', 'func-names': 'off', 'func-style': ['off', 'declaration'], 'global-require': 'off', 'guard-for-in': 'off', 'handle-callback-err': 'off', 'id-length': 'off', 'id-match': 'off', 'import/no-extraneous-dependencies': [ 'error', { devDependencies: [ '**/__mocks__/**', '**/__tests__/**', '**/__typetests__/**', '**/?(*.)(spec|test).js?(x)', 'scripts/**', 'babel.config.js', 'testSetupFile.js', '.eslintrc.cjs', ], }, ], 'import/no-unresolved': ['error', {ignore: ['fsevents']}], 'import/order': [ 'error', { alphabetize: { order: 'asc', }, // this is the default order except for added `internal` in the middle groups: [ 'builtin', 'external', 'internal', 'parent', 'sibling', 'index', ], 'newlines-between': 'never', }, ], 'init-declarations': 'off', 'jsdoc/check-alignment': 'error', 'lines-around-comment': 'off', 'max-depth': 'off', 'max-nested-callbacks': 'off', 'max-params': 'off', 'max-statements': 'off', 'new-cap': 'off', 'new-parens': 'error', 'newline-after-var': 'off', 'no-alert': 'off', 'no-array-constructor': 'error', 'no-bitwise': 'warn', 'no-caller': 'error', 'no-case-declarations': 'off', 'no-class-assign': 'warn', 'no-cond-assign': 'off', 'no-confusing-arrow': 'off', 'no-console': [ 'warn', {allow: ['warn', 'error', 'time', 'timeEnd', 'timeStamp']}, ], 'no-const-assign': 'error', 'no-constant-condition': 'off', 'no-continue': 'off', 'no-control-regex': 'off', 'no-debugger': 'error', 'no-delete-var': 'error', 'no-div-regex': 'off', 'no-dupe-args': 'error', 'no-dupe-class-members': 'error', 'no-dupe-keys': 'error', 'no-duplicate-case': 'error', 'no-duplicate-imports': 'error', 'no-else-return': 'off', 'no-empty': 'off', 'no-empty-character-class': 'warn', 'no-empty-pattern': 'warn', 'no-eq-null': 'off', 'no-eval': 'error', 'no-ex-assign': 'warn', 'no-extend-native': 'warn', 'no-extra-bind': 'warn', 'no-extra-boolean-cast': 'warn', 'no-fallthrough': 'warn', 'no-floating-decimal': 'error', 'no-func-assign': 'error', 'no-implicit-coercion': 'off', 'no-implied-eval': 'error', 'no-inline-comments': 'off', 'no-inner-declarations': 'off', 'no-invalid-regexp': 'warn', 'no-invalid-this': 'off', 'no-irregular-whitespace': 'error', 'no-iterator': 'off', 'no-label-var': 'warn', 'no-labels': ['error', {allowLoop: true, allowSwitch: true}], 'no-lonely-if': 'off', 'no-loop-func': 'off', 'no-magic-numbers': 'off', 'no-mixed-requires': 'off', 'no-mixed-spaces-and-tabs': 'error', 'no-multi-str': 'error', 'no-multiple-empty-lines': 'off', 'no-native-reassign': ['error', {exceptions: ['Map', 'Set']}], 'no-negated-condition': 'off', 'no-negated-in-lhs': 'error', 'no-nested-ternary': 'off', 'no-new': 'warn', 'no-new-func': 'error', 'no-new-object': 'warn', 'no-new-require': 'off', 'no-new-wrappers': 'warn', 'no-obj-calls': 'error', 'no-octal': 'warn', 'no-octal-escape': 'warn', 'no-param-reassign': 'off', 'no-plusplus': 'off', 'no-process-env': 'off', 'no-process-exit': 'off', 'no-proto': 'error', 'no-prototype-builtins': 'error', 'no-redeclare': 'warn', 'no-regex-spaces': 'warn', 'no-restricted-globals': [ 'error', {message: 'Use `globalThis` instead.', name: 'global'}, ], 'no-restricted-imports': [ 'error', {message: 'Please use graceful-fs instead.', name: 'fs'}, ], 'no-restricted-modules': 'off', 'no-restricted-syntax': 'off', 'no-return-assign': 'off', 'no-script-url': 'error', 'no-self-compare': 'warn', 'no-sequences': 'warn', 'no-shadow': 'off', 'no-shadow-restricted-names': 'warn', 'no-sparse-arrays': 'error', 'no-sync': 'off', 'no-ternary': 'off', 'no-this-before-super': 'error', 'no-throw-literal': 'error', 'no-undef': 'error', 'no-undef-init': 'off', 'no-undefined': 'off', 'no-underscore-dangle': 'off', 'no-unneeded-ternary': 'warn', 'no-unreachable': 'error', 'no-unused-expressions': 'off', 'no-unused-vars': ['error', {argsIgnorePattern: '^_'}], 'no-use-before-define': 'off', 'no-useless-call': 'error', 'no-useless-computed-key': 'error', 'no-useless-concat': 'error', 'no-var': 'error', 'no-void': 'off', 'no-warn-comments': 'off', 'no-with': 'off', 'object-shorthand': 'error', 'one-var': ['warn', {initialized: 'never'}], 'operator-assignment': ['warn', 'always'], 'operator-linebreak': 'off', 'padded-blocks': 'off', 'prefer-arrow-callback': ['error', {allowNamedFunctions: true}], 'prefer-const': 'error', 'prefer-template': 'error', quotes: [ 'error', 'single', {allowTemplateLiterals: false, avoidEscape: true}, ], radix: 'warn', 'require-jsdoc': 'off', 'require-yield': 'off', 'sort-imports': ['error', {ignoreDeclarationSort: true}], 'sort-keys': 'error', 'sort-vars': 'off', 'spaced-comment': ['off', 'always', {exceptions: ['eslint', 'global']}], strict: 'off', 'use-isnan': 'error', 'valid-jsdoc': 'off', 'valid-typeof': 'error', 'vars-on-top': 'off', 'wrap-iife': 'off', 'wrap-regex': 'off', yoda: 'off', 'unicorn/explicit-length-check': 'error', 'unicorn/no-array-for-each': 'error', 'unicorn/no-negated-condition': 'error', 'unicorn/prefer-default-parameters': 'error', 'unicorn/prefer-includes': 'error', 'unicorn/template-indent': 'error', }, settings: { 'import/ignore': ['react-native'], // using `new RegExp` makes sure to escape `/` 'import/internal-regex': new RegExp( getPackages() .map(pkg => `^${pkg}$`) .join('|'), ).source, 'import/resolver': { typescript: {}, }, }, };
.eslintrc.cjs
1
https://github.com/jestjs/jest/commit/bd2305b374ff976e67579f188559d25d69443c30
[ 0.9030393362045288, 0.01804470457136631, 0.0001619285758351907, 0.00016967076226137578, 0.11527112871408463 ]
{ "id": 4, "code_window": [ " '**/__mocks__/**',\n", " '**/__tests__/**',\n", " '**/__typetests__/**',\n", " ],\n", " rules: {\n", " '@typescript-eslint/no-unused-vars': 'off',\n", " 'import/no-unresolved': 'off',\n", " 'no-console': 'off',\n", " 'no-unused-vars': 'off',\n", " },\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " '@typescript-eslint/no-extraneous-class': 'off',\n" ], "file_path": ".eslintrc.cjs", "type": "add", "edit_start_line_idx": 379 }
{ "jest": { "testEnvironment": "node" } }
e2e/test-in-root/package.json
0
https://github.com/jestjs/jest/commit/bd2305b374ff976e67579f188559d25d69443c30
[ 0.00017031711468007416, 0.00017031711468007416, 0.00017031711468007416, 0.00017031711468007416, 0 ]
{ "id": 4, "code_window": [ " '**/__mocks__/**',\n", " '**/__tests__/**',\n", " '**/__typetests__/**',\n", " ],\n", " rules: {\n", " '@typescript-eslint/no-unused-vars': 'off',\n", " 'import/no-unresolved': 'off',\n", " 'no-console': 'off',\n", " 'no-unused-vars': 'off',\n", " },\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " '@typescript-eslint/no-extraneous-class': 'off',\n" ], "file_path": ".eslintrc.cjs", "type": "add", "edit_start_line_idx": 379 }
--- title: Jest Community id: jest-community --- The community around Jest is working hard to make the testing experience even greater. [jest-community](https://github.com/jest-community) is a new GitHub organization for high quality Jest additions curated by Jest maintainers and collaborators. It already features some of our favorite projects, to name a few: - [vscode-jest](https://github.com/jest-community/vscode-jest) - [jest-extended](https://github.com/jest-community/jest-extended) - [eslint-plugin-jest](https://github.com/jest-community/eslint-plugin-jest) - [awesome-jest](https://github.com/jest-community/awesome-jest) Community projects under one organization are a great way for Jest to experiment with new ideas/techniques and approaches. Encourage contributions from the community and publish contributions independently at a faster pace. ## Awesome Jest The jest-community org maintains an [awesome-jest](https://github.com/jest-community/awesome-jest) list of great projects and resources related to Jest. If you have something awesome to share, feel free to reach out to us! We'd love to share your project on the awesome-jest list ([send a PR here](https://github.com/jest-community/awesome-jest/pulls)) or if you would like to transfer your project to the jest-community org reach out to one of the owners of the org.
website/versioned_docs/version-29.5/JestCommunity.md
0
https://github.com/jestjs/jest/commit/bd2305b374ff976e67579f188559d25d69443c30
[ 0.00017265269707422704, 0.000171241641510278, 0.00016844157653395087, 0.00017263063637074083, 0.0000019799620076810243 ]
{ "id": 4, "code_window": [ " '**/__mocks__/**',\n", " '**/__tests__/**',\n", " '**/__typetests__/**',\n", " ],\n", " rules: {\n", " '@typescript-eslint/no-unused-vars': 'off',\n", " 'import/no-unresolved': 'off',\n", " 'no-console': 'off',\n", " 'no-unused-vars': 'off',\n", " },\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " '@typescript-eslint/no-extraneous-class': 'off',\n" ], "file_path": ".eslintrc.cjs", "type": "add", "edit_start_line_idx": 379 }
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* eslint-env browser */ 'use strict'; beforeEach(() => { jest.spyOn(console, 'error'); console.error.mockImplementation(() => {}); }); afterEach(() => { console.error.mockRestore(); }); test('can mock console.error calls from jsdom', () => { // copied and modified for tests from: // https://github.com/facebook/react/blob/46b3c3e4ae0d52565f7ed2344036a22016781ca0/packages/shared/invokeGuardedCallback.js#L62-L147 const fakeNode = document.createElement('react'); const evt = document.createEvent('Event'); const evtType = 'react-invokeguardedcallback'; function callCallback() { fakeNode.removeEventListener(evtType, callCallback, false); throw new Error('this is an error in an event callback'); } function onError(event) {} window.addEventListener('error', onError); fakeNode.addEventListener(evtType, callCallback, false); evt.initEvent(evtType, false, false); fakeNode.dispatchEvent(evt); window.removeEventListener('error', onError); expect(console.error).toHaveBeenCalledTimes(1); expect(console.error).toHaveBeenCalledWith( expect.objectContaining({ detail: expect.objectContaining({ message: 'this is an error in an event callback', }), }), ); });
e2e/console-jsdom/__tests__/console.test.js
0
https://github.com/jestjs/jest/commit/bd2305b374ff976e67579f188559d25d69443c30
[ 0.00017414387548342347, 0.00017133686924353242, 0.00016899564070627093, 0.00017100447439588606, 0.0000020087695702386554 ]
{ "id": 5, "code_window": [ " invocationCallOrder: [],\n", " results: [],\n", " };\n", " }\n", "\n", " private _makeComponent<T extends Record<string, any>>(\n", " metadata: MockMetadata<T, 'object'>,\n", " restore?: () => void,\n", " ): T;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " /* eslint-disable @typescript-eslint/unified-signatures */\n" ], "file_path": "packages/jest-mock/src/index.ts", "type": "add", "edit_start_line_idx": 607 }
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* eslint-disable local/ban-types-eventually, local/prefer-rest-params-eventually */ import {isPromise} from 'jest-util'; export type MockMetadataType = | 'object' | 'array' | 'regexp' | 'function' | 'constant' | 'collection' | 'null' | 'undefined'; // TODO remove re-export in Jest 30 export type MockFunctionMetadataType = MockMetadataType; export type MockMetadata<T, MetadataType = MockMetadataType> = { ref?: number; members?: Record<string, MockMetadata<T>>; mockImpl?: T; name?: string; refID?: number; type?: MetadataType; value?: T; length?: number; }; // TODO remove re-export in Jest 30 export type MockFunctionMetadata< T = unknown, MetadataType = MockMetadataType, > = MockMetadata<T, MetadataType>; export type ClassLike = {new (...args: any): any}; export type FunctionLike = (...args: any) => any; export type ConstructorLikeKeys<T> = keyof { [K in keyof T as Required<T>[K] extends ClassLike ? K : never]: T[K]; }; export type MethodLikeKeys<T> = keyof { [K in keyof T as Required<T>[K] extends FunctionLike ? K : never]: T[K]; }; export type PropertyLikeKeys<T> = Exclude< keyof T, ConstructorLikeKeys<T> | MethodLikeKeys<T> >; export type MockedClass<T extends ClassLike> = MockInstance< (...args: ConstructorParameters<T>) => Mocked<InstanceType<T>> > & MockedObject<T>; export type MockedFunction<T extends FunctionLike> = MockInstance<T> & MockedObject<T>; type MockedFunctionShallow<T extends FunctionLike> = MockInstance<T> & T; export type MockedObject<T extends object> = { [K in keyof T]: T[K] extends ClassLike ? MockedClass<T[K]> : T[K] extends FunctionLike ? MockedFunction<T[K]> : T[K] extends object ? MockedObject<T[K]> : T[K]; } & T; type MockedObjectShallow<T extends object> = { [K in keyof T]: T[K] extends ClassLike ? MockedClass<T[K]> : T[K] extends FunctionLike ? MockedFunctionShallow<T[K]> : T[K]; } & T; export type Mocked<T> = T extends ClassLike ? MockedClass<T> : T extends FunctionLike ? MockedFunction<T> : T extends object ? MockedObject<T> : T; export type MockedShallow<T> = T extends ClassLike ? MockedClass<T> : T extends FunctionLike ? MockedFunctionShallow<T> : T extends object ? MockedObjectShallow<T> : T; export type UnknownFunction = (...args: Array<unknown>) => unknown; export type UnknownClass = {new (...args: Array<unknown>): unknown}; export type SpiedClass<T extends ClassLike = UnknownClass> = MockInstance< (...args: ConstructorParameters<T>) => InstanceType<T> >; export type SpiedFunction<T extends FunctionLike = UnknownFunction> = MockInstance<(...args: Parameters<T>) => ReturnType<T>>; export type SpiedGetter<T> = MockInstance<() => T>; export type SpiedSetter<T> = MockInstance<(arg: T) => void>; export type Spied<T extends ClassLike | FunctionLike> = T extends ClassLike ? SpiedClass<T> : T extends FunctionLike ? SpiedFunction<T> : never; // TODO in Jest 30 remove `SpyInstance` in favour of `Spied` // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface SpyInstance<T extends FunctionLike = UnknownFunction> extends MockInstance<T> {} /** * All what the internal typings need is to be sure that we have any-function. * `FunctionLike` type ensures that and helps to constrain the type as well. * The default of `UnknownFunction` makes sure that `any`s do not leak to the * user side. For instance, calling `fn()` without implementation will return * a mock of `(...args: Array<unknown>) => unknown` type. If implementation * is provided, its typings are inferred correctly. */ export interface Mock<T extends FunctionLike = UnknownFunction> extends Function, MockInstance<T> { new (...args: Parameters<T>): ReturnType<T>; (...args: Parameters<T>): ReturnType<T>; } type ResolveType<T extends FunctionLike> = ReturnType<T> extends PromiseLike< infer U > ? U : never; type RejectType<T extends FunctionLike> = ReturnType<T> extends PromiseLike<any> ? unknown : never; export interface MockInstance<T extends FunctionLike = UnknownFunction> { _isMockFunction: true; _protoImpl: Function; getMockImplementation(): T | undefined; getMockName(): string; mock: MockFunctionState<T>; mockClear(): this; mockReset(): this; mockRestore(): void; mockImplementation(fn: T): this; mockImplementationOnce(fn: T): this; withImplementation(fn: T, callback: () => Promise<unknown>): Promise<void>; withImplementation(fn: T, callback: () => void): void; mockName(name: string): this; mockReturnThis(): this; mockReturnValue(value: ReturnType<T>): this; mockReturnValueOnce(value: ReturnType<T>): this; mockResolvedValue(value: ResolveType<T>): this; mockResolvedValueOnce(value: ResolveType<T>): this; mockRejectedValue(value: RejectType<T>): this; mockRejectedValueOnce(value: RejectType<T>): this; } export interface Replaced<T = unknown> { /** * Restore property to its original value known at the time of mocking. */ restore(): void; /** * Change the value of the property. */ replaceValue(value: T): this; } type ReplacedPropertyRestorer<T extends object, K extends keyof T> = { (): void; object: T; property: K; replaced: Replaced<T[K]>; }; type MockFunctionResultIncomplete = { type: 'incomplete'; /** * Result of a single call to a mock function that has not yet completed. * This occurs if you test the result from within the mock function itself, * or from within a function that was called by the mock. */ value: undefined; }; type MockFunctionResultReturn<T extends FunctionLike = UnknownFunction> = { type: 'return'; /** * Result of a single call to a mock function that returned. */ value: ReturnType<T>; }; type MockFunctionResultThrow = { type: 'throw'; /** * Result of a single call to a mock function that threw. */ value: unknown; }; type MockFunctionResult<T extends FunctionLike = UnknownFunction> = | MockFunctionResultIncomplete | MockFunctionResultReturn<T> | MockFunctionResultThrow; type MockFunctionState<T extends FunctionLike = UnknownFunction> = { /** * List of the call arguments of all calls that have been made to the mock. */ calls: Array<Parameters<T>>; /** * List of all the object instances that have been instantiated from the mock. */ instances: Array<ReturnType<T>>; /** * List of all the function contexts that have been applied to calls to the mock. */ contexts: Array<ThisParameterType<T>>; /** * List of the call order indexes of the mock. Jest is indexing the order of * invocations of all mocks in a test file. The index is starting with `1`. */ invocationCallOrder: Array<number>; /** * List of the call arguments of the last call that was made to the mock. * If the function was not called, it will return `undefined`. */ lastCall?: Parameters<T>; /** * List of the results of all calls that have been made to the mock. */ results: Array<MockFunctionResult<T>>; }; type MockFunctionConfig = { mockImpl: Function | undefined; mockName: string; specificMockImpls: Array<Function>; }; const MOCK_CONSTRUCTOR_NAME = 'mockConstructor'; const FUNCTION_NAME_RESERVED_PATTERN = /[\s!-/:-@[-`{-~]/; const FUNCTION_NAME_RESERVED_REPLACE = new RegExp( FUNCTION_NAME_RESERVED_PATTERN.source, 'g', ); const RESERVED_KEYWORDS = new Set([ 'arguments', 'await', 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'enum', 'eval', 'export', 'extends', 'false', 'finally', 'for', 'function', 'if', 'implements', 'import', 'in', 'instanceof', 'interface', 'let', 'new', 'null', 'package', 'private', 'protected', 'public', 'return', 'static', 'super', 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'var', 'void', 'while', 'with', 'yield', ]); function matchArity(fn: Function, length: number): Function { let mockConstructor; switch (length) { case 1: mockConstructor = function (this: unknown, _a: unknown) { return fn.apply(this, arguments); }; break; case 2: mockConstructor = function (this: unknown, _a: unknown, _b: unknown) { return fn.apply(this, arguments); }; break; case 3: mockConstructor = function ( this: unknown, _a: unknown, _b: unknown, _c: unknown, ) { return fn.apply(this, arguments); }; break; case 4: mockConstructor = function ( this: unknown, _a: unknown, _b: unknown, _c: unknown, _d: unknown, ) { return fn.apply(this, arguments); }; break; case 5: mockConstructor = function ( this: unknown, _a: unknown, _b: unknown, _c: unknown, _d: unknown, _e: unknown, ) { return fn.apply(this, arguments); }; break; case 6: mockConstructor = function ( this: unknown, _a: unknown, _b: unknown, _c: unknown, _d: unknown, _e: unknown, _f: unknown, ) { return fn.apply(this, arguments); }; break; case 7: mockConstructor = function ( this: unknown, _a: unknown, _b: unknown, _c: unknown, _d: unknown, _e: unknown, _f: unknown, _g: unknown, ) { return fn.apply(this, arguments); }; break; case 8: mockConstructor = function ( this: unknown, _a: unknown, _b: unknown, _c: unknown, _d: unknown, _e: unknown, _f: unknown, _g: unknown, _h: unknown, ) { return fn.apply(this, arguments); }; break; case 9: mockConstructor = function ( this: unknown, _a: unknown, _b: unknown, _c: unknown, _d: unknown, _e: unknown, _f: unknown, _g: unknown, _h: unknown, _i: unknown, ) { return fn.apply(this, arguments); }; break; default: mockConstructor = function (this: unknown) { return fn.apply(this, arguments); }; break; } return mockConstructor; } function getObjectType(value: unknown): string { return Object.prototype.toString.apply(value).slice(8, -1); } function getType(ref?: unknown): MockMetadataType | null { const typeName = getObjectType(ref); if ( typeName === 'Function' || typeName === 'AsyncFunction' || typeName === 'GeneratorFunction' || typeName === 'AsyncGeneratorFunction' ) { return 'function'; } else if (Array.isArray(ref)) { return 'array'; } else if (typeName === 'Object' || typeName === 'Module') { return 'object'; } else if ( typeName === 'Number' || typeName === 'String' || typeName === 'Boolean' || typeName === 'Symbol' ) { return 'constant'; } else if ( typeName === 'Map' || typeName === 'WeakMap' || typeName === 'Set' ) { return 'collection'; } else if (typeName === 'RegExp') { return 'regexp'; } else if (ref === undefined) { return 'undefined'; } else if (ref === null) { return 'null'; } else { return null; } } function isReadonlyProp(object: unknown, prop: string): boolean { if ( prop === 'arguments' || prop === 'caller' || prop === 'callee' || prop === 'name' || prop === 'length' ) { const typeName = getObjectType(object); return ( typeName === 'Function' || typeName === 'AsyncFunction' || typeName === 'GeneratorFunction' || typeName === 'AsyncGeneratorFunction' ); } if ( prop === 'source' || prop === 'global' || prop === 'ignoreCase' || prop === 'multiline' ) { return getObjectType(object) === 'RegExp'; } return false; } export class ModuleMocker { private readonly _environmentGlobal: typeof globalThis; private _mockState: WeakMap<Mock, MockFunctionState>; private _mockConfigRegistry: WeakMap<Function, MockFunctionConfig>; private _spyState: Set<() => void>; private _invocationCallCounter: number; /** * @see README.md * @param global Global object of the test environment, used to create * mocks */ constructor(global: typeof globalThis) { this._environmentGlobal = global; this._mockState = new WeakMap(); this._mockConfigRegistry = new WeakMap(); this._spyState = new Set(); this._invocationCallCounter = 1; } private _getSlots(object?: Record<string, any>): Array<string> { if (!object) { return []; } const slots = new Set<string>(); const EnvObjectProto = this._environmentGlobal.Object.prototype; const EnvFunctionProto = this._environmentGlobal.Function.prototype; const EnvRegExpProto = this._environmentGlobal.RegExp.prototype; // Also check the builtins in the current context as they leak through // core node modules. const ObjectProto = Object.prototype; const FunctionProto = Function.prototype; const RegExpProto = RegExp.prototype; // Properties of Object.prototype, Function.prototype and RegExp.prototype // are never reported as slots while ( object != null && object !== EnvObjectProto && object !== EnvFunctionProto && object !== EnvRegExpProto && object !== ObjectProto && object !== FunctionProto && object !== RegExpProto ) { const ownNames = Object.getOwnPropertyNames(object); for (let i = 0; i < ownNames.length; i++) { const prop = ownNames[i]; if (!isReadonlyProp(object, prop)) { const propDesc = Object.getOwnPropertyDescriptor(object, prop); if ((propDesc !== undefined && !propDesc.get) || object.__esModule) { slots.add(prop); } } } object = Object.getPrototypeOf(object); } return Array.from(slots); } private _ensureMockConfig(f: Mock): MockFunctionConfig { let config = this._mockConfigRegistry.get(f); if (!config) { config = this._defaultMockConfig(); this._mockConfigRegistry.set(f, config); } return config; } private _ensureMockState<T extends UnknownFunction>( f: Mock<T>, ): MockFunctionState<T> { let state = this._mockState.get(f); if (!state) { state = this._defaultMockState(); this._mockState.set(f, state); } if (state.calls.length > 0) { state.lastCall = state.calls[state.calls.length - 1]; } return state; } private _defaultMockConfig(): MockFunctionConfig { return { mockImpl: undefined, mockName: 'jest.fn()', specificMockImpls: [], }; } private _defaultMockState(): MockFunctionState { return { calls: [], contexts: [], instances: [], invocationCallOrder: [], results: [], }; } private _makeComponent<T extends Record<string, any>>( metadata: MockMetadata<T, 'object'>, restore?: () => void, ): T; private _makeComponent<T extends Array<unknown>>( metadata: MockMetadata<T, 'array'>, restore?: () => void, ): T; private _makeComponent<T extends RegExp>( metadata: MockMetadata<T, 'regexp'>, restore?: () => void, ): T; private _makeComponent<T>( metadata: MockMetadata<T, 'constant' | 'collection' | 'null' | 'undefined'>, restore?: () => void, ): T; private _makeComponent<T extends UnknownFunction>( metadata: MockMetadata<T, 'function'>, restore?: () => void, ): Mock<T>; private _makeComponent<T extends UnknownFunction>( metadata: MockMetadata<T>, restore?: () => void, ): Record<string, any> | Array<unknown> | RegExp | T | Mock | undefined { if (metadata.type === 'object') { return new this._environmentGlobal.Object(); } else if (metadata.type === 'array') { return new this._environmentGlobal.Array(); } else if (metadata.type === 'regexp') { return new this._environmentGlobal.RegExp(''); } else if ( metadata.type === 'constant' || metadata.type === 'collection' || metadata.type === 'null' || metadata.type === 'undefined' ) { return metadata.value; } else if (metadata.type === 'function') { const prototype = (metadata.members && metadata.members.prototype && metadata.members.prototype.members) || {}; const prototypeSlots = this._getSlots(prototype); // eslint-disable-next-line @typescript-eslint/no-this-alias const mocker = this; const mockConstructor = matchArity(function ( this: ReturnType<T>, ...args: Parameters<T> ) { const mockState = mocker._ensureMockState(f); const mockConfig = mocker._ensureMockConfig(f); mockState.instances.push(this); mockState.contexts.push(this); mockState.calls.push(args); // Create and record an "incomplete" mock result immediately upon // calling rather than waiting for the mock to return. This avoids // issues caused by recursion where results can be recorded in the // wrong order. const mockResult: MockFunctionResult = { type: 'incomplete', value: undefined, }; mockState.results.push(mockResult); mockState.invocationCallOrder.push(mocker._invocationCallCounter++); // Will be set to the return value of the mock if an error is not thrown let finalReturnValue; // Will be set to the error that is thrown by the mock (if it throws) let thrownError; // Will be set to true if the mock throws an error. The presence of a // value in `thrownError` is not a 100% reliable indicator because a // function could throw a value of undefined. let callDidThrowError = false; try { // The bulk of the implementation is wrapped in an immediately // executed arrow function so the return value of the mock function // can be easily captured and recorded, despite the many separate // return points within the logic. finalReturnValue = (() => { if (this instanceof f) { // This is probably being called as a constructor for (const slot of prototypeSlots) { // Copy prototype methods to the instance to make // it easier to interact with mock instance call and // return values if (prototype[slot].type === 'function') { // @ts-expect-error no index signature const protoImpl = this[slot]; // @ts-expect-error no index signature this[slot] = mocker.generateFromMetadata(prototype[slot]); // @ts-expect-error no index signature this[slot]._protoImpl = protoImpl; } } // Run the mock constructor implementation const mockImpl = mockConfig.specificMockImpls.length > 0 ? mockConfig.specificMockImpls.shift() : mockConfig.mockImpl; return mockImpl && mockImpl.apply(this, arguments); } // If mockImplementationOnce()/mockImplementation() is last set, // implementation use the mock let specificMockImpl = mockConfig.specificMockImpls.shift(); if (specificMockImpl === undefined) { specificMockImpl = mockConfig.mockImpl; } if (specificMockImpl) { return specificMockImpl.apply(this, arguments); } // Otherwise use prototype implementation if (f._protoImpl) { return f._protoImpl.apply(this, arguments); } return undefined; })(); } catch (error) { // Store the thrown error so we can record it, then re-throw it. thrownError = error; callDidThrowError = true; throw error; } finally { // Record the result of the function. // NOTE: Intentionally NOT pushing/indexing into the array of mock // results here to avoid corrupting results data if mockClear() // is called during the execution of the mock. // @ts-expect-error reassigning 'incomplete' mockResult.type = callDidThrowError ? 'throw' : 'return'; mockResult.value = callDidThrowError ? thrownError : finalReturnValue; } return finalReturnValue; }, metadata.length || 0); const f = this._createMockFunction(metadata, mockConstructor) as Mock; f._isMockFunction = true; f.getMockImplementation = () => this._ensureMockConfig(f).mockImpl as T; if (typeof restore === 'function') { this._spyState.add(restore); } this._mockState.set(f, this._defaultMockState()); this._mockConfigRegistry.set(f, this._defaultMockConfig()); Object.defineProperty(f, 'mock', { configurable: false, enumerable: true, get: () => this._ensureMockState(f), set: val => this._mockState.set(f, val), }); f.mockClear = () => { this._mockState.delete(f); return f; }; f.mockReset = () => { f.mockClear(); this._mockConfigRegistry.delete(f); return f; }; f.mockRestore = () => { f.mockReset(); return restore ? restore() : undefined; }; f.mockReturnValueOnce = (value: ReturnType<T>) => // next function call will return this value or default return value f.mockImplementationOnce(() => value); f.mockResolvedValueOnce = (value: ResolveType<T>) => f.mockImplementationOnce(() => this._environmentGlobal.Promise.resolve(value), ); f.mockRejectedValueOnce = (value: unknown) => f.mockImplementationOnce(() => this._environmentGlobal.Promise.reject(value), ); f.mockReturnValue = (value: ReturnType<T>) => // next function call will return specified return value or this one f.mockImplementation(() => value); f.mockResolvedValue = (value: ResolveType<T>) => f.mockImplementation(() => this._environmentGlobal.Promise.resolve(value), ); f.mockRejectedValue = (value: unknown) => f.mockImplementation(() => this._environmentGlobal.Promise.reject(value), ); f.mockImplementationOnce = (fn: T) => { // next function call will use this mock implementation return value // or default mock implementation return value const mockConfig = this._ensureMockConfig(f); mockConfig.specificMockImpls.push(fn); return f; }; f.withImplementation = withImplementation.bind(this); function withImplementation(fn: T, callback: () => void): void; function withImplementation( fn: T, callback: () => Promise<unknown>, ): Promise<void>; function withImplementation( this: ModuleMocker, fn: T, callback: (() => void) | (() => Promise<unknown>), ): void | Promise<void> { // Remember previous mock implementation, then set new one const mockConfig = this._ensureMockConfig(f); const previousImplementation = mockConfig.mockImpl; const previousSpecificImplementations = mockConfig.specificMockImpls; mockConfig.mockImpl = fn; mockConfig.specificMockImpls = []; const returnedValue = callback(); if (isPromise(returnedValue)) { return returnedValue.then(() => { mockConfig.mockImpl = previousImplementation; mockConfig.specificMockImpls = previousSpecificImplementations; }); } else { mockConfig.mockImpl = previousImplementation; mockConfig.specificMockImpls = previousSpecificImplementations; } } f.mockImplementation = (fn: T) => { // next function call will use mock implementation return value const mockConfig = this._ensureMockConfig(f); mockConfig.mockImpl = fn; return f; }; f.mockReturnThis = () => f.mockImplementation(function (this: ReturnType<T>) { return this; }); f.mockName = (name: string) => { if (name) { const mockConfig = this._ensureMockConfig(f); mockConfig.mockName = name; } return f; }; f.getMockName = () => { const mockConfig = this._ensureMockConfig(f); return mockConfig.mockName || 'jest.fn()'; }; if (metadata.mockImpl) { f.mockImplementation(metadata.mockImpl); } return f; } else { const unknownType = metadata.type || 'undefined type'; throw new Error(`Unrecognized type ${unknownType}`); } } private _createMockFunction<T extends UnknownFunction>( metadata: MockMetadata<T>, mockConstructor: Function, ): Function { let name = metadata.name; if (!name) { return mockConstructor; } // Preserve `name` property of mocked function. const boundFunctionPrefix = 'bound '; let bindCall = ''; // if-do-while for perf reasons. The common case is for the if to fail. if (name.startsWith(boundFunctionPrefix)) { do { name = name.substring(boundFunctionPrefix.length); // Call bind() just to alter the function name. bindCall = '.bind(null)'; } while (name && name.startsWith(boundFunctionPrefix)); } // Special case functions named `mockConstructor` to guard for infinite loops if (name === MOCK_CONSTRUCTOR_NAME) { return mockConstructor; } if ( // It's a syntax error to define functions with a reserved keyword as name RESERVED_KEYWORDS.has(name) || // It's also a syntax error to define functions with a name that starts with a number /^\d/.test(name) ) { name = `$${name}`; } // It's also a syntax error to define a function with a reserved character // as part of it's name. if (FUNCTION_NAME_RESERVED_PATTERN.test(name)) { name = name.replace(FUNCTION_NAME_RESERVED_REPLACE, '$'); } const body = `return function ${name}() {` + ` return ${MOCK_CONSTRUCTOR_NAME}.apply(this,arguments);` + `}${bindCall}`; const createConstructor = new this._environmentGlobal.Function( MOCK_CONSTRUCTOR_NAME, body, ); return createConstructor(mockConstructor); } private _generateMock<T>( metadata: MockMetadata<T>, callbacks: Array<Function>, refs: Record< number, Record<string, any> | Array<unknown> | RegExp | T | Mock | undefined >, ): Mocked<T> { // metadata not compatible but it's the same type, maybe problem with // overloading of _makeComponent and not _generateMock? // @ts-expect-error - unsure why TSC complains here? const mock = this._makeComponent(metadata); if (metadata.refID != null) { refs[metadata.refID] = mock; } for (const slot of this._getSlots(metadata.members)) { const slotMetadata = (metadata.members && metadata.members[slot]) || {}; if (slotMetadata.ref == null) { mock[slot] = this._generateMock(slotMetadata, callbacks, refs); } else { callbacks.push( (function (ref) { return () => (mock[slot] = refs[ref]); })(slotMetadata.ref), ); } } if ( metadata.type !== 'undefined' && metadata.type !== 'null' && mock.prototype && typeof mock.prototype === 'object' ) { mock.prototype.constructor = mock; } return mock as Mocked<T>; } /** * Check whether the given property of an object has been already replaced. */ private _findReplacedProperty<T extends object, K extends keyof T>( object: T, propertyKey: K, ): ReplacedPropertyRestorer<T, K> | undefined { for (const spyState of this._spyState) { if ( 'object' in spyState && 'property' in spyState && spyState.object === object && spyState.property === propertyKey ) { return spyState as ReplacedPropertyRestorer<T, K>; } } return; } /** * @see README.md * @param metadata Metadata for the mock in the schema returned by the * getMetadata method of this module. */ generateFromMetadata<T>(metadata: MockMetadata<T>): Mocked<T> { const callbacks: Array<Function> = []; const refs = {}; const mock = this._generateMock<T>(metadata, callbacks, refs); for (const setter of callbacks) setter(); return mock; } /** * @see README.md * @param component The component for which to retrieve metadata. */ getMetadata<T = unknown>( component: T, _refs?: Map<T, number>, ): MockMetadata<T> | null { const refs = _refs || new Map<T, number>(); const ref = refs.get(component); if (ref != null) { return {ref}; } const type = getType(component); if (!type) { return null; } const metadata: MockMetadata<T> = {type}; if ( type === 'constant' || type === 'collection' || type === 'undefined' || type === 'null' ) { metadata.value = component; return metadata; } else if (type === 'function') { // @ts-expect-error component is a function so it has a name, but not // necessarily a string: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#function_names_in_classes const componentName = component.name; if (typeof componentName === 'string') { metadata.name = componentName; } if (this.isMockFunction(component)) { metadata.mockImpl = component.getMockImplementation() as T; } } metadata.refID = refs.size; refs.set(component, metadata.refID); let members: Record<string, MockMetadata<T>> | null = null; // Leave arrays alone if (type !== 'array') { // @ts-expect-error component is object for (const slot of this._getSlots(component)) { if ( type === 'function' && this.isMockFunction(component) && slot.match(/^mock/) ) { continue; } // @ts-expect-error no index signature const slotMetadata = this.getMetadata<T>(component[slot], refs); if (slotMetadata) { if (!members) { members = {}; } members[slot] = slotMetadata; } } } if (members) { metadata.members = members; } return metadata; } isMockFunction<T extends FunctionLike = UnknownFunction>( fn: MockInstance<T>, ): fn is MockInstance<T>; isMockFunction<P extends Array<unknown>, R>( fn: (...args: P) => R, ): fn is Mock<(...args: P) => R>; isMockFunction(fn: unknown): fn is Mock<UnknownFunction>; isMockFunction(fn: unknown): fn is Mock<UnknownFunction> { return fn != null && (fn as Mock)._isMockFunction === true; } fn<T extends FunctionLike = UnknownFunction>(implementation?: T): Mock<T> { const length = implementation ? implementation.length : 0; const fn = this._makeComponent<T>({ length, type: 'function', }); if (implementation) { fn.mockImplementation(implementation); } return fn; } spyOn< T extends object, K extends PropertyLikeKeys<T>, V extends Required<T>[K], A extends 'get' | 'set', >( object: T, methodKey: K, accessType: A, ): A extends 'get' ? SpiedGetter<V> : A extends 'set' ? SpiedSetter<V> : never; spyOn< T extends object, K extends ConstructorLikeKeys<T> | MethodLikeKeys<T>, V extends Required<T>[K], >( object: T, methodKey: K, ): V extends ClassLike | FunctionLike ? Spied<V> : never; spyOn<T extends object>( object: T, methodKey: keyof T, accessType?: 'get' | 'set', ): MockInstance { if ( object == null || (typeof object !== 'object' && typeof object !== 'function') ) { throw new Error( `Cannot use spyOn on a primitive value; ${this._typeOf(object)} given`, ); } if (methodKey == null) { throw new Error('No property name supplied'); } if (accessType) { return this._spyOnProperty(object, methodKey, accessType); } const original = object[methodKey]; if (!original) { throw new Error( `Property \`${String( methodKey, )}\` does not exist in the provided object`, ); } if (!this.isMockFunction(original)) { if (typeof original !== 'function') { throw new Error( `Cannot spy on the \`${String( methodKey, )}\` property because it is not a function; ${this._typeOf( original, )} given instead.${ typeof original === 'object' ? '' : ` If you are trying to mock a property, use \`jest.replaceProperty(object, '${String( methodKey, )}', value)\` instead.` }`, ); } const isMethodOwner = Object.prototype.hasOwnProperty.call( object, methodKey, ); let descriptor = Object.getOwnPropertyDescriptor(object, methodKey); let proto = Object.getPrototypeOf(object); while (!descriptor && proto !== null) { descriptor = Object.getOwnPropertyDescriptor(proto, methodKey); proto = Object.getPrototypeOf(proto); } let mock: Mock; if (descriptor && descriptor.get) { const originalGet = descriptor.get; mock = this._makeComponent({type: 'function'}, () => { descriptor!.get = originalGet; Object.defineProperty(object, methodKey, descriptor!); }); descriptor.get = () => mock; Object.defineProperty(object, methodKey, descriptor); } else { mock = this._makeComponent({type: 'function'}, () => { if (isMethodOwner) { object[methodKey] = original; } else { delete object[methodKey]; } }); // @ts-expect-error overriding original method with a Mock object[methodKey] = mock; } mock.mockImplementation(function (this: unknown) { return original.apply(this, arguments); }); } return object[methodKey] as Mock; } private _spyOnProperty<T extends object>( object: T, propertyKey: keyof T, accessType: 'get' | 'set', ): MockInstance { let descriptor = Object.getOwnPropertyDescriptor(object, propertyKey); let proto = Object.getPrototypeOf(object); while (!descriptor && proto !== null) { descriptor = Object.getOwnPropertyDescriptor(proto, propertyKey); proto = Object.getPrototypeOf(proto); } if (!descriptor) { throw new Error( `Property \`${String( propertyKey, )}\` does not exist in the provided object`, ); } if (!descriptor.configurable) { throw new Error( `Property \`${String(propertyKey)}\` is not declared configurable`, ); } if (!descriptor[accessType]) { throw new Error( `Property \`${String( propertyKey, )}\` does not have access type ${accessType}`, ); } const original = descriptor[accessType]; if (!this.isMockFunction(original)) { if (typeof original !== 'function') { throw new Error( `Cannot spy on the ${String( propertyKey, )} property because it is not a function; ${this._typeOf( original, )} given instead.${ typeof original === 'object' ? '' : ` If you are trying to mock a property, use \`jest.replaceProperty(object, '${String( propertyKey, )}', value)\` instead.` }`, ); } descriptor[accessType] = this._makeComponent({type: 'function'}, () => { // @ts-expect-error: mock is assignable descriptor![accessType] = original; Object.defineProperty(object, propertyKey, descriptor!); }); (descriptor[accessType] as Mock).mockImplementation(function ( this: unknown, ) { // @ts-expect-error - wrong context return original.apply(this, arguments); }); } Object.defineProperty(object, propertyKey, descriptor); return descriptor[accessType] as Mock; } replaceProperty<T extends object, K extends keyof T>( object: T, propertyKey: K, value: T[K], ): Replaced<T[K]> { if ( object == null || (typeof object !== 'object' && typeof object !== 'function') ) { throw new Error( `Cannot use replaceProperty on a primitive value; ${this._typeOf( object, )} given`, ); } if (propertyKey == null) { throw new Error('No property name supplied'); } let descriptor = Object.getOwnPropertyDescriptor(object, propertyKey); let proto = Object.getPrototypeOf(object); while (!descriptor && proto !== null) { descriptor = Object.getOwnPropertyDescriptor(proto, propertyKey); proto = Object.getPrototypeOf(proto); } if (!descriptor) { throw new Error( `Property \`${String( propertyKey, )}\` does not exist in the provided object`, ); } if (!descriptor.configurable) { throw new Error( `Property \`${String(propertyKey)}\` is not declared configurable`, ); } if (descriptor.get !== undefined) { throw new Error( `Cannot replace the \`${String( propertyKey, )}\` property because it has a getter. Use \`jest.spyOn(object, '${String( propertyKey, )}', 'get').mockReturnValue(value)\` instead.`, ); } if (descriptor.set !== undefined) { throw new Error( `Cannot replace the \`${String( propertyKey, )}\` property because it has a setter. Use \`jest.spyOn(object, '${String( propertyKey, )}', 'set').mockReturnValue(value)\` instead.`, ); } if (typeof descriptor.value === 'function') { throw new Error( `Cannot replace the \`${String( propertyKey, )}\` property because it is a function. Use \`jest.spyOn(object, '${String( propertyKey, )}')\` instead.`, ); } const existingRestore = this._findReplacedProperty(object, propertyKey); if (existingRestore) { return existingRestore.replaced.replaceValue(value); } const isPropertyOwner = Object.prototype.hasOwnProperty.call( object, propertyKey, ); const originalValue = descriptor.value; const restore: ReplacedPropertyRestorer<T, K> = () => { if (isPropertyOwner) { object[propertyKey] = originalValue; } else { delete object[propertyKey]; } }; const replaced: Replaced<T[K]> = { replaceValue: value => { object[propertyKey] = value; return replaced; }, restore: () => { restore(); this._spyState.delete(restore); }, }; restore.object = object; restore.property = propertyKey; restore.replaced = replaced; this._spyState.add(restore); return replaced.replaceValue(value); } clearAllMocks(): void { this._mockState = new WeakMap(); } resetAllMocks(): void { this._mockConfigRegistry = new WeakMap(); this._mockState = new WeakMap(); } restoreAllMocks(): void { for (const restore of this._spyState) restore(); this._spyState = new Set(); } private _typeOf(value: unknown): string { return value == null ? `${value}` : typeof value; } mocked<T extends object>(source: T, options?: {shallow: false}): Mocked<T>; mocked<T extends object>( source: T, options: {shallow: true}, ): MockedShallow<T>; mocked<T extends object>( source: T, _options?: {shallow: boolean}, ): Mocked<T> | MockedShallow<T> { return source as Mocked<T> | MockedShallow<T>; } } const JestMock = new ModuleMocker(globalThis); export const fn = JestMock.fn.bind(JestMock); export const spyOn = JestMock.spyOn.bind(JestMock); export const mocked = JestMock.mocked.bind(JestMock); export const replaceProperty = JestMock.replaceProperty.bind(JestMock);
packages/jest-mock/src/index.ts
1
https://github.com/jestjs/jest/commit/bd2305b374ff976e67579f188559d25d69443c30
[ 0.9974920749664307, 0.06938965618610382, 0.0001612826163182035, 0.00021123541228007525, 0.23759165406227112 ]
{ "id": 5, "code_window": [ " invocationCallOrder: [],\n", " results: [],\n", " };\n", " }\n", "\n", " private _makeComponent<T extends Record<string, any>>(\n", " metadata: MockMetadata<T, 'object'>,\n", " restore?: () => void,\n", " ): T;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " /* eslint-disable @typescript-eslint/unified-signatures */\n" ], "file_path": "packages/jest-mock/src/index.ts", "type": "add", "edit_start_line_idx": 607 }
{ "jest": {} }
e2e/wrong-env/package.json
0
https://github.com/jestjs/jest/commit/bd2305b374ff976e67579f188559d25d69443c30
[ 0.00017879238293971866, 0.00017879238293971866, 0.00017879238293971866, 0.00017879238293971866, 0 ]