refactor: migrate tools to prettier formatting (#53947)

Migrate formatting to prettier for tools directory from clang-format

PR Close #53947
This commit is contained in:
Joey Perrott
2024-01-16 21:51:06 +00:00
committed by Dylan Hunn
parent 6ac0a68d73
commit 28aa7b3188
28 changed files with 696 additions and 550 deletions
+7 -1
View File
@@ -5,7 +5,10 @@ import {FormatConfig} from '@angular/ng-dev';
*/
export const format: FormatConfig = {
'prettier': {
'matchers': ['**/*.{yaml,yml}'],
'matchers': [
'**/*.{yaml,yml}',
'tools/**/*.{js,ts}',
],
},
'clang-format': {
'matchers': [
@@ -31,6 +34,9 @@ export const format: FormatConfig = {
'!packages/common/src/i18n/currencies.ts',
// Temporarily disable formatting for adev
'!adev/**',
// Migrated to prettier
'!tools/**/*.{js,ts}',
],
},
'buildifier': true,
@@ -22,8 +22,7 @@ class BazelRunfileResolutionPlugin {
// Update the request to refer to the runfile resolved file path.
resolver.doResolve('resolve', {...request, request: resolvedPath}, null, callback, true);
return;
} catch {
}
} catch {}
// If the file could not be resolved through Bazel's runfile resolution, proceed
// with the default module resolvers.
callback();
@@ -34,5 +33,5 @@ class BazelRunfileResolutionPlugin {
// Configures a plugin which ensures that Madge can properly resolve specified
// dependencies through their configured module names.
module.exports = {
resolve: {plugins: [new BazelRunfileResolutionPlugin()]}
resolve: {plugins: [new BazelRunfileResolutionPlugin()]},
};
+50 -49
View File
@@ -34,10 +34,10 @@ const REPOS = ['angular', 'components', 'angular-cli'];
/**
* Handle flags for the script.
*/
const args = yargs.option('use-created', {type: 'boolean'})
.option('since', {type: 'string', demandOption: true})
.strictOptions()
.argv;
const args = yargs
.option('use-created', {type: 'boolean'})
.option('since', {type: 'string', demandOption: true})
.strictOptions().argv;
/**
* Authenticated instance of Github GraphQl API service, relies on a
@@ -48,7 +48,7 @@ const graphql = unauthenticatedGraphql.defaults({
// TODO(josephperrott): Remove reference to TOKEN environment variable as part of larger
// effort to migrate to expecting tokens via GITHUB_ACCESS_TOKEN environment variables.
authorization: `token ${process.env['TOKEN'] || process.env['GITHUB_ACCESS_TOKEN']}`,
}
},
});
/**
@@ -57,27 +57,32 @@ const graphql = unauthenticatedGraphql.defaults({
async function getAllOrgMembers() {
// The GraphQL query object to get a page of members of an organization.
const MEMBERS_QUERY = params(
{
$first: 'Int', // How many entries to get with each request
$after: 'String', // The cursor to start the page at
$owner: 'String!', // The organization to query for
},
{
organization: params({login: '$owner'}, {
{
$first: 'Int', // How many entries to get with each request
$after: 'String', // The cursor to start the page at
$owner: 'String!', // The organization to query for
},
{
organization: params(
{login: '$owner'},
{
membersWithRole: params(
{
first: '$first',
after: '$after',
{
first: '$first',
after: '$after',
},
{
nodes: [{login: types.string}],
pageInfo: {
hasNextPage: types.boolean,
endCursor: types.string,
},
{
nodes: [{login: types.string}],
pageInfo: {
hasNextPage: types.boolean,
endCursor: types.string,
},
}),
})
});
},
),
},
),
},
);
const query = graphqlQuery('members', MEMBERS_QUERY);
/**
@@ -103,10 +108,11 @@ async function getAllOrgMembers() {
while (hasNextPage) {
const {query, params} = queryBuilder(100, cursor);
const results = await graphql(query.toString(), params) as typeof MEMBERS_QUERY;
const results = (await graphql(query.toString(), params)) as typeof MEMBERS_QUERY;
results.organization.membersWithRole.nodes.forEach(
(node: {login: string}) => members.push(node.login));
results.organization.membersWithRole.nodes.forEach((node: {login: string}) =>
members.push(node.login),
);
hasNextPage = results.organization.membersWithRole.pageInfo.hasNextPage;
cursor = results.organization.membersWithRole.pageInfo.endCursor;
}
@@ -121,7 +127,7 @@ async function getAllOrgMembers() {
function buildQueryAndParams(username: string, date: string) {
// Whether the updated or created timestamp should be used.
const updatedOrCreated = args['use-created'] ? 'created' : 'updated';
let dataQueries: {[key: string]: {query: string, label: string}} = {};
let dataQueries: {[key: string]: {query: string; label: string}} = {};
// Add queries and params for all values queried for each repo.
for (let repo of REPOS) {
dataQueries = {
@@ -131,8 +137,7 @@ function buildQueryAndParams(username: string, date: string) {
label: `${ORG}/${repo} Issue Authored`,
},
[`${repo.replace(/[\/\-]/g, '_')}_issues_involved`]: {
query: `repo:${ORG}/${repo} is:issue -author:${username} involves:${username} ${
updatedOrCreated}:>${date}`,
query: `repo:${ORG}/${repo} is:issue -author:${username} involves:${username} ${updatedOrCreated}:>${date}`,
label: `${ORG}/${repo} Issue Involved`,
},
[`${repo.replace(/[\/\-]/g, '_')}_pr_author`]: {
@@ -144,13 +149,11 @@ function buildQueryAndParams(username: string, date: string) {
label: `${ORG}/${repo} PR Involved`,
},
[`${repo.replace(/[\/\-]/g, '_')}_pr_reviewed`]: {
query: `repo:${ORG}/${repo} is:pr -author:${username} reviewed-by:${username} ${
updatedOrCreated}:>${date}`,
query: `repo:${ORG}/${repo} is:pr -author:${username} reviewed-by:${username} ${updatedOrCreated}:>${date}`,
label: `${ORG}/${repo} PR Reviewed`,
},
[`${repo.replace(/[\/\-]/g, '_')}_pr_commented`]: {
query: `repo:${ORG}/${repo} is:pr -author:${username} commenter:${username} ${
updatedOrCreated}:>${date}`,
query: `repo:${ORG}/${repo} is:pr -author:${username} commenter:${username} ${updatedOrCreated}:>${date}`,
label: `${ORG}/${repo} PR Commented`,
},
};
@@ -163,8 +166,7 @@ function buildQueryAndParams(username: string, date: string) {
label: `${ORG} org Issue Authored`,
},
[`${ORG}_org_issues_involved`]: {
query: `org:${ORG} is:issue -author:${username} involves:${username} ${updatedOrCreated}:>${
date}`,
query: `org:${ORG} is:issue -author:${username} involves:${username} ${updatedOrCreated}:>${date}`,
label: `${ORG} org Issue Involved`,
},
[`${ORG}_org_pr_author`]: {
@@ -176,13 +178,11 @@ function buildQueryAndParams(username: string, date: string) {
label: `${ORG} org PR Involved`,
},
[`${ORG}_org_pr_reviewed`]: {
query: `org:${ORG} is:pr -author:${username} reviewed-by:${username} ${updatedOrCreated}:>${
date}`,
query: `org:${ORG} is:pr -author:${username} reviewed-by:${username} ${updatedOrCreated}:>${date}`,
label: `${ORG} org PR Reviewed`,
},
[`${ORG}_org_pr_commented`]: {
query:
`org:${ORG} is:pr -author:${username} commenter:${username} ${updatedOrCreated}:>${date}`,
query: `org:${ORG} is:pr -author:${username} commenter:${username} ${updatedOrCreated}:>${date}`,
label: `${ORG} org PR Commented`,
},
};
@@ -191,7 +191,7 @@ function buildQueryAndParams(username: string, date: string) {
* Gets the labels for each requested value to be used as headers.
*/
function getLabels(pairs: typeof dataQueries) {
return Object.values(pairs).map(val => val.label);
return Object.values(pairs).map((val) => val.label);
}
/**
@@ -201,13 +201,14 @@ function buildQueryAndParams(username: string, date: string) {
const output: {[key: string]: {}} = {};
Object.entries(pairs).map(([key, val]) => {
output[alias(key, 'search')] = params(
{
query: `"${val.query}"`,
type: 'ISSUE',
},
{
issueCount: types.number,
});
{
query: `"${val.query}"`,
type: 'ISSUE',
},
{
issueCount: types.number,
},
);
});
return output;
}
@@ -229,7 +230,7 @@ async function run(date: string) {
for (const username of allOrgMembers) {
const results = await graphql(buildQueryAndParams(username, date).query.toString());
const values = Object.values(results).map(result => `${result.issueCount}`);
const values = Object.values(results).map((result) => `${result.issueCount}`);
console.info([username, ...values].join(','));
}
} catch (error) {
+18 -13
View File
@@ -13,17 +13,22 @@ module.exports = (gulp) => () => {
// the tag of zone.js will start with `zone.js-`, such as `zone.js-0.10.0`
// we will remove the first 8 (zone.js-) chars to get the real version.
const version = tag.replace(/^zone\.js-/, '');
return gulp.src('packages/zone.js/CHANGELOG.md')
.pipe(conventionalChangelog(
{
preset: 'angular',
},
{linkCompare: true, previousTag: ptag, currentTag: tag, version: version}, {
// Ignore commits that have a different scope than `zone.js`.
extendedRegexp: true,
grep: '^[^(]+\\(zone\\.js\\)',
from: ptag,
to: 'HEAD',
}))
.pipe(gulp.dest('./packages/zone.js/'));
return gulp
.src('packages/zone.js/CHANGELOG.md')
.pipe(
conventionalChangelog(
{
preset: 'angular',
},
{linkCompare: true, previousTag: ptag, currentTag: tag, version: version},
{
// Ignore commits that have a different scope than `zone.js`.
extendedRegexp: true,
grep: '^[^(]+\\(zone\\.js\\)',
from: ptag,
to: 'HEAD',
},
),
)
.pipe(gulp.dest('./packages/zone.js/'));
};
@@ -15,7 +15,7 @@ function main() {
const rawParamLines = readFileSync(paramFilePath, {encoding: 'utf8'}).split('\n');
const [srcs, outputFileExecRootRelativePath] = rawParamLines;
const entries: DocEntry[] = srcs.split(',').map(sourceFilePath => {
const entries: DocEntry[] = srcs.split(',').map((sourceFilePath) => {
const fileContent = readFileSync(sourceFilePath, {encoding: 'utf8'});
return {
@@ -15,7 +15,7 @@ function main() {
const rawParamLines = readFileSync(paramFilePath, {encoding: 'utf8'}).split('\n');
const [srcs, outputFileExecRootRelativePath] = rawParamLines;
const entries: DocEntry[] = srcs.split(',').map(sourceFilePath => {
const entries: DocEntry[] = srcs.split(',').map((sourceFilePath) => {
const fileContent = readFileSync(sourceFilePath, {encoding: 'utf8'});
return {
+3 -2
View File
@@ -15,8 +15,9 @@ try {
// This can be fixed using the --preserve-symlinks-main flag which
// is introduced in node 10.2.0
console.warn(
`Running postinstall-patches.js script in an external repository requires --preserve-symlinks-main node flag introduced in node 10.2.0. ` +
`Current node version is ${process.version}. Node called with '${process.argv.join(' ')}'.`);
`Running postinstall-patches.js script in an external repository requires --preserve-symlinks-main node flag introduced in node 10.2.0. ` +
`Current node version is ${process.version}. Node called with '${process.argv.join(' ')}'.`,
);
process.exit(0);
}
@@ -43,13 +43,13 @@ if (!parallelExecutions) {
// Start the daemon and launch the given browser
const daemon = new SaucelabsDaemon(
username,
accessKey,
process.env['CIRCLE_BUILD_NUM']!,
Object.values(customLaunchers) as Browser[],
parallelExecutions,
sauceConnect,
{tunnelIdentifier},
username,
accessKey,
process.env['CIRCLE_BUILD_NUM']!,
Object.values(customLaunchers) as Browser[],
parallelExecutions,
sauceConnect,
{tunnelIdentifier},
);
if (args.includes('--connect')) {
@@ -9,7 +9,11 @@
import {createServer, Server, Socket} from 'net';
import {IPC_PORT} from '../ipc-defaults';
import {BackgroundServiceReceiveMessages, InternalErrorMessage, NoAvailableBrowserMessage} from '../ipc-messages';
import {
BackgroundServiceReceiveMessages,
InternalErrorMessage,
NoAvailableBrowserMessage,
} from '../ipc-messages';
import {SaucelabsDaemon} from './saucelabs-daemon';
@@ -27,30 +31,30 @@ export class IpcServer {
constructor(private _service: SaucelabsDaemon) {
this._server = createServer(this._connectionHandler.bind(this));
this._server.listen(
IPC_PORT, () => console.info(`Daemon IPC server listening (pid ${process.pid}).`));
this._server.listen(IPC_PORT, () =>
console.info(`Daemon IPC server listening (pid ${process.pid}).`),
);
}
private _connectionHandler(socket: Socket) {
const socketId = nextSocketId++;
this._connections.set(socketId, socket);
socket.on('data', b => {
socket.on('data', (b) => {
this._processMessage(
socket,
socketId,
JSON.parse(b.toString()) as BackgroundServiceReceiveMessages,
)
.catch((err) => {
console.error(err);
this._sendInternalError(socket, err.toString());
});
socket,
socketId,
JSON.parse(b.toString()) as BackgroundServiceReceiveMessages,
).catch((err) => {
console.error(err);
this._sendInternalError(socket, err.toString());
});
});
}
private async _processMessage(
socket: Socket,
socketId: number,
message: BackgroundServiceReceiveMessages,
socket: Socket,
socketId: number,
message: BackgroundServiceReceiveMessages,
) {
switch (message.type) {
case 'start-test':
@@ -28,9 +28,9 @@ const defaultCapabilities = {
interface RemoteBrowser {
id: string;
state: 'claimed'|'free'|'launching';
driver: WebDriver|null;
sessionUrl: string|null;
state: 'claimed' | 'free' | 'launching';
driver: WebDriver | null;
sessionUrl: string | null;
}
interface BrowserTest {
@@ -66,22 +66,22 @@ export class SaucelabsDaemon {
private _baseCapabilities = {...defaultCapabilities, ...this._userCapabilities};
/** Id of the keep alive interval that ensures no remote browsers time out. */
private _keepAliveIntervalId: NodeJS.Timeout|null = null;
private _keepAliveIntervalId: NodeJS.Timeout | null = null;
/* Promise indicating whether we the tunnel is active, or if we are still connecting. */
private _connection: Promise<void>|undefined = undefined;
private _connection: Promise<void> | undefined = undefined;
/* Number of parallel executions started */
private _parallelExecutions: number = 0;
constructor(
private _username: string,
private _accessKey: string,
private _buildName: string,
private _browsers: Browser[],
private _maxParallelExecutions: number,
private _sauceConnect: string,
private _userCapabilities: object = {},
private _username: string,
private _accessKey: string,
private _buildName: string,
private _browsers: Browser[],
private _maxParallelExecutions: number,
private _sauceConnect: string,
private _userCapabilities: object = {},
) {
// Starts the keep alive loop for all active browsers, running every 15 seconds.
this._keepAliveIntervalId = setInterval(() => this._keepAliveBrowsers(), 15_000);
@@ -104,7 +104,7 @@ export class SaucelabsDaemon {
*/
async quitAllBrowsers() {
let quitBrowsers: Promise<void>[] = [];
this._activeBrowsers.forEach(b => {
this._activeBrowsers.forEach((b) => {
if (b.driver) {
quitBrowsers.push(b.driver.quit());
}
@@ -190,7 +190,9 @@ export class SaucelabsDaemon {
**/
private async _connect() {
await openSauceConnectTunnel(
(this._userCapabilities as any).tunnelIdentifier, this._sauceConnect);
(this._userCapabilities as any).tunnelIdentifier,
this._sauceConnect,
);
}
/**
@@ -202,74 +204,76 @@ export class SaucelabsDaemon {
private async launchBrowserSet() {
this._parallelExecutions++;
console.debug(
`Launching browsers set ${this._parallelExecutions} of ${this._maxParallelExecutions}...`);
`Launching browsers set ${this._parallelExecutions} of ${this._maxParallelExecutions}...`,
);
// Once the tunnel is established we can launch browsers
await Promise.all(
this._browsers.map(async (browser, id) => {
const browserId = getUniqueId(browser);
const launched: RemoteBrowser = {
state: 'launching',
driver: null,
sessionUrl: null,
id: browserId,
};
const browserDescription = `${this._buildName} - ${browser.browserName} - #${id + 1}`;
this._browsers.map(async (browser, id) => {
const browserId = getUniqueId(browser);
const launched: RemoteBrowser = {
state: 'launching',
driver: null,
sessionUrl: null,
id: browserId,
};
const browserDescription = `${this._buildName} - ${browser.browserName} - #${id + 1}`;
const capabilities: any = {
'browserName': browser.browserName,
'sauce:options': {...this._baseCapabilities, ...browser},
};
const capabilities: any = {
'browserName': browser.browserName,
'sauce:options': {...this._baseCapabilities, ...browser},
};
// Set `sauce:options` to provide a build name for the remote browser instances.
// This helps with debugging. Also ensures the W3C protocol is used.
// See. https://wiki.saucelabs.com/display/DOCS/Test+Configuration+Options
capabilities['sauce:options']['name'] = browserDescription;
capabilities['sauce:options']['build'] = browserDescription;
// Set `sauce:options` to provide a build name for the remote browser instances.
// This helps with debugging. Also ensures the W3C protocol is used.
// See. https://wiki.saucelabs.com/display/DOCS/Test+Configuration+Options
capabilities['sauce:options']['name'] = browserDescription;
capabilities['sauce:options']['build'] = browserDescription;
console.debug(
`Capabilities for ${browser.browserName}:`, JSON.stringify(capabilities, null, 2));
console.debug(` > Browser-ID: `, browserId);
console.debug(` > Browser-Description: `, browserDescription);
console.debug(
`Capabilities for ${browser.browserName}:`,
JSON.stringify(capabilities, null, 2),
);
console.debug(` > Browser-ID: `, browserId);
console.debug(` > Browser-Description: `, browserDescription);
// Keep track of the launched browser. We do this before it even completed the
// launch as we can then handle scheduled tests when the browser is still launching.
this._activeBrowsers.push(launched);
// Keep track of the launched browser. We do this before it even completed the
// launch as we can then handle scheduled tests when the browser is still launching.
this._activeBrowsers.push(launched);
// See the following link for public API of the selenium server.
// https://wiki.saucelabs.com/display/DOCS/Instant+Selenium+Node.js+Tests
const driver = await new Builder()
.withCapabilities(capabilities)
.usingServer(
`http://${this._username}:${
this._accessKey}@ondemand.saucelabs.com:80/wd/hub`,
)
.build();
// See the following link for public API of the selenium server.
// https://wiki.saucelabs.com/display/DOCS/Instant+Selenium+Node.js+Tests
const driver = await new Builder()
.withCapabilities(capabilities)
.usingServer(
`http://${this._username}:${this._accessKey}@ondemand.saucelabs.com:80/wd/hub`,
)
.build();
// Only wait 30 seconds to load a test page.
await driver.manage().setTimeouts({pageLoad: 30000});
// Only wait 30 seconds to load a test page.
await driver.manage().setTimeouts({pageLoad: 30000});
const sessionId = (await driver.getSession()).getId();
const sessionId = (await driver.getSession()).getId();
// Mark the browser as available after launch completion.
launched.state = 'free';
launched.driver = driver;
launched.sessionUrl = `https://saucelabs.com/tests/${sessionId}`;
// Mark the browser as available after launch completion.
launched.state = 'free';
launched.driver = driver;
launched.sessionUrl = `https://saucelabs.com/tests/${sessionId}`;
console.info(
chalk.yellow(
`Started browser ${browser.browserName} on Saucelabs: ${launched.sessionUrl}`,
),
);
console.info(
chalk.yellow(
`Started browser ${browser.browserName} on Saucelabs: ${launched.sessionUrl}`,
),
);
// If a test has been scheduled before the browser completed launching, run
// it now given that the browser is ready now.
if (this._pendingTests.has(launched)) {
const test = this._pendingTests.get(launched)!;
this._pendingTests.delete(launched);
this._startBrowserTest(launched, test);
}
}),
// If a test has been scheduled before the browser completed launching, run
// it now given that the browser is ready now.
if (this._pendingTests.has(launched)) {
const test = this._pendingTests.get(launched)!;
this._pendingTests.delete(launched);
this._startBrowserTest(launched, test);
}
}),
);
}
@@ -305,7 +309,7 @@ export class SaucelabsDaemon {
* or launching with no pending test. If no such browser if found, returns
* null.
**/
private _findAvailableBrowser(browserId: string): RemoteBrowser|null {
private _findAvailableBrowser(browserId: string): RemoteBrowser | null {
for (const browser of this._activeBrowsers) {
// If the browser ID doesn't match, continue searching.
if (browser.id !== browserId) {
@@ -337,13 +341,16 @@ export class SaucelabsDaemon {
**/
private async _keepAliveBrowsers() {
const pendingCommands: Promise<string>[] = [];
this._activeBrowsers.forEach(b => {
this._activeBrowsers.forEach((b) => {
if (b.driver !== null) {
pendingCommands.push(b.driver.getTitle() as Promise<string>);
}
});
await Promise.all(pendingCommands);
console.debug(`${Date().toLocaleString()}: Refreshed ${pendingCommands.length} browsers (pid ${
process.pid}).`);
console.debug(
`${Date().toLocaleString()}: Refreshed ${pendingCommands.length} browsers (pid ${
process.pid
}).`,
);
}
}
+3 -1
View File
@@ -20,6 +20,8 @@ export interface Browser {
* across the background service and launcher using IPC.
*/
export function getUniqueId(browser: Browser): string {
let result = Object.keys(browser).sort().map(key => `${key}=${browser[key as keyof Browser]}`);
let result = Object.keys(browser)
.sort()
.map((key) => `${key}=${browser[key as keyof Browser]}`);
return result.join(':');
}
+7 -3
View File
@@ -9,7 +9,11 @@
/** Message that can be sent to the daemon to start a given test. */
export class StartTestMessage {
readonly type = 'start-test';
constructor(public url: string, public browserId: string, public testDescription: string) {}
constructor(
public url: string,
public browserId: string,
public testDescription: string,
) {}
}
/** Message that can be sent to the daemon if a test completed. */
@@ -29,7 +33,7 @@ export class InternalErrorMessage {
}
/** Type of messages the background service can receive. */
export type BackgroundServiceReceiveMessages = StartTestMessage|EndTestMessage;
export type BackgroundServiceReceiveMessages = StartTestMessage | EndTestMessage;
/** Type of messages the background services can send to clients. */
export type BackgroundServiceSendMessages = NoAvailableBrowserMessage|InternalErrorMessage;
export type BackgroundServiceSendMessages = NoAvailableBrowserMessage | InternalErrorMessage;
+18 -18
View File
@@ -13,13 +13,13 @@ import {IPC_PORT} from '../ipc-defaults';
import {BackgroundServiceSendMessages, EndTestMessage, StartTestMessage} from '../ipc-messages';
export function SaucelabsLauncher(
this: any,
args: Browser,
config: unknown,
logger: any,
baseLauncherDecorator: any,
captureTimeoutLauncherDecorator: any,
retryLauncherDecorator: any,
this: any,
args: Browser,
config: unknown,
logger: any,
baseLauncherDecorator: any,
captureTimeoutLauncherDecorator: any,
retryLauncherDecorator: any,
) {
// Apply base class mixins. This would be nice to have typed, but this is a low-priority now.
baseLauncherDecorator(this);
@@ -27,12 +27,13 @@ export function SaucelabsLauncher(
retryLauncherDecorator(this);
const log = logger.create('SaucelabsLauncher');
const browserDisplayName = args.browserName +
(args.browserVersion ? ' ' + args.browserVersion : '') +
(args.platformName ? ' (' + args.platformName + ')' : '');
const browserDisplayName =
args.browserName +
(args.browserVersion ? ' ' + args.browserVersion : '') +
(args.platformName ? ' (' + args.platformName + ')' : '');
const testSuiteDescription = process.env['TEST_TARGET'] ?? '<unknown>';
let daemonConnection: Socket|null = null;
let daemonConnection: Socket | null = null;
// Setup Browser name that will be printed out by Karma.
this.name = browserDisplayName + ' on SauceLabs (daemon)';
@@ -40,11 +41,10 @@ export function SaucelabsLauncher(
this.on('start', (pageUrl: string) => {
daemonConnection = createConnection({port: IPC_PORT}, () => _startBrowserTest(pageUrl, args));
daemonConnection.on(
'data',
b => _processMessage(JSON.parse(b.toString()) as BackgroundServiceSendMessages),
daemonConnection.on('data', (b) =>
_processMessage(JSON.parse(b.toString()) as BackgroundServiceSendMessages),
);
daemonConnection.on('error', err => {
daemonConnection.on('error', (err) => {
log.error(err);
// Notify karma about the failure.
@@ -62,8 +62,8 @@ export function SaucelabsLauncher(
switch (message.type) {
case 'browser-not-ready':
log.error(
'Browser %s is not ready in the Saucelabs background service.',
browserDisplayName,
'Browser %s is not ready in the Saucelabs background service.',
browserDisplayName,
);
this._done('failure');
}
@@ -72,7 +72,7 @@ export function SaucelabsLauncher(
const _startBrowserTest = (pageUrl: string, browser: Browser) => {
log.info('Starting browser %s test in daemon with URL: %s', browserDisplayName, pageUrl);
daemonConnection!.write(
JSON.stringify(new StartTestMessage(pageUrl, getUniqueId(browser), testSuiteDescription)),
JSON.stringify(new StartTestMessage(pageUrl, getUniqueId(browser), testSuiteDescription)),
);
};
+1 -1
View File
@@ -21,7 +21,7 @@ process.exitCode = main(args) ? 0 : 1;
* cli javascriptFilePath.js goldenFilePath.json
* ```
*/
function main(argv: [string, string, string]|[string, string]): boolean {
function main(argv: [string, string, string] | [string, string]): boolean {
const javascriptFilePath = runfiles.resolveWorkspaceRelative(argv[0]);
const goldenFilePath = runfiles.resolveWorkspaceRelative(argv[1]);
const doUpdate = argv[2] == '--accept';
@@ -19,21 +19,25 @@ const USER_COMMAND = argv._[0];
// The shell command to query for all tests.
// Bazel targets for testing goldens
process.stdout.write('Gathering all symbol extractor targets');
const ALL_TEST_TARGETS =
spawnSync(
'yarn',
[
'-s', 'bazel', 'query', '--output', 'label',
`'kind(nodejs_test, ...) intersect attr("tags", "symbol_extractor", ...)'`
],
{encoding: 'utf8', shell: true, cwd: path.resolve(__dirname, '../..')})
.stdout.trim()
.split('\n')
.map(line => line.trim());
const ALL_TEST_TARGETS = spawnSync(
'yarn',
[
'-s',
'bazel',
'query',
'--output',
'label',
`'kind(nodejs_test, ...) intersect attr("tags", "symbol_extractor", ...)'`,
],
{encoding: 'utf8', shell: true, cwd: path.resolve(__dirname, '../..')},
)
.stdout.trim()
.split('\n')
.map((line) => line.trim());
process.stdout.clearLine();
process.stdout.cursorTo(0);
// Bazel targets for generating goldens
const ALL_ACCEPT_TARGETS = ALL_TEST_TARGETS.map(test => `${test}.accept`);
const ALL_ACCEPT_TARGETS = ALL_TEST_TARGETS.map((test) => `${test}.accept`);
/** Run the provided bazel commands on each provided target individually. */
function runBazelCommandOnTargets(command, targets, present) {
+10 -9
View File
@@ -8,7 +8,6 @@
import ts from 'typescript';
export interface Symbol {
name: string;
}
@@ -65,8 +64,8 @@ export class SymbolExtractor {
classDecl.name && symbols.push({name: stripSuffix(classDecl.name.getText())});
break;
default:
// Left for easier debugging.
// console.log('###', ts.SyntaxKind[child.kind], child.getText());
// Left for easier debugging.
// console.log('###', ts.SyntaxKind[child.kind], child.getText());
}
}
visitor(source);
@@ -74,7 +73,7 @@ export class SymbolExtractor {
return symbols;
}
static diff(actual: Symbol[], expected: string|((Symbol | string)[])): {[name: string]: number} {
static diff(actual: Symbol[], expected: string | (Symbol | string)[]): {[name: string]: number} {
if (typeof expected == 'string') {
expected = JSON.parse(expected) as string[];
}
@@ -83,7 +82,7 @@ export class SymbolExtractor {
// All symbols in the golden file start out with a count corresponding to the number of symbols
// with that name. Once they are matched with symbols in the actual output, the count should
// even out to 0.
expected.forEach(nameOrSymbol => {
expected.forEach((nameOrSymbol) => {
const symbolName = typeof nameOrSymbol == 'string' ? nameOrSymbol : nameOrSymbol.name;
diff[symbolName] = (diff[symbolName] || 0) + 1;
});
@@ -98,16 +97,18 @@ export class SymbolExtractor {
return diff;
}
constructor(private path: string, private contents: string) {
constructor(
private path: string,
private contents: string,
) {
this.actual = SymbolExtractor.parse(path, contents);
}
expect(expectedSymbols: (string|Symbol)[]) {
expect(expectedSymbols: (string | Symbol)[]) {
expect(SymbolExtractor.diff(this.actual, expectedSymbols)).toEqual({});
}
compareAndPrintError(goldenFilePath: string, expected: string|((Symbol | string)[])): boolean {
compareAndPrintError(goldenFilePath: string, expected: string | (Symbol | string)[]): boolean {
let passed = true;
const diff = SymbolExtractor.diff(this.actual, expected);
Object.keys(diff).forEach((key) => {
@@ -14,7 +14,8 @@ import {SymbolExtractor} from './symbol_extractor';
describe('scenarios', () => {
const symbolExtractorSpecDir = path.dirname(
runfiles.resolve('angular/tools/symbol-extractor/symbol_extractor_spec/empty.json'));
runfiles.resolve('angular/tools/symbol-extractor/symbol_extractor_spec/empty.json'),
);
const scenarioFiles = fs.readdirSync(symbolExtractorSpecDir);
for (let i = 0; i < scenarioFiles.length; i++) {
const filePath = scenarioFiles[i];
@@ -47,11 +48,14 @@ describe('scenarios', () => {
it('should properly capture classes in TypeScript ES2015 class output', () => {
const jsFileContent = fs.readFileSync(
runfiles.resolve(
'angular/tools/symbol-extractor/symbol_extractor_spec/es2015_class_output.mjs'),
'utf8');
const jsonFileContent =
fs.readFileSync(path.join(symbolExtractorSpecDir, 'es2015_class_output.json')).toString();
runfiles.resolve(
'angular/tools/symbol-extractor/symbol_extractor_spec/es2015_class_output.mjs',
),
'utf8',
);
const jsonFileContent = fs
.readFileSync(path.join(symbolExtractorSpecDir, 'es2015_class_output.json'))
.toString();
const symbols = SymbolExtractor.parse('es2015_class_output', jsFileContent);
const diff = SymbolExtractor.diff(symbols, jsonFileContent);
expect(diff).toEqual({});
@@ -6,14 +6,14 @@
* found in the LICENSE file at https://angular.io/license
*/
!function() {
!(function () {
function A() {
function ignoreA() {}
}
function B() {
let ignoreB = {};
}
!function() {
!function () {
let ignoreC = {};
};
}();
})();
@@ -6,7 +6,9 @@
* found in the LICENSE file at https://angular.io/license
*/
!function() {
!(function () {
'use strict';
var constant$1 = 1, method$2 = function() {}, clazz$3 = class {};
}();
var constant$1 = 1,
method$2 = function () {},
clazz$3 = class {};
})();
@@ -6,4 +6,4 @@
* found in the LICENSE file at https://angular.io/license
*/
(function() {})();
(function () {})();
@@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
!function() {
!(function () {
'use strict';
/**
*@license
@@ -49,9 +49,11 @@
* 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
*/ 'undefined' != typeof window && window,
'undefined' != typeof self && 'undefined' != typeof WorkerGlobalScope &&
self instanceof WorkerGlobalScope && self,
'undefined' != typeof global && global;
'undefined' != typeof self &&
'undefined' != typeof WorkerGlobalScope &&
self instanceof WorkerGlobalScope &&
self,
'undefined' != typeof global && global;
/**
*@license
*Copyright Google Inc. All Rights Reserved.
@@ -69,46 +71,50 @@
*/
Function;
var __window$1 = 'undefined' != typeof window && window,
__self$1 = 'undefined' != typeof self && 'undefined' != typeof WorkerGlobalScope &&
self instanceof WorkerGlobalScope && self,
__global$1 = 'undefined' != typeof global && global,
_root = __window$1 || __global$1 || __self$1;
!function() {
__self$1 =
'undefined' != typeof self &&
'undefined' != typeof WorkerGlobalScope &&
self instanceof WorkerGlobalScope &&
self,
__global$1 = 'undefined' != typeof global && global,
_root = __window$1 || __global$1 || __self$1;
!(function () {
if (!_root) throw new Error('RxJS could not find any global context (window, self, global)');
}();
})();
Array;
!function() {
!(function () {
Object.setPrototypeOf || Array;
}();
})();
Error;
var RendererStyleFlags2, Symbol$1 = _root.Symbol;
'function' == typeof Symbol$1 && 'function' == typeof Symbol$1.for &&
Symbol$1.for('rxSubscriber'),
function() {
Object.setPrototypeOf || Array;
}();
!function(context) {
var $$observable, Symbol = _root.Symbol;
var RendererStyleFlags2,
Symbol$1 = _root.Symbol;
'function' == typeof Symbol$1 &&
'function' == typeof Symbol$1.for &&
Symbol$1.for('rxSubscriber'),
(function () {
Object.setPrototypeOf || Array;
})();
!(function (context) {
var $$observable,
Symbol = _root.Symbol;
if ('function' == typeof Symbol)
if (Symbol.observable)
$$observable = Symbol.observable;
if (Symbol.observable) $$observable = Symbol.observable;
else {
$$observable = Symbol('observable');
Symbol.observable = $$observable;
}
else
$$observable = '@@observable';
}();
(function() {
else $$observable = '@@observable';
})();
(function () {
Object.setPrototypeOf || Array;
})(),
function() {
Object.setPrototypeOf || Array;
}();
!function() {
(function () {
Object.setPrototypeOf || Array;
})();
!(function () {
Object.setPrototypeOf || Array;
}();
(function(root) {
})();
(function (root) {
var Symbol = root.Symbol;
if ('function' == typeof Symbol) {
Symbol.iterator || (Symbol.iterator = Symbol('iterator polyfill'));
@@ -124,37 +130,41 @@
return key;
}
})(_root),
function() {
Object.setPrototypeOf || Array;
}();
(function() {
(function () {
Object.setPrototypeOf || Array;
})();
(function () {
Object.setPrototypeOf || Array;
})(),
function() {
Object.setPrototypeOf || Array;
}();
!function() {
(function () {
Object.setPrototypeOf || Array;
})();
!(function () {
Object.setPrototypeOf || Array;
}();
Error, function() {
})();
Error,
(function () {
Object.setPrototypeOf || Array;
})(),
(function () {
Object.setPrototypeOf || Array;
})(),
(function () {
Object.setPrototypeOf || Array;
})();
!(function () {
Object.setPrototypeOf || Array;
}(), function() {
Object.setPrototypeOf || Array;
}(), function() {
Object.setPrototypeOf || Array;
}();
!function() {
Object.setPrototypeOf || Array;
}();
})();
Object;
RendererStyleFlags2 || (RendererStyleFlags2 = {});
var RendererStyleFlags3, _renderCompCount = 0;
var RendererStyleFlags3,
_renderCompCount = 0;
function executeHooks(data, allHooks, checkHooks, creationMode) {
var hooksToCall = creationMode ? allHooks : checkHooks;
null != hooksToCall &&
function(data, arr) {
for (var i = 0; i < arr.length; i += 2) arr[1 | i].call(data[arr[i]]);
}
(function (data, arr) {
for (var i = 0; i < arr.length; i += 2) arr[1 | i].call(data[arr[i]]);
})(
/**
* @license
* Copyright Google LLC All Rights Reserved.
@@ -183,13 +193,15 @@
* 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
*/
(data, hooksToCall);
data,
hooksToCall,
);
}
RendererStyleFlags3 || (RendererStyleFlags3 = {});
var domRendererFactory3 = {
createRenderer: function(hostElement, rendererType) {
createRenderer: function (hostElement, rendererType) {
return document;
}
},
};
/**
*@license
@@ -207,24 +219,24 @@
*/
function getNextLNodeWithProjection(node) {
var pNextOrParent = node.pNextOrParent;
return pNextOrParent ? 1 == (3 & pNextOrParent.flags) ? null : pNextOrParent : node.next;
return pNextOrParent ? (1 == (3 & pNextOrParent.flags) ? null : pNextOrParent) : node.next;
}
function getNextOrParentSiblingNode(initialNode, rootNode) {
for (var node = initialNode, nextNode = getNextLNodeWithProjection(node); node && !nextNode;) {
for (var node = initialNode, nextNode = getNextLNodeWithProjection(node); node && !nextNode; ) {
if ((node = node.pNextOrParent || node.parent) === rootNode) return null;
nextNode = node && getNextLNodeWithProjection(node);
}
return nextNode;
}
function findFirstRNode(rootNode) {
for (var node = rootNode; node;) {
var type = 3 & node.flags, nextNode = null;
for (var node = rootNode; node; ) {
var type = 3 & node.flags,
nextNode = null;
if (3 === type) return node.native;
if (0 === type) {
var childContainerData = node.data;
nextNode = childContainerData.views.length ? childContainerData.views[0].child : null;
} else
nextNode = 1 === type ? node.data.head : node.child;
} else nextNode = 1 === type ? node.data.head : node.child;
node = null === nextNode ? getNextOrParentSiblingNode(node, rootNode) : nextNode;
}
return null;
@@ -233,9 +245,13 @@
return 3 == (3 & parent.flags) && (parent.view !== view || null === parent.data);
}
function stringify$1(value) {
return 'function' == typeof value ?
value.name || value :
'string' == typeof value ? value : null == value ? '' : '' + value;
return 'function' == typeof value
? value.name || value
: 'string' == typeof value
? value
: null == value
? ''
: '' + value;
}
/**
*@license
@@ -244,8 +260,16 @@
*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 renderer, rendererFactory, previousOrParentNode, isParent, tData, currentView, currentQueries,
creationMode, data, bindingIndex;
var renderer,
rendererFactory,
previousOrParentNode,
isParent,
tData,
currentView,
currentQueries,
creationMode,
data,
bindingIndex;
currentView = createLView(null, null, createTView());
function enterView(newView, host) {
var oldView = currentView;
@@ -264,8 +288,11 @@
}
function leaveView(newView) {
executeHooks(
currentView.data, currentView.tView.viewHooks, currentView.tView.viewCheckHooks,
creationMode);
currentView.data,
currentView.tView.viewHooks,
currentView.tView.viewCheckHooks,
creationMode,
);
currentView.creationMode = !1;
currentView.lifecycleStage = 1;
currentView.tView.firstCreatePass = !1;
@@ -291,52 +318,58 @@
context: context,
dynamicViewCount: 0,
lifecycleStage: 1,
queries: null
queries: null,
};
}
function createLNode(index, type, native, state) {
var parent =
isParent ? previousOrParentNode : previousOrParentNode && previousOrParentNode.parent,
queries =
(isParent ? currentQueries : previousOrParentNode && previousOrParentNode.queries) ||
parent && parent.queries && parent.queries.child(),
isState = null != state, node = {
flags: type,
native: native,
view: currentView,
parent: parent,
child: null,
next: null,
nodeInjector: parent ? parent.nodeInjector : null,
data: isState ? state : null,
queries: queries,
tNode: null,
pNextOrParent: null
};
var parent = isParent
? previousOrParentNode
: previousOrParentNode && previousOrParentNode.parent,
queries =
(isParent ? currentQueries : previousOrParentNode && previousOrParentNode.queries) ||
(parent && parent.queries && parent.queries.child()),
isState = null != state,
node = {
flags: type,
native: native,
view: currentView,
parent: parent,
child: null,
next: null,
nodeInjector: parent ? parent.nodeInjector : null,
data: isState ? state : null,
queries: queries,
tNode: null,
pNextOrParent: null,
};
2 == (2 & type) && isState && (state.node = node);
if (null != index) {
data[index] = node;
index >= tData.length ? tData[index] = null : node.tNode = tData[index];
index >= tData.length ? (tData[index] = null) : (node.tNode = tData[index]);
if (isParent) {
currentQueries = null;
previousOrParentNode.view !== currentView && 2 != (3 & previousOrParentNode.flags) ||
(previousOrParentNode.child = node);
} else
previousOrParentNode && (previousOrParentNode.next = node);
(previousOrParentNode.view !== currentView && 2 != (3 & previousOrParentNode.flags)) ||
(previousOrParentNode.child = node);
} else previousOrParentNode && (previousOrParentNode.next = node);
}
previousOrParentNode = node;
isParent = !0;
return node;
}
function renderEmbeddedTemplate(viewNode, template, context, renderer) {
var _isParent = isParent, _previousOrParentNode = previousOrParentNode;
var _isParent = isParent,
_previousOrParentNode = previousOrParentNode;
try {
isParent = !0;
previousOrParentNode = null;
var cm = !1;
if (null == viewNode) {
viewNode =
createLNode(null, 2, null, createLView(-1, renderer, createTView(), template, context));
viewNode = createLNode(
null,
2,
null,
createLView(-1, renderer, createTView(), template, context),
);
cm = !0;
}
enterView(viewNode.data, viewNode);
@@ -353,26 +386,31 @@
var oldView = enterView(hostView, node);
try {
rendererFactory.begin && rendererFactory.begin();
template ?
template(componentOrContext, creationMode) :
function(directiveIndex, elementIndex) {
!function(currentView, tView, creationMode) {
template
? template(componentOrContext, creationMode)
: (function (directiveIndex, elementIndex) {
!(function (currentView, tView, creationMode) {
if (1 === currentView.lifecycleStage) {
executeHooks(currentView.data, tView.initHooks, tView.checkHooks, creationMode);
currentView.lifecycleStage = 2;
}
}(currentView, currentView.tView, creationMode);
!function(currentView, tView, creationMode) {
})(currentView, currentView.tView, creationMode);
!(function (currentView, tView, creationMode) {
if (currentView.lifecycleStage < 3) {
executeHooks(
currentView.data, tView.contentHooks, tView.contentCheckHooks, creationMode);
currentView.data,
tView.contentHooks,
tView.contentCheckHooks,
creationMode,
);
currentView.lifecycleStage = 3;
}
}(currentView, currentView.tView, creationMode);
})(currentView, currentView.tView, creationMode);
var template = tData[1].template;
if (null != template) {
var element = data[0], directive = getDirectiveInstance(data[1]),
oldView = enterView(element.data, element);
var element = data[0],
directive = getDirectiveInstance(data[1]),
oldView = enterView(element.data, element);
try {
template(directive, creationMode);
} finally {
@@ -380,7 +418,7 @@
leaveView(oldView);
}
}
}();
})();
} finally {
rendererFactory.end && rendererFactory.end();
leaveView(oldView);
@@ -397,16 +435,17 @@
viewHooks: null,
viewCheckHooks: null,
destroyHooks: null,
objectLiterals: null
objectLiterals: null,
};
}
function locateHostElement(factory, elementOrSelector) {
rendererFactory = factory;
var defaultRenderer = factory.createRenderer(null, null);
return 'string' == typeof elementOrSelector ?
defaultRenderer.selectRootElement ? defaultRenderer.selectRootElement(elementOrSelector) :
defaultRenderer.querySelector(elementOrSelector) :
elementOrSelector;
return 'string' == typeof elementOrSelector
? defaultRenderer.selectRootElement
? defaultRenderer.selectRootElement(elementOrSelector)
: defaultRenderer.querySelector(elementOrSelector)
: elementOrSelector;
}
function refreshDynamicChildren() {
for (var current = currentView.child; null !== current; current = current.next)
@@ -471,41 +510,58 @@
* 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
*/
!
/**
* @license
* Copyright Google LLC 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
*/
function(componentType, opts) {
void 0 === opts && (opts = {});
var component, rendererFactory = opts.rendererFactory || domRendererFactory3,
componentDef = componentType.ɵcmp;
componentDef.type != componentType && (componentDef.type = componentType);
var hostNode = locateHostElement(rendererFactory, opts.host || componentDef.tag),
oldView = enterView(
createLView(
-1, rendererFactory.createRenderer(hostNode, componentDef.rendererType),
createTView()),
null);
try {
!function(rNode, def) {
!function() {
isParent = !1;
previousOrParentNode = null;
}();
createLNode(0, 3, rNode, createLView(-1, renderer, function(template) {
return template.ngPrivateData || (template.ngPrivateData = createTView());
}(def.template)));
}(hostNode, componentDef);
component = getDirectiveInstance(function(index, directive, directiveDef, queryName) {
var instance, flags = previousOrParentNode.flags;
0 == (4092 & flags) ? flags = 4100 | 3 & flags : flags += 4;
!(
/**
* @license
* Copyright Google LLC 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
*/
(function (componentType, opts) {
void 0 === opts && (opts = {});
var component,
rendererFactory = opts.rendererFactory || domRendererFactory3,
componentDef = componentType.ɵcmp;
componentDef.type != componentType && (componentDef.type = componentType);
var hostNode = locateHostElement(rendererFactory, opts.host || componentDef.tag),
oldView = enterView(
createLView(
-1,
rendererFactory.createRenderer(hostNode, componentDef.rendererType),
createTView(),
),
null,
);
try {
!(function (rNode, def) {
!(function () {
isParent = !1;
previousOrParentNode = null;
})();
createLNode(
0,
3,
rNode,
createLView(
-1,
renderer,
(function (template) {
return template.ngPrivateData || (template.ngPrivateData = createTView());
})(def.template),
),
);
})(hostNode, componentDef);
component = getDirectiveInstance(
(function (index, directive, directiveDef, queryName) {
var instance,
flags = previousOrParentNode.flags;
0 == (4092 & flags) ? (flags = 4100 | (3 & flags)) : (flags += 4);
previousOrParentNode.flags = flags;
Object.defineProperty(
directive, '__ngHostLNode__', {enumerable: !1, value: previousOrParentNode});
Object.defineProperty(directive, '__ngHostLNode__', {
enumerable: !1,
value: previousOrParentNode,
});
data[1] = instance = directive;
if (1 >= tData.length) {
tData[1] = directiveDef;
@@ -513,56 +569,62 @@
var diPublic = directiveDef.diPublic;
diPublic && diPublic(directiveDef);
var tNode = previousOrParentNode.tNode;
tNode && tNode.attrs && function(instance, inputs, tNode) {
var directiveIndex = ((4092 & previousOrParentNode.flags) >> 2) - 1,
tNode &&
tNode.attrs &&
(function (instance, inputs, tNode) {
var directiveIndex = ((4092 & previousOrParentNode.flags) >> 2) - 1,
initialInputData = tNode.initialInputs;
(void 0 === initialInputData || directiveIndex >= initialInputData.length) &&
(initialInputData = function(directiveIndex, inputs, tNode) {
(void 0 === initialInputData || directiveIndex >= initialInputData.length) &&
(initialInputData = (function (directiveIndex, inputs, tNode) {
var initialInputData = tNode.initialInputs || (tNode.initialInputs = []);
initialInputData[directiveIndex] = null;
for (var attrs = tNode.attrs, i = 0; i < attrs.length; i += 2) {
var minifiedInputName = inputs[attrs[i]];
void 0 !== minifiedInputName &&
(initialInputData[directiveIndex] ||
(initialInputData[directiveIndex] = []))
.push(minifiedInputName, attrs[1 | i]);
(
initialInputData[directiveIndex] ||
(initialInputData[directiveIndex] = [])
).push(minifiedInputName, attrs[1 | i]);
}
return initialInputData;
}(directiveIndex, directiveDef.inputs, tNode));
var initialInputs = initialInputData[directiveIndex];
if (initialInputs)
for (var i = 0; i < initialInputs.length; i += 2)
instance[initialInputs[i]] = initialInputs[1 | i];
}(instance, 0, tNode);
!
/**
* @license
* Copyright Google LLC 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
*/
function(index, onInit, doCheck, tView) {
if (!0 === tView.firstCreatePass) {
null != onInit && (tView.initHooks || (tView.initHooks = [])).push(1, onInit);
if (null != doCheck) {
(tView.initHooks || (tView.initHooks = [])).push(1, doCheck);
(tView.checkHooks || (tView.checkHooks = [])).push(1, doCheck);
}
})(directiveIndex, directiveDef.inputs, tNode));
var initialInputs = initialInputData[directiveIndex];
if (initialInputs)
for (var i = 0; i < initialInputs.length; i += 2)
instance[initialInputs[i]] = initialInputs[1 | i];
})(instance, 0, tNode);
!(
/**
* @license
* Copyright Google LLC 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
*/
(function (index, onInit, doCheck, tView) {
if (!0 === tView.firstCreatePass) {
null != onInit && (tView.initHooks || (tView.initHooks = [])).push(1, onInit);
if (null != doCheck) {
(tView.initHooks || (tView.initHooks = [])).push(1, doCheck);
(tView.checkHooks || (tView.checkHooks = [])).push(1, doCheck);
}
}(0, directiveDef.onInit, directiveDef.doCheck, currentView.tView);
}
})(0, directiveDef.onInit, directiveDef.doCheck, currentView.tView)
);
return instance;
}(0, componentDef.n(), componentDef));
} finally {
leaveView(oldView);
}
opts.features && opts.features.forEach(function(feature) {
})(0, componentDef.n(), componentDef),
);
} finally {
leaveView(oldView);
}
opts.features &&
opts.features.forEach(function (feature) {
return feature(component, componentDef);
});
!function(component) {
var hostNode = component.__ngHostLNode__;
renderComponentOrTemplate(hostNode, hostNode.view, component);
}
!(function (component) {
var hostNode = component.__ngHostLNode__;
renderComponentOrTemplate(hostNode, hostNode.view, component);
})(
/**
* @license
* Copyright Google LLC All Rights Reserved.
@@ -577,140 +639,160 @@
* 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
*/
(component);
}(function() {
component,
);
})(
(function () {
function HelloWorld() {
this.name = 'World';
}
HelloWorld.ɵcmp = function(componentDefinition) {
var type = componentDefinition.type, def = {
type: type,
diPublic: null,
n: componentDefinition.factory,
tag: componentDefinition.tag || null,
template: componentDefinition.template || null,
h: componentDefinition.hostBindings || noop$2,
inputs: invertObject(componentDefinition.inputs),
outputs: invertObject(componentDefinition.outputs),
methods: invertObject(componentDefinition.methods),
rendererType: function(type) {
if (type && '$$undefined' === type.id) {
var isFilled =
null != type.encapsulation && type.encapsulation !== ViewEncapsulation.None ||
type.styles.length || Object.keys(type.data).length;
type.id = isFilled ? 'c' + _renderCompCount++ : '$$empty';
}
type && '$$empty' === type.id && (type = null);
return type || null;
}(componentDefinition.rendererType) ||
null,
exportAs: componentDefinition.exportAs,
onInit: type.prototype.ngOnInit || null,
doCheck: type.prototype.ngDoCheck || null,
afterContentInit: type.prototype.ngAfterContentInit || null,
afterContentChecked: type.prototype.ngAfterContentChecked || null,
afterViewInit: type.prototype.ngAfterViewInit || null,
afterViewChecked: type.prototype.ngAfterViewChecked || null,
onDestroy: type.prototype.ngOnDestroy || null
},
feature = componentDefinition.features;
feature && feature.forEach(function(fn) {
return fn(def);
});
HelloWorld.ɵcmp = (function (componentDefinition) {
var type = componentDefinition.type,
def = {
type: type,
diPublic: null,
n: componentDefinition.factory,
tag: componentDefinition.tag || null,
template: componentDefinition.template || null,
h: componentDefinition.hostBindings || noop$2,
inputs: invertObject(componentDefinition.inputs),
outputs: invertObject(componentDefinition.outputs),
methods: invertObject(componentDefinition.methods),
rendererType:
(function (type) {
if (type && '$$undefined' === type.id) {
var isFilled =
(null != type.encapsulation &&
type.encapsulation !== ViewEncapsulation.None) ||
type.styles.length ||
Object.keys(type.data).length;
type.id = isFilled ? 'c' + _renderCompCount++ : '$$empty';
}
type && '$$empty' === type.id && (type = null);
return type || null;
})(componentDefinition.rendererType) || null,
exportAs: componentDefinition.exportAs,
onInit: type.prototype.ngOnInit || null,
doCheck: type.prototype.ngDoCheck || null,
afterContentInit: type.prototype.ngAfterContentInit || null,
afterContentChecked: type.prototype.ngAfterContentChecked || null,
afterViewInit: type.prototype.ngAfterViewInit || null,
afterViewChecked: type.prototype.ngAfterViewChecked || null,
onDestroy: type.prototype.ngOnDestroy || null,
},
feature = componentDefinition.features;
feature &&
feature.forEach(function (fn) {
return fn(def);
});
return def;
}({
})({
type: HelloWorld,
tag: 'hello-world',
factory: function() {
factory: function () {
return new HelloWorld();
},
template: function(ctx, cm) {
cm && function(index, value) {
createLNode(0, 3, null);
isParent = !1;
}();
!function(index, value) {
template: function (ctx, cm) {
cm &&
(function (index, value) {
createLNode(0, 3, null);
isParent = !1;
})();
!(function (index, value) {
var existingNode = data[0];
if (existingNode.native)
value !== NO_CHANGE &&
(renderer.setValue ?
renderer.setValue(existingNode.native, stringify$1(value)) :
existingNode.native.textContent = stringify$1(value));
(renderer.setValue
? renderer.setValue(existingNode.native, stringify$1(value))
: (existingNode.native.textContent = stringify$1(value)));
else {
existingNode.native = renderer.createText ?
renderer.createText(stringify$1(value)) :
renderer.createTextNode(stringify$1(value));
!function(node, currentView) {
existingNode.native = renderer.createText
? renderer.createText(stringify$1(value))
: renderer.createTextNode(stringify$1(value));
!(function (node, currentView) {
var parent = node.parent;
if (canInsertNativeNode(parent, currentView)) {
var nativeSibling = function(node, stopNode) {
for (var currentNode = node; currentNode && null !== currentNode;) {
var pNextOrParent = currentNode.pNextOrParent;
if (pNextOrParent) {
for (var pNextOrParentType = 3 & pNextOrParent.flags;
1 !== pNextOrParentType;) {
if (nativeNode = findFirstRNode(pNextOrParent)) return nativeNode;
pNextOrParent = pNextOrParent.pNextOrParent;
}
currentNode = pNextOrParent;
} else {
for (var currentSibling = currentNode.next; currentSibling;) {
var nativeNode;
if (nativeNode = findFirstRNode(currentSibling)) return nativeNode;
currentSibling = currentSibling.next;
}
var parentNode = currentNode.parent;
currentNode = null;
if (parentNode) {
var parentType = 3 & parentNode.flags;
0 !== parentType && 2 !== parentType || (currentNode = parentNode);
var nativeSibling = (function (node, stopNode) {
for (var currentNode = node; currentNode && null !== currentNode; ) {
var pNextOrParent = currentNode.pNextOrParent;
if (pNextOrParent) {
for (
var pNextOrParentType = 3 & pNextOrParent.flags;
1 !== pNextOrParentType;
) {
if ((nativeNode = findFirstRNode(pNextOrParent))) return nativeNode;
pNextOrParent = pNextOrParent.pNextOrParent;
}
currentNode = pNextOrParent;
} else {
for (var currentSibling = currentNode.next; currentSibling; ) {
var nativeNode;
if ((nativeNode = findFirstRNode(currentSibling))) return nativeNode;
currentSibling = currentSibling.next;
}
var parentNode = currentNode.parent;
currentNode = null;
if (parentNode) {
var parentType = 3 & parentNode.flags;
(0 !== parentType && 2 !== parentType) || (currentNode = parentNode);
}
}
}
}
return null;
}(node), renderer = currentView.renderer;
renderer.listen ?
renderer.insertBefore(parent.native, node.native, nativeSibling) :
parent.native.insertBefore(node.native, nativeSibling, !1);
return null;
})(node),
renderer = currentView.renderer;
renderer.listen
? renderer.insertBefore(parent.native, node.native, nativeSibling)
: parent.native.insertBefore(node.native, nativeSibling, !1);
}
}
/**
* @license
* Copyright Google LLC 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
*/
/**
* @license
* Copyright Google LLC 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
*/
(existingNode, currentView);
})(
/**
* @license
* Copyright Google LLC 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
*/
/**
* @license
* Copyright Google LLC 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
*/
existingNode,
currentView,
);
}
}(0, function(prefix, value, suffix) {
return function(value) {
if (creationMode) {
!function() {
null == currentView.bindingStartIndex &&
})(
0,
(function (prefix, value, suffix) {
return (function (value) {
if (creationMode) {
!(function () {
null == currentView.bindingStartIndex &&
(bindingIndex = currentView.bindingStartIndex = data.length);
}();
return data[bindingIndex++] = value;
}
var changed = value !== NO_CHANGE && function(a, b) {
return !(a != a && value != value) && a !== value;
}(data[bindingIndex]);
changed && (data[bindingIndex] = value);
bindingIndex++;
return changed ? value : NO_CHANGE;
}(value) === NO_CHANGE ?
NO_CHANGE :
'Hello ' + stringify$1(value) + '!';
}(0, ctx.name));
}
})();
return (data[bindingIndex++] = value);
}
var changed =
value !== NO_CHANGE &&
(function (a, b) {
return !(a != a && value != value) && a !== value;
})(data[bindingIndex]);
changed && (data[bindingIndex] = value);
bindingIndex++;
return changed ? value : NO_CHANGE;
})(value) === NO_CHANGE
? NO_CHANGE
: 'Hello ' + stringify$1(value) + '!';
})(0, ctx.name),
);
},
});
return HelloWorld;
}());
}();
})(),
)
);
})();
@@ -7,5 +7,6 @@
*/
(() => {
var Class = function() {}, fn = function() {};
var Class = function () {},
fn = function () {};
})();
@@ -6,6 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
(function() {
var Class = function() {}, fn = function() {};
(function () {
var Class = function () {},
fn = function () {};
})();
@@ -6,22 +6,29 @@
* found in the LICENSE file at https://angular.io/license
*/
!function() {
!(function () {
'use strict';
// tslint:disable-next-line:no-console
console.log('Hello, Alice in Wonderland');
var A = function() {
function A() {}
return A.prototype.a = function() {
return document.a;
}, A;
}(), B = function() {
function B() {}
return B.prototype.b = function() {
return window.b;
}, B;
}();
var A = (function () {
function A() {}
return (
(A.prototype.a = function () {
return document.a;
}),
A
);
})(),
B = (function () {
function B() {}
return (
(B.prototype.b = function () {
return window.b;
}),
B
);
})();
var no_initializer;
// tslint:disable-next-line:no-console
console.error(new A().a(), new B().b());
}();
})();
@@ -6,7 +6,9 @@
* found in the LICENSE file at https://angular.io/license
*/
!function() {
!(function () {
'use strict';
var constant = 1, method = function() {}, clazz = class {};
}();
var constant = 1,
method = function () {},
clazz = class {};
})();
+7 -2
View File
@@ -11,11 +11,16 @@ import './zone_base_setup';
import '@angular/compiler'; // For JIT mode. Must be in front of any other @angular/* imports.
import {TestBed} from '@angular/core/testing';
import {BrowserDynamicTestingModule, platformBrowserDynamicTesting} from '@angular/platform-browser-dynamic/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting,
} from '@angular/platform-browser-dynamic/testing';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
TestBed.initTestEnvironment(
[BrowserDynamicTestingModule, NoopAnimationsModule], platformBrowserDynamicTesting());
[BrowserDynamicTestingModule, NoopAnimationsModule],
platformBrowserDynamicTesting(),
);
(window as any).isNode = false;
(window as any).isBrowser = true;
+7 -3
View File
@@ -15,11 +15,15 @@ import './zone_base_setup';
import '@angular/compiler'; // For JIT mode. Must be in front of any other @angular/* imports.
// Init TestBed
import {TestBed} from '@angular/core/testing';
import {ServerTestingModule, platformServerTesting} from '@angular/platform-server/testing/src/server';
import {
ServerTestingModule,
platformServerTesting,
} from '@angular/platform-server/testing/src/server';
import {DominoAdapter} from '@angular/platform-server/src/domino_adapter';
import domino from '../../packages/platform-server/src/bundled-domino';
TestBed.initTestEnvironment(ServerTestingModule, platformServerTesting());
DominoAdapter.makeCurrent();
(global as any).document = (DominoAdapter as any).defaultDoc ||
((DominoAdapter as any).defaultDoc = domino.createDocument());
(global as any).document =
(DominoAdapter as any).defaultDoc ||
((DominoAdapter as any).defaultDoc = domino.createDocument());
@@ -45,8 +45,12 @@ class TypedefWalker extends RuleWalker {
if (this.hasInternalAnnotation(ranges[i])) return;
}
}
this.addFailure(this.createFailure(
node.getStart(), node.getWidth(),
`module-private member ${node.name?.getText()} must be annotated @internal`));
this.addFailure(
this.createFailure(
node.getStart(),
node.getWidth(),
`module-private member ${node.name?.getText()} must be annotated @internal`,
),
);
}
}