Conexio amb la api

This commit is contained in:
janmaroto 2022-02-09 18:30:03 +01:00
commit b12369cb47
48513 changed files with 7391639 additions and 7 deletions

29
node_modules/@angular/cli/models/analytics-collector.d.ts generated vendored Executable file
View file

@ -0,0 +1,29 @@
/**
* @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
*/
import { analytics } from '@angular-devkit/core';
/**
* See: https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
*/
export declare class AnalyticsCollector implements analytics.Analytics {
private trackingEventsQueue;
private readonly parameters;
private readonly analyticsLogDebug;
constructor(trackingId: string, userId: string);
event(ec: string, ea: string, options?: analytics.EventOptions): void;
pageview(dp: string, options?: analytics.PageviewOptions): void;
timing(utc: string, utv: string, utt: string | number, options?: analytics.TimingOptions): void;
screenview(cd: string, an: string, options?: analytics.ScreenviewOptions): void;
flush(): Promise<void>;
private addToQueue;
private send;
/**
* Creates the dimension and metrics variables to add to the queue.
* @private
*/
private customVariables;
}

235
node_modules/@angular/cli/models/analytics-collector.js generated vendored Executable file
View file

@ -0,0 +1,235 @@
"use strict";
/**
* @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
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AnalyticsCollector = void 0;
const core_1 = require("@angular-devkit/core");
const child_process_1 = require("child_process");
const debug_1 = __importDefault(require("debug"));
const https = __importStar(require("https"));
const os = __importStar(require("os"));
const querystring = __importStar(require("querystring"));
const version_1 = require("./version");
/**
* See: https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
*/
class AnalyticsCollector {
constructor(trackingId, userId) {
this.trackingEventsQueue = [];
this.parameters = {};
this.analyticsLogDebug = debug_1.default('ng:analytics:log');
// API Version
this.parameters['v'] = '1';
// User ID
this.parameters['cid'] = userId;
// Tracking
this.parameters['tid'] = trackingId;
this.parameters['ds'] = 'cli';
this.parameters['ua'] = _buildUserAgentString();
this.parameters['ul'] = _getLanguage();
// @angular/cli with version.
this.parameters['an'] = '@angular/cli';
this.parameters['av'] = version_1.VERSION.full;
// We use the application ID for the Node version. This should be "node v12.10.0".
const nodeVersion = `node ${process.version}`;
this.parameters['aid'] = nodeVersion;
// Custom dimentions
// We set custom metrics for values we care about.
this.parameters['cd' + core_1.analytics.NgCliAnalyticsDimensions.CpuCount] = os.cpus().length;
// Get the first CPU's speed. It's very rare to have multiple CPUs of different speed (in most
// non-ARM configurations anyway), so that's all we care about.
this.parameters['cd' + core_1.analytics.NgCliAnalyticsDimensions.CpuSpeed] = Math.floor(os.cpus()[0].speed);
this.parameters['cd' + core_1.analytics.NgCliAnalyticsDimensions.RamInGigabytes] = Math.round(os.totalmem() / (1024 * 1024 * 1024));
this.parameters['cd' + core_1.analytics.NgCliAnalyticsDimensions.NodeVersion] = nodeVersion;
}
event(ec, ea, options = {}) {
const { label: el, value: ev, metrics, dimensions } = options;
this.addToQueue('event', { ec, ea, el, ev, metrics, dimensions });
}
pageview(dp, options = {}) {
const { hostname: dh, title: dt, metrics, dimensions } = options;
this.addToQueue('pageview', { dp, dh, dt, metrics, dimensions });
}
timing(utc, utv, utt, options = {}) {
const { label: utl, metrics, dimensions } = options;
this.addToQueue('timing', { utc, utv, utt, utl, metrics, dimensions });
}
screenview(cd, an, options = {}) {
const { appVersion: av, appId: aid, appInstallerId: aiid, metrics, dimensions } = options;
this.addToQueue('screenview', { cd, an, av, aid, aiid, metrics, dimensions });
}
async flush() {
const pending = this.trackingEventsQueue.length;
this.analyticsLogDebug(`flush queue size: ${pending}`);
if (!pending) {
return;
}
// The below is needed so that if flush is called multiple times,
// we don't report the same event multiple times.
const pendingTrackingEvents = this.trackingEventsQueue;
this.trackingEventsQueue = [];
try {
await this.send(pendingTrackingEvents);
}
catch (error) {
// Failure to report analytics shouldn't crash the CLI.
this.analyticsLogDebug('send error: %j', error);
}
}
addToQueue(eventType, parameters) {
const { metrics, dimensions, ...restParameters } = parameters;
const data = {
...this.parameters,
...restParameters,
...this.customVariables({ metrics, dimensions }),
t: eventType,
};
this.analyticsLogDebug('add event to queue: %j', data);
this.trackingEventsQueue.push(data);
}
async send(data) {
this.analyticsLogDebug('send event: %j', data);
return new Promise((resolve, reject) => {
const request = https.request({
host: 'www.google-analytics.com',
method: 'POST',
path: data.length > 1 ? '/batch' : '/collect',
}, (response) => {
if (response.statusCode !== 200) {
reject(new Error(`Analytics reporting failed with status code: ${response.statusCode}.`));
return;
}
});
request.on('error', reject);
const queryParameters = data.map((p) => querystring.stringify(p)).join('\n');
request.write(queryParameters);
request.end(resolve);
});
}
/**
* Creates the dimension and metrics variables to add to the queue.
* @private
*/
customVariables(options) {
const additionals = {};
const { dimensions, metrics } = options;
dimensions === null || dimensions === void 0 ? void 0 : dimensions.forEach((v, i) => (additionals[`cd${i}`] = v));
metrics === null || metrics === void 0 ? void 0 : metrics.forEach((v, i) => (additionals[`cm${i}`] = v));
return additionals;
}
}
exports.AnalyticsCollector = AnalyticsCollector;
// These are just approximations of UA strings. We just try to fool Google Analytics to give us the
// data we want.
// See https://developers.whatismybrowser.com/useragents/
const osVersionMap = {
darwin: {
'1.3.1': '10_0_4',
'1.4.1': '10_1_0',
'5.1': '10_1_1',
'5.2': '10_1_5',
'6.0.1': '10_2',
'6.8': '10_2_8',
'7.0': '10_3_0',
'7.9': '10_3_9',
'8.0': '10_4_0',
'8.11': '10_4_11',
'9.0': '10_5_0',
'9.8': '10_5_8',
'10.0': '10_6_0',
'10.8': '10_6_8',
// We stop here because we try to math out the version for anything greater than 10, and it
// works. Those versions are standardized using a calculation now.
},
win32: {
'6.3.9600': 'Windows 8.1',
'6.2.9200': 'Windows 8',
'6.1.7601': 'Windows 7 SP1',
'6.1.7600': 'Windows 7',
'6.0.6002': 'Windows Vista SP2',
'6.0.6000': 'Windows Vista',
'5.1.2600': 'Windows XP',
},
};
/**
* Build a fake User Agent string. This gets sent to Analytics so it shows the proper OS version.
* @private
*/
function _buildUserAgentString() {
switch (os.platform()) {
case 'darwin': {
let v = osVersionMap.darwin[os.release()];
if (!v) {
// Remove 4 to tie Darwin version to OSX version, add other info.
const x = parseFloat(os.release());
if (x > 10) {
v = `10_` + (x - 4).toString().replace('.', '_');
}
}
const cpuModel = os.cpus()[0].model.match(/^[a-z]+/i);
const cpu = cpuModel ? cpuModel[0] : os.cpus()[0].model;
return `(Macintosh; ${cpu} Mac OS X ${v || os.release()})`;
}
case 'win32':
return `(Windows NT ${os.release()})`;
case 'linux':
return `(X11; Linux i686; ${os.release()}; ${os.cpus()[0].model})`;
default:
return os.platform() + ' ' + os.release();
}
}
/**
* Get a language code.
* @private
*/
function _getLanguage() {
// Note: Windows does not expose the configured language by default.
return (process.env.LANG || // Default Unix env variable.
process.env.LC_CTYPE || // For C libraries. Sometimes the above isn't set.
process.env.LANGSPEC || // For Windows, sometimes this will be set (not always).
_getWindowsLanguageCode() ||
'??'); // ¯\_(ツ)_/¯
}
/**
* Attempt to get the Windows Language Code string.
* @private
*/
function _getWindowsLanguageCode() {
if (!os.platform().startsWith('win')) {
return undefined;
}
try {
// This is true on Windows XP, 7, 8 and 10 AFAIK. Would return empty string or fail if it
// doesn't work.
return child_process_1.execSync('wmic.exe os get locale').toString().trim();
}
catch { }
return undefined;
}

58
node_modules/@angular/cli/models/analytics.d.ts generated vendored Executable file
View file

@ -0,0 +1,58 @@
/**
* @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
*/
import { AnalyticsCollector } from './analytics-collector';
export declare const AnalyticsProperties: {
AngularCliProd: string;
AngularCliStaging: string;
readonly AngularCliDefault: string;
};
/**
* This is the ultimate safelist for checking if a package name is safe to report to analytics.
*/
export declare const analyticsPackageSafelist: (string | RegExp)[];
export declare function isPackageNameSafeForAnalytics(name: string): boolean;
/**
* Set analytics settings. This does not work if the user is not inside a project.
* @param level Which config to use. "global" for user-level, and "local" for project-level.
* @param value Either a user ID, true to generate a new User ID, or false to disable analytics.
*/
export declare function setAnalyticsConfig(level: 'global' | 'local', value: string | boolean): void;
/**
* Prompt the user for usage gathering permission.
* @param force Whether to ask regardless of whether or not the user is using an interactive shell.
* @return Whether or not the user was shown a prompt.
*/
export declare function promptGlobalAnalytics(force?: boolean): Promise<boolean>;
/**
* Prompt the user for usage gathering permission for the local project. Fails if there is no
* local workspace.
* @param force Whether to ask regardless of whether or not the user is using an interactive shell.
* @return Whether or not the user was shown a prompt.
*/
export declare function promptProjectAnalytics(force?: boolean): Promise<boolean>;
export declare function hasGlobalAnalyticsConfiguration(): Promise<boolean>;
/**
* Get the global analytics object for the user. This returns an instance of UniversalAnalytics,
* or undefined if analytics are disabled.
*
* If any problem happens, it is considered the user has been opting out of analytics.
*/
export declare function getGlobalAnalytics(): Promise<AnalyticsCollector | undefined>;
export declare function hasWorkspaceAnalyticsConfiguration(): Promise<boolean>;
/**
* Get the workspace analytics object for the user. This returns an instance of AnalyticsCollector,
* or undefined if analytics are disabled.
*
* If any problem happens, it is considered the user has been opting out of analytics.
*/
export declare function getWorkspaceAnalytics(): Promise<AnalyticsCollector | undefined>;
/**
* Return the usage analytics sharing setting, which is either a property string (GA-XXXXXXX-XX),
* or undefined if no sharing.
*/
export declare function getSharedAnalytics(): Promise<AnalyticsCollector | undefined>;

358
node_modules/@angular/cli/models/analytics.js generated vendored Executable file
View file

@ -0,0 +1,358 @@
"use strict";
/**
* @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
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSharedAnalytics = exports.getWorkspaceAnalytics = exports.hasWorkspaceAnalyticsConfiguration = exports.getGlobalAnalytics = exports.hasGlobalAnalyticsConfiguration = exports.promptProjectAnalytics = exports.promptGlobalAnalytics = exports.setAnalyticsConfig = exports.isPackageNameSafeForAnalytics = exports.analyticsPackageSafelist = exports.AnalyticsProperties = void 0;
const core_1 = require("@angular-devkit/core");
const debug_1 = __importDefault(require("debug"));
const inquirer = __importStar(require("inquirer"));
const uuid_1 = require("uuid");
const version_1 = require("../models/version");
const color_1 = require("../utilities/color");
const config_1 = require("../utilities/config");
const tty_1 = require("../utilities/tty");
const analytics_collector_1 = require("./analytics-collector");
/* eslint-disable no-console */
const analyticsDebug = debug_1.default('ng:analytics'); // Generate analytics, including settings and users.
let _defaultAngularCliPropertyCache;
exports.AnalyticsProperties = {
AngularCliProd: 'UA-8594346-29',
AngularCliStaging: 'UA-8594346-32',
get AngularCliDefault() {
if (_defaultAngularCliPropertyCache) {
return _defaultAngularCliPropertyCache;
}
const v = version_1.VERSION.full;
// The logic is if it's a full version then we should use the prod GA property.
if (/^\d+\.\d+\.\d+$/.test(v) && v !== '0.0.0') {
_defaultAngularCliPropertyCache = exports.AnalyticsProperties.AngularCliProd;
}
else {
_defaultAngularCliPropertyCache = exports.AnalyticsProperties.AngularCliStaging;
}
return _defaultAngularCliPropertyCache;
},
};
/**
* This is the ultimate safelist for checking if a package name is safe to report to analytics.
*/
exports.analyticsPackageSafelist = [
/^@angular\//,
/^@angular-devkit\//,
/^@ngtools\//,
'@schematics/angular',
];
function isPackageNameSafeForAnalytics(name) {
return exports.analyticsPackageSafelist.some((pattern) => {
if (typeof pattern == 'string') {
return pattern === name;
}
else {
return pattern.test(name);
}
});
}
exports.isPackageNameSafeForAnalytics = isPackageNameSafeForAnalytics;
/**
* Set analytics settings. This does not work if the user is not inside a project.
* @param level Which config to use. "global" for user-level, and "local" for project-level.
* @param value Either a user ID, true to generate a new User ID, or false to disable analytics.
*/
function setAnalyticsConfig(level, value) {
analyticsDebug('setting %s level analytics to: %s', level, value);
const [config, configPath] = config_1.getWorkspaceRaw(level);
if (!config || !configPath) {
throw new Error(`Could not find ${level} workspace.`);
}
const cli = config.get(['cli']);
if (cli !== undefined && !core_1.json.isJsonObject(cli)) {
throw new Error(`Invalid config found at ${configPath}. CLI should be an object.`);
}
if (value === true) {
value = uuid_1.v4();
}
config.modify(['cli', 'analytics'], value);
config.save();
analyticsDebug('done');
}
exports.setAnalyticsConfig = setAnalyticsConfig;
/**
* Prompt the user for usage gathering permission.
* @param force Whether to ask regardless of whether or not the user is using an interactive shell.
* @return Whether or not the user was shown a prompt.
*/
async function promptGlobalAnalytics(force = false) {
analyticsDebug('prompting global analytics.');
if (force || tty_1.isTTY()) {
const answers = await inquirer.prompt([
{
type: 'confirm',
name: 'analytics',
message: core_1.tags.stripIndents `
Would you like to share anonymous usage data with the Angular Team at Google under
Googles Privacy Policy at https://policies.google.com/privacy? For more details and
how to change this setting, see https://angular.io/analytics.
`,
default: false,
},
]);
setAnalyticsConfig('global', answers.analytics);
if (answers.analytics) {
console.log('');
console.log(core_1.tags.stripIndent `
Thank you for sharing anonymous usage data. If you change your mind, the following
command will disable this feature entirely:
${color_1.colors.yellow('ng analytics off')}
`);
console.log('');
// Send back a ping with the user `optin`.
const ua = new analytics_collector_1.AnalyticsCollector(exports.AnalyticsProperties.AngularCliDefault, 'optin');
ua.pageview('/telemetry/optin');
await ua.flush();
}
else {
// Send back a ping with the user `optout`. This is the only thing we send.
const ua = new analytics_collector_1.AnalyticsCollector(exports.AnalyticsProperties.AngularCliDefault, 'optout');
ua.pageview('/telemetry/optout');
await ua.flush();
}
return true;
}
else {
analyticsDebug('Either STDOUT or STDIN are not TTY and we skipped the prompt.');
}
return false;
}
exports.promptGlobalAnalytics = promptGlobalAnalytics;
/**
* Prompt the user for usage gathering permission for the local project. Fails if there is no
* local workspace.
* @param force Whether to ask regardless of whether or not the user is using an interactive shell.
* @return Whether or not the user was shown a prompt.
*/
async function promptProjectAnalytics(force = false) {
analyticsDebug('prompting user');
const [config, configPath] = config_1.getWorkspaceRaw('local');
if (!config || !configPath) {
throw new Error(`Could not find a local workspace. Are you in a project?`);
}
if (force || tty_1.isTTY()) {
const answers = await inquirer.prompt([
{
type: 'confirm',
name: 'analytics',
message: core_1.tags.stripIndents `
Would you like to share anonymous usage data about this project with the Angular Team at
Google under Googles Privacy Policy at https://policies.google.com/privacy? For more
details and how to change this setting, see https://angular.io/analytics.
`,
default: false,
},
]);
setAnalyticsConfig('local', answers.analytics);
if (answers.analytics) {
console.log('');
console.log(core_1.tags.stripIndent `
Thank you for sharing anonymous usage data. Would you change your mind, the following
command will disable this feature entirely:
${color_1.colors.yellow('ng analytics project off')}
`);
console.log('');
// Send back a ping with the user `optin`.
const ua = new analytics_collector_1.AnalyticsCollector(exports.AnalyticsProperties.AngularCliDefault, 'optin');
ua.pageview('/telemetry/project/optin');
await ua.flush();
}
else {
// Send back a ping with the user `optout`. This is the only thing we send.
const ua = new analytics_collector_1.AnalyticsCollector(exports.AnalyticsProperties.AngularCliDefault, 'optout');
ua.pageview('/telemetry/project/optout');
await ua.flush();
}
return true;
}
return false;
}
exports.promptProjectAnalytics = promptProjectAnalytics;
async function hasGlobalAnalyticsConfiguration() {
try {
const globalWorkspace = await config_1.getWorkspace('global');
const analyticsConfig = globalWorkspace && globalWorkspace.getCli() && globalWorkspace.getCli()['analytics'];
if (analyticsConfig !== null && analyticsConfig !== undefined) {
return true;
}
}
catch { }
return false;
}
exports.hasGlobalAnalyticsConfiguration = hasGlobalAnalyticsConfiguration;
/**
* Get the global analytics object for the user. This returns an instance of UniversalAnalytics,
* or undefined if analytics are disabled.
*
* If any problem happens, it is considered the user has been opting out of analytics.
*/
async function getGlobalAnalytics() {
analyticsDebug('getGlobalAnalytics');
const propertyId = exports.AnalyticsProperties.AngularCliDefault;
if ('NG_CLI_ANALYTICS' in process.env) {
if (process.env['NG_CLI_ANALYTICS'] == 'false' || process.env['NG_CLI_ANALYTICS'] == '') {
analyticsDebug('NG_CLI_ANALYTICS is false');
return undefined;
}
if (process.env['NG_CLI_ANALYTICS'] === 'ci') {
analyticsDebug('Running in CI mode');
return new analytics_collector_1.AnalyticsCollector(propertyId, 'ci');
}
}
// If anything happens we just keep the NOOP analytics.
try {
const globalWorkspace = await config_1.getWorkspace('global');
const analyticsConfig = globalWorkspace && globalWorkspace.getCli() && globalWorkspace.getCli()['analytics'];
analyticsDebug('Client Analytics config found: %j', analyticsConfig);
if (analyticsConfig === false) {
analyticsDebug('Analytics disabled. Ignoring all analytics.');
return undefined;
}
else if (analyticsConfig === undefined || analyticsConfig === null) {
analyticsDebug('Analytics settings not found. Ignoring all analytics.');
// globalWorkspace can be null if there is no file. analyticsConfig would be null in this
// case. Since there is no file, the user hasn't answered and the expected return value is
// undefined.
return undefined;
}
else {
let uid = undefined;
if (typeof analyticsConfig == 'string') {
uid = analyticsConfig;
}
else if (typeof analyticsConfig == 'object' && typeof analyticsConfig['uid'] == 'string') {
uid = analyticsConfig['uid'];
}
analyticsDebug('client id: %j', uid);
if (uid == undefined) {
return undefined;
}
return new analytics_collector_1.AnalyticsCollector(propertyId, uid);
}
}
catch (err) {
analyticsDebug('Error happened during reading of analytics config: %s', err.message);
return undefined;
}
}
exports.getGlobalAnalytics = getGlobalAnalytics;
async function hasWorkspaceAnalyticsConfiguration() {
try {
const globalWorkspace = await config_1.getWorkspace('local');
const analyticsConfig = globalWorkspace && globalWorkspace.getCli() && globalWorkspace.getCli()['analytics'];
if (analyticsConfig !== undefined) {
return true;
}
}
catch { }
return false;
}
exports.hasWorkspaceAnalyticsConfiguration = hasWorkspaceAnalyticsConfiguration;
/**
* Get the workspace analytics object for the user. This returns an instance of AnalyticsCollector,
* or undefined if analytics are disabled.
*
* If any problem happens, it is considered the user has been opting out of analytics.
*/
async function getWorkspaceAnalytics() {
analyticsDebug('getWorkspaceAnalytics');
try {
const globalWorkspace = await config_1.getWorkspace('local');
const analyticsConfig = globalWorkspace === null || globalWorkspace === void 0 ? void 0 : globalWorkspace.getCli()['analytics'];
analyticsDebug('Workspace Analytics config found: %j', analyticsConfig);
if (analyticsConfig === false) {
analyticsDebug('Analytics disabled. Ignoring all analytics.');
return undefined;
}
else if (analyticsConfig === undefined || analyticsConfig === null) {
analyticsDebug('Analytics settings not found. Ignoring all analytics.');
return undefined;
}
else {
let uid = undefined;
if (typeof analyticsConfig == 'string') {
uid = analyticsConfig;
}
else if (typeof analyticsConfig == 'object' && typeof analyticsConfig['uid'] == 'string') {
uid = analyticsConfig['uid'];
}
analyticsDebug('client id: %j', uid);
if (uid == undefined) {
return undefined;
}
return new analytics_collector_1.AnalyticsCollector(exports.AnalyticsProperties.AngularCliDefault, uid);
}
}
catch (err) {
analyticsDebug('Error happened during reading of analytics config: %s', err.message);
return undefined;
}
}
exports.getWorkspaceAnalytics = getWorkspaceAnalytics;
/**
* Return the usage analytics sharing setting, which is either a property string (GA-XXXXXXX-XX),
* or undefined if no sharing.
*/
async function getSharedAnalytics() {
analyticsDebug('getSharedAnalytics');
const envVarName = 'NG_CLI_ANALYTICS_SHARE';
if (envVarName in process.env) {
if (process.env[envVarName] == 'false' || process.env[envVarName] == '') {
analyticsDebug('NG_CLI_ANALYTICS is false');
return undefined;
}
}
// If anything happens we just keep the NOOP analytics.
try {
const globalWorkspace = await config_1.getWorkspace('global');
const analyticsConfig = globalWorkspace === null || globalWorkspace === void 0 ? void 0 : globalWorkspace.getCli()['analyticsSharing'];
if (!analyticsConfig || !analyticsConfig.tracking || !analyticsConfig.uuid) {
return undefined;
}
else {
analyticsDebug('Analytics sharing info: %j', analyticsConfig);
return new analytics_collector_1.AnalyticsCollector(analyticsConfig.tracking, analyticsConfig.uuid);
}
}
catch (err) {
analyticsDebug('Error happened during reading of analytics sharing config: %s', err.message);
return undefined;
}
}
exports.getSharedAnalytics = getSharedAnalytics;

33
node_modules/@angular/cli/models/architect-command.d.ts generated vendored Executable file
View file

@ -0,0 +1,33 @@
/**
* @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
*/
import { Architect, Target } from '@angular-devkit/architect';
import { WorkspaceNodeModulesArchitectHost } from '@angular-devkit/architect/node';
import { json } from '@angular-devkit/core';
import { BaseCommandOptions, Command } from './command';
import { Arguments } from './interface';
export interface ArchitectCommandOptions extends BaseCommandOptions {
project?: string;
configuration?: string;
prod?: boolean;
target?: string;
}
export declare abstract class ArchitectCommand<T extends ArchitectCommandOptions = ArchitectCommandOptions> extends Command<T> {
protected _architect: Architect;
protected _architectHost: WorkspaceNodeModulesArchitectHost;
protected _registry: json.schema.SchemaRegistry;
protected readonly useReportAnalytics = false;
protected multiTarget: boolean;
target: string | undefined;
missingTargetError: string | undefined;
initialize(options: T & Arguments): Promise<number | void>;
run(options: ArchitectCommandOptions & Arguments): Promise<number>;
protected runSingleTarget(target: Target, targetOptions: string[]): Promise<0 | 1>;
protected runArchitectTarget(options: ArchitectCommandOptions & Arguments): Promise<number>;
private getProjectNamesByTarget;
private _makeTargetSpecifier;
}

295
node_modules/@angular/cli/models/architect-command.js generated vendored Executable file
View file

@ -0,0 +1,295 @@
"use strict";
/**
* @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
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ArchitectCommand = void 0;
const architect_1 = require("@angular-devkit/architect");
const node_1 = require("@angular-devkit/architect/node");
const core_1 = require("@angular-devkit/core");
const json_schema_1 = require("../utilities/json-schema");
const analytics_1 = require("./analytics");
const command_1 = require("./command");
const parser_1 = require("./parser");
class ArchitectCommand extends command_1.Command {
constructor() {
super(...arguments);
this.useReportAnalytics = false;
// If this command supports running multiple targets.
this.multiTarget = false;
}
async initialize(options) {
this._registry = new core_1.json.schema.CoreSchemaRegistry();
this._registry.addPostTransform(core_1.json.schema.transforms.addUndefinedDefaults);
this._registry.useXDeprecatedProvider((msg) => this.logger.warn(msg));
if (!this.workspace) {
this.logger.fatal('A workspace is required for this command.');
return 1;
}
this._architectHost = new node_1.WorkspaceNodeModulesArchitectHost(this.workspace, this.workspace.basePath);
this._architect = new architect_1.Architect(this._architectHost, this._registry);
if (!this.target) {
if (options.help) {
// This is a special case where we just return.
return;
}
const specifier = this._makeTargetSpecifier(options);
if (!specifier.project || !specifier.target) {
this.logger.fatal('Cannot determine project or target for command.');
return 1;
}
return;
}
let projectName = options.project;
if (projectName && !this.workspace.projects.has(projectName)) {
this.logger.fatal(`Project '${projectName}' does not exist.`);
return 1;
}
const commandLeftovers = options['--'];
const targetProjectNames = [];
for (const [name, project] of this.workspace.projects) {
if (project.targets.has(this.target)) {
targetProjectNames.push(name);
}
}
if (targetProjectNames.length === 0) {
this.logger.fatal(this.missingTargetError || `No projects support the '${this.target}' target.`);
return 1;
}
if (projectName && !targetProjectNames.includes(projectName)) {
this.logger.fatal(this.missingTargetError ||
`Project '${projectName}' does not support the '${this.target}' target.`);
return 1;
}
if (!projectName && commandLeftovers && commandLeftovers.length > 0) {
const builderNames = new Set();
const leftoverMap = new Map();
let potentialProjectNames = new Set(targetProjectNames);
for (const name of targetProjectNames) {
const builderName = await this._architectHost.getBuilderNameForTarget({
project: name,
target: this.target,
});
if (this.multiTarget) {
builderNames.add(builderName);
}
const builderDesc = await this._architectHost.resolveBuilder(builderName);
const optionDefs = await json_schema_1.parseJsonSchemaToOptions(this._registry, builderDesc.optionSchema);
const parsedOptions = parser_1.parseArguments([...commandLeftovers], optionDefs);
const builderLeftovers = parsedOptions['--'] || [];
leftoverMap.set(name, { optionDefs, parsedOptions });
potentialProjectNames = new Set(builderLeftovers.filter((x) => potentialProjectNames.has(x)));
}
if (potentialProjectNames.size === 1) {
projectName = [...potentialProjectNames][0];
// remove the project name from the leftovers
const optionInfo = leftoverMap.get(projectName);
if (optionInfo) {
const locations = [];
let i = 0;
while (i < commandLeftovers.length) {
i = commandLeftovers.indexOf(projectName, i + 1);
if (i === -1) {
break;
}
locations.push(i);
}
delete optionInfo.parsedOptions['--'];
for (const location of locations) {
const tempLeftovers = [...commandLeftovers];
tempLeftovers.splice(location, 1);
const tempArgs = parser_1.parseArguments([...tempLeftovers], optionInfo.optionDefs);
delete tempArgs['--'];
if (JSON.stringify(optionInfo.parsedOptions) === JSON.stringify(tempArgs)) {
options['--'] = tempLeftovers;
break;
}
}
}
}
if (!projectName && this.multiTarget && builderNames.size > 1) {
this.logger.fatal(core_1.tags.oneLine `
Architect commands with command line overrides cannot target different builders. The
'${this.target}' target would run on projects ${targetProjectNames.join()} which have the
following builders: ${'\n ' + [...builderNames].join('\n ')}
`);
return 1;
}
}
if (!projectName && !this.multiTarget) {
const defaultProjectName = this.workspace.extensions['defaultProject'];
if (targetProjectNames.length === 1) {
projectName = targetProjectNames[0];
}
else if (defaultProjectName && targetProjectNames.includes(defaultProjectName)) {
projectName = defaultProjectName;
}
else if (options.help) {
// This is a special case where we just return.
return;
}
else {
this.logger.fatal(this.missingTargetError || 'Cannot determine project or target for command.');
return 1;
}
}
options.project = projectName;
const builderConf = await this._architectHost.getBuilderNameForTarget({
project: projectName || (targetProjectNames.length > 0 ? targetProjectNames[0] : ''),
target: this.target,
});
const builderDesc = await this._architectHost.resolveBuilder(builderConf);
this.description.options.push(...(await json_schema_1.parseJsonSchemaToOptions(this._registry, builderDesc.optionSchema)));
// Update options to remove analytics from options if the builder isn't safelisted.
for (const o of this.description.options) {
if (o.userAnalytics && !analytics_1.isPackageNameSafeForAnalytics(builderConf)) {
o.userAnalytics = undefined;
}
}
}
async run(options) {
return await this.runArchitectTarget(options);
}
async runSingleTarget(target, targetOptions) {
// We need to build the builderSpec twice because architect does not understand
// overrides separately (getting the configuration builds the whole project, including
// overrides).
const builderConf = await this._architectHost.getBuilderNameForTarget(target);
const builderDesc = await this._architectHost.resolveBuilder(builderConf);
const targetOptionArray = await json_schema_1.parseJsonSchemaToOptions(this._registry, builderDesc.optionSchema);
const overrides = parser_1.parseArguments(targetOptions, targetOptionArray, this.logger);
const allowAdditionalProperties = typeof builderDesc.optionSchema === 'object' && builderDesc.optionSchema.additionalProperties;
if (overrides['--'] && !allowAdditionalProperties) {
(overrides['--'] || []).forEach((additional) => {
this.logger.fatal(`Unknown option: '${additional.split(/=/)[0]}'`);
});
return 1;
}
await this.reportAnalytics([this.description.name], {
...(await this._architectHost.getOptionsForTarget(target)),
...overrides,
});
const run = await this._architect.scheduleTarget(target, overrides, {
logger: this.logger,
analytics: analytics_1.isPackageNameSafeForAnalytics(builderConf) ? this.analytics : undefined,
});
const { error, success } = await run.output.toPromise();
await run.stop();
if (error) {
this.logger.error(error);
}
return success ? 0 : 1;
}
async runArchitectTarget(options) {
var _a;
const extra = options['--'] || [];
try {
const targetSpec = this._makeTargetSpecifier(options);
if (!targetSpec.project && this.target) {
// This runs each target sequentially.
// Running them in parallel would jumble the log messages.
let result = 0;
for (const project of this.getProjectNamesByTarget(this.target)) {
result |= await this.runSingleTarget({ ...targetSpec, project }, extra);
}
return result;
}
else {
return await this.runSingleTarget(targetSpec, extra);
}
}
catch (e) {
if (e instanceof core_1.schema.SchemaValidationException) {
const newErrors = [];
for (const schemaError of e.errors) {
if (schemaError.keyword === 'additionalProperties') {
const unknownProperty = (_a = schemaError.params) === null || _a === void 0 ? void 0 : _a.additionalProperty;
if (unknownProperty in options) {
const dashes = unknownProperty.length === 1 ? '-' : '--';
this.logger.fatal(`Unknown option: '${dashes}${unknownProperty}'`);
continue;
}
}
newErrors.push(schemaError);
}
if (newErrors.length > 0) {
this.logger.error(new core_1.schema.SchemaValidationException(newErrors).message);
}
return 1;
}
else {
throw e;
}
}
}
getProjectNamesByTarget(targetName) {
const allProjectsForTargetName = [];
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
for (const [name, project] of this.workspace.projects) {
if (project.targets.has(targetName)) {
allProjectsForTargetName.push(name);
}
}
if (this.multiTarget) {
// For multi target commands, we always list all projects that have the target.
return allProjectsForTargetName;
}
else {
// For single target commands, we try the default project first,
// then the full list if it has a single project, then error out.
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const maybeDefaultProject = this.workspace.extensions['defaultProject'];
if (maybeDefaultProject && allProjectsForTargetName.includes(maybeDefaultProject)) {
return [maybeDefaultProject];
}
if (allProjectsForTargetName.length === 1) {
return allProjectsForTargetName;
}
throw new Error(`Could not determine a single project for the '${targetName}' target.`);
}
}
_makeTargetSpecifier(commandOptions) {
var _a, _b, _c;
let project, target, configuration;
if (commandOptions.target) {
[project, target, configuration] = commandOptions.target.split(':');
if (commandOptions.configuration) {
configuration = commandOptions.configuration;
}
}
else {
project = commandOptions.project;
target = this.target;
if (commandOptions.prod) {
const defaultConfig = project &&
target &&
((_c = (_b = (_a = this.workspace) === null || _a === void 0 ? void 0 : _a.projects.get(project)) === null || _b === void 0 ? void 0 : _b.targets.get(target)) === null || _c === void 0 ? void 0 : _c.defaultConfiguration);
this.logger.warn(defaultConfig === 'production'
? 'Option "--prod" is deprecated: No need to use this option as this builder defaults to configuration "production".'
: 'Option "--prod" is deprecated: Use "--configuration production" instead.');
// The --prod flag will always be the first configuration, available to be overwritten
// by following configurations.
configuration = 'production';
}
if (commandOptions.configuration) {
configuration = `${configuration ? `${configuration},` : ''}${commandOptions.configuration}`;
}
}
if (!project) {
project = '';
}
if (!target) {
target = '';
}
return {
project,
configuration: configuration || '',
target,
};
}
}
exports.ArchitectCommand = ArchitectCommand;

24
node_modules/@angular/cli/models/command-runner.d.ts generated vendored Executable file
View file

@ -0,0 +1,24 @@
/**
* @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
*/
import { analytics, logging } from '@angular-devkit/core';
import { AngularWorkspace } from '../utilities/config';
export interface CommandMapOptions {
[key: string]: string;
}
/**
* Run a command.
* @param args Raw unparsed arguments.
* @param logger The logger to use.
* @param workspace Workspace information.
* @param commands The map of supported commands.
* @param options Additional options.
*/
export declare function runCommand(args: string[], logger: logging.Logger, workspace: AngularWorkspace | undefined, commands?: CommandMapOptions, options?: {
analytics?: analytics.Analytics;
currentDirectory: string;
}): Promise<number | void>;

241
node_modules/@angular/cli/models/command-runner.js generated vendored Executable file
View file

@ -0,0 +1,241 @@
"use strict";
/**
* @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
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.runCommand = void 0;
const core_1 = require("@angular-devkit/core");
const fs_1 = require("fs");
const path_1 = require("path");
const json_file_1 = require("../utilities/json-file");
const json_schema_1 = require("../utilities/json-schema");
const analytics_1 = require("./analytics");
const command_1 = require("./command");
const parser = __importStar(require("./parser"));
// NOTE: Update commands.json if changing this. It's still deep imported in one CI validation
const standardCommands = {
'add': '../commands/add.json',
'analytics': '../commands/analytics.json',
'build': '../commands/build.json',
'deploy': '../commands/deploy.json',
'config': '../commands/config.json',
'doc': '../commands/doc.json',
'e2e': '../commands/e2e.json',
'extract-i18n': '../commands/extract-i18n.json',
'make-this-awesome': '../commands/easter-egg.json',
'generate': '../commands/generate.json',
'help': '../commands/help.json',
'lint': '../commands/lint.json',
'new': '../commands/new.json',
'run': '../commands/run.json',
'serve': '../commands/serve.json',
'test': '../commands/test.json',
'update': '../commands/update.json',
'version': '../commands/version.json',
};
/**
* Create the analytics instance.
* @private
*/
async function _createAnalytics(workspace, skipPrompt = false) {
let config = await analytics_1.getGlobalAnalytics();
// If in workspace and global analytics is enabled, defer to workspace level
if (workspace && config) {
const skipAnalytics = skipPrompt ||
(process.env['NG_CLI_ANALYTICS'] &&
(process.env['NG_CLI_ANALYTICS'].toLowerCase() === 'false' ||
process.env['NG_CLI_ANALYTICS'] === '0'));
// TODO: This should honor the `no-interactive` option.
// It is currently not an `ng` option but rather only an option for specific commands.
// The concept of `ng`-wide options are needed to cleanly handle this.
if (!skipAnalytics && !(await analytics_1.hasWorkspaceAnalyticsConfiguration())) {
await analytics_1.promptProjectAnalytics();
}
config = await analytics_1.getWorkspaceAnalytics();
}
const maybeSharedAnalytics = await analytics_1.getSharedAnalytics();
if (config && maybeSharedAnalytics) {
return new core_1.analytics.MultiAnalytics([config, maybeSharedAnalytics]);
}
else if (config) {
return config;
}
else if (maybeSharedAnalytics) {
return maybeSharedAnalytics;
}
else {
return new core_1.analytics.NoopAnalytics();
}
}
async function loadCommandDescription(name, path, registry) {
const schemaPath = path_1.resolve(__dirname, path);
const schema = json_file_1.readAndParseJson(schemaPath);
if (!core_1.isJsonObject(schema)) {
throw new Error('Invalid command JSON loaded from ' + JSON.stringify(schemaPath));
}
return json_schema_1.parseJsonSchemaToCommandDescription(name, schemaPath, registry, schema);
}
/**
* Run a command.
* @param args Raw unparsed arguments.
* @param logger The logger to use.
* @param workspace Workspace information.
* @param commands The map of supported commands.
* @param options Additional options.
*/
async function runCommand(args, logger, workspace, commands = standardCommands, options = {
currentDirectory: process.cwd(),
}) {
var _a;
// This registry is exclusively used for flattening schemas, and not for validating.
const registry = new core_1.schema.CoreSchemaRegistry([]);
registry.registerUriHandler((uri) => {
if (uri.startsWith('ng-cli://')) {
const content = fs_1.readFileSync(path_1.join(__dirname, '..', uri.substr('ng-cli://'.length)), 'utf-8');
return Promise.resolve(JSON.parse(content));
}
else {
return null;
}
});
let commandName = undefined;
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (!arg.startsWith('-')) {
commandName = arg;
args.splice(i, 1);
break;
}
}
let description = null;
// if no commands were found, use `help`.
if (!commandName) {
if (args.length === 1 && args[0] === '--version') {
commandName = 'version';
}
else {
commandName = 'help';
}
if (!(commandName in commands)) {
logger.error(core_1.tags.stripIndent `
The "${commandName}" command seems to be disabled.
This is an issue with the CLI itself. If you see this comment, please report it and
provide your repository.
`);
return 1;
}
}
if (commandName in commands) {
description = await loadCommandDescription(commandName, commands[commandName], registry);
}
else {
const commandNames = Object.keys(commands);
// Optimize loading for common aliases
if (commandName.length === 1) {
commandNames.sort((a, b) => {
const aMatch = a[0] === commandName;
const bMatch = b[0] === commandName;
if (aMatch && !bMatch) {
return -1;
}
else if (!aMatch && bMatch) {
return 1;
}
else {
return 0;
}
});
}
for (const name of commandNames) {
const aliasDesc = await loadCommandDescription(name, commands[name], registry);
const aliases = aliasDesc.aliases;
if (aliases && aliases.some((alias) => alias === commandName)) {
commandName = name;
description = aliasDesc;
break;
}
}
}
if (!description) {
const commandsDistance = {};
const name = commandName;
const allCommands = Object.keys(commands).sort((a, b) => {
if (!(a in commandsDistance)) {
commandsDistance[a] = core_1.strings.levenshtein(a, name);
}
if (!(b in commandsDistance)) {
commandsDistance[b] = core_1.strings.levenshtein(b, name);
}
return commandsDistance[a] - commandsDistance[b];
});
logger.error(core_1.tags.stripIndent `
The specified command ("${commandName}") is invalid. For a list of available options,
run "ng help".
Did you mean "${allCommands[0]}"?
`);
return 1;
}
try {
const parsedOptions = parser.parseArguments(args, description.options, logger);
command_1.Command.setCommandMap(async () => {
const map = {};
for (const [name, path] of Object.entries(commands)) {
map[name] = await loadCommandDescription(name, path, registry);
}
return map;
});
const analytics = options.analytics || (await _createAnalytics(!!workspace, description.name === 'update'));
const context = {
workspace,
analytics,
currentDirectory: options.currentDirectory,
root: (_a = workspace === null || workspace === void 0 ? void 0 : workspace.basePath) !== null && _a !== void 0 ? _a : options.currentDirectory,
};
const command = new description.impl(context, description, logger);
// Flush on an interval (if the event loop is waiting).
let analyticsFlushPromise = Promise.resolve();
const analyticsFlushInterval = setInterval(() => {
analyticsFlushPromise = analyticsFlushPromise.then(() => analytics.flush());
}, 1000);
const result = await command.validateAndRun(parsedOptions);
// Flush one last time.
clearInterval(analyticsFlushInterval);
await analyticsFlushPromise.then(() => analytics.flush());
return result;
}
catch (e) {
if (e instanceof parser.ParseArgumentException) {
logger.fatal('Cannot parse arguments. See below for the reasons.');
logger.fatal(' ' + e.comments.join('\n '));
return 1;
}
else {
throw e;
}
}
}
exports.runCommand = runCommand;

34
node_modules/@angular/cli/models/command.d.ts generated vendored Executable file
View file

@ -0,0 +1,34 @@
/**
* @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
*/
import { analytics, logging } from '@angular-devkit/core';
import { AngularWorkspace } from '../utilities/config';
import { Arguments, CommandContext, CommandDescription, CommandDescriptionMap, CommandScope, Option } from './interface';
export interface BaseCommandOptions {
help?: boolean | string;
}
export declare abstract class Command<T extends BaseCommandOptions = BaseCommandOptions> {
protected readonly context: CommandContext;
readonly description: CommandDescription;
protected readonly logger: logging.Logger;
protected allowMissingWorkspace: boolean;
protected useReportAnalytics: boolean;
readonly workspace?: AngularWorkspace;
readonly analytics: analytics.Analytics;
protected static commandMap: () => Promise<CommandDescriptionMap>;
static setCommandMap(map: () => Promise<CommandDescriptionMap>): void;
constructor(context: CommandContext, description: CommandDescription, logger: logging.Logger);
initialize(options: T & Arguments): Promise<number | void>;
printHelp(): Promise<number>;
printJsonHelp(): Promise<number>;
protected printHelpUsage(): Promise<void>;
protected printHelpOptions(options?: Option[]): Promise<void>;
validateScope(scope?: CommandScope): Promise<void>;
reportAnalytics(paths: string[], options: Arguments, dimensions?: (boolean | number | string)[], metrics?: (boolean | number | string)[]): Promise<void>;
abstract run(options: T & Arguments): Promise<number | void>;
validateAndRun(options: T & Arguments): Promise<number | void>;
}

143
node_modules/@angular/cli/models/command.js generated vendored Executable file
View file

@ -0,0 +1,143 @@
"use strict";
/**
* @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
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Command = void 0;
const core_1 = require("@angular-devkit/core");
const color_1 = require("../utilities/color");
const interface_1 = require("./interface");
class Command {
constructor(context, description, logger) {
this.context = context;
this.description = description;
this.logger = logger;
this.allowMissingWorkspace = false;
this.useReportAnalytics = true;
this.workspace = context.workspace;
this.analytics = context.analytics || new core_1.analytics.NoopAnalytics();
}
static setCommandMap(map) {
this.commandMap = map;
}
async initialize(options) { }
async printHelp() {
await this.printHelpUsage();
await this.printHelpOptions();
return 0;
}
async printJsonHelp() {
const replacer = (key, value) => key === 'name' ? core_1.strings.dasherize(value) : value;
this.logger.info(JSON.stringify(this.description, replacer, 2));
return 0;
}
async printHelpUsage() {
this.logger.info(this.description.description);
const name = this.description.name;
const args = this.description.options.filter((x) => x.positional !== undefined);
const opts = this.description.options.filter((x) => x.positional === undefined);
const argDisplay = args && args.length > 0 ? ' ' + args.map((a) => `<${a.name}>`).join(' ') : '';
const optionsDisplay = opts && opts.length > 0 ? ` [options]` : ``;
this.logger.info(`usage: ng ${name}${argDisplay}${optionsDisplay}`);
this.logger.info('');
}
async printHelpOptions(options = this.description.options) {
const args = options.filter((opt) => opt.positional !== undefined);
const opts = options.filter((opt) => opt.positional === undefined);
const formatDescription = (description) => ` ${description.replace(/\n/g, '\n ')}`;
if (args.length > 0) {
this.logger.info(`arguments:`);
args.forEach((o) => {
this.logger.info(` ${color_1.colors.cyan(o.name)}`);
if (o.description) {
this.logger.info(formatDescription(o.description));
}
});
}
if (options.length > 0) {
if (args.length > 0) {
this.logger.info('');
}
this.logger.info(`options:`);
opts
.filter((o) => !o.hidden)
.sort((a, b) => a.name.localeCompare(b.name))
.forEach((o) => {
const aliases = o.aliases && o.aliases.length > 0
? '(' + o.aliases.map((a) => `-${a}`).join(' ') + ')'
: '';
this.logger.info(` ${color_1.colors.cyan('--' + core_1.strings.dasherize(o.name))} ${aliases}`);
if (o.description) {
this.logger.info(formatDescription(o.description));
}
});
}
}
async validateScope(scope) {
switch (scope === undefined ? this.description.scope : scope) {
case interface_1.CommandScope.OutProject:
if (this.workspace) {
this.logger.fatal(core_1.tags.oneLine `
The ${this.description.name} command requires to be run outside of a project, but a
project definition was found at "${this.workspace.filePath}".
`);
// eslint-disable-next-line no-throw-literal
throw 1;
}
break;
case interface_1.CommandScope.InProject:
if (!this.workspace) {
this.logger.fatal(core_1.tags.oneLine `
The ${this.description.name} command requires to be run in an Angular project, but a
project definition could not be found.
`);
// eslint-disable-next-line no-throw-literal
throw 1;
}
break;
case interface_1.CommandScope.Everywhere:
// Can't miss this.
break;
}
}
async reportAnalytics(paths, options, dimensions = [], metrics = []) {
for (const option of this.description.options) {
const ua = option.userAnalytics;
const v = options[option.name];
if (v !== undefined && !Array.isArray(v) && ua) {
dimensions[ua] = v;
}
}
this.analytics.pageview('/command/' + paths.join('/'), { dimensions, metrics });
}
async validateAndRun(options) {
if (!(options.help === true || options.help === 'json' || options.help === 'JSON')) {
await this.validateScope();
}
let result = await this.initialize(options);
if (typeof result === 'number' && result !== 0) {
return result;
}
if (options.help === true) {
return this.printHelp();
}
else if (options.help === 'json' || options.help === 'JSON') {
return this.printJsonHelp();
}
else {
const startTime = +new Date();
if (this.useReportAnalytics) {
await this.reportAnalytics([this.description.name], options);
}
result = await this.run(options);
const endTime = +new Date();
this.analytics.timing(this.description.name, 'duration', endTime - startTime);
return result;
}
}
}
exports.Command = Command;

10
node_modules/@angular/cli/models/error.d.ts generated vendored Executable file
View file

@ -0,0 +1,10 @@
/**
* @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
*/
export declare class NgToolkitError extends Error {
constructor(message?: string);
}

22
node_modules/@angular/cli/models/error.js generated vendored Executable file
View file

@ -0,0 +1,22 @@
"use strict";
/**
* @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
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.NgToolkitError = void 0;
class NgToolkitError extends Error {
constructor(message) {
super();
if (message) {
this.message = message;
}
else {
this.message = this.constructor.name;
}
}
}
exports.NgToolkitError = NgToolkitError;

196
node_modules/@angular/cli/models/interface.d.ts generated vendored Executable file
View file

@ -0,0 +1,196 @@
/**
* @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
*/
import { analytics, json, logging } from '@angular-devkit/core';
import { AngularWorkspace } from '../utilities/config';
/**
* Value type of arguments.
*/
export declare type Value = number | string | boolean | (number | string | boolean)[];
/**
* An object representing parsed arguments from the command line.
*/
export interface Arguments {
[argName: string]: Value | undefined;
/**
* Extra arguments that were not parsed. Will be omitted if all arguments were parsed.
*/
'--'?: string[];
}
/**
* The base interface for Command, understood by the command runner.
*/
export interface CommandInterface<T extends Arguments = Arguments> {
printHelp(options: T): Promise<number>;
printJsonHelp(options: T): Promise<number>;
validateAndRun(options: T): Promise<number>;
}
/**
* Command constructor.
*/
export interface CommandConstructor {
new (context: CommandContext, description: CommandDescription, logger: logging.Logger): CommandInterface;
}
/**
* A command runner context.
*/
export interface CommandContext {
currentDirectory: string;
root: string;
workspace?: AngularWorkspace;
analytics?: analytics.Analytics;
}
/**
* Value types of an Option.
*/
export declare enum OptionType {
Any = "any",
Array = "array",
Boolean = "boolean",
Number = "number",
String = "string"
}
/**
* An option description. This is exposed when using `ng --help=json`.
*/
export interface Option {
/**
* The name of the option.
*/
name: string;
/**
* A short description of the option.
*/
description: string;
/**
* The type of option value. If multiple types exist, this type will be the first one, and the
* types array will contain all types accepted.
*/
type: OptionType;
/**
* {@see type}
*/
types?: OptionType[];
/**
* If this field is set, only values contained in this field are valid. This array can be mixed
* types (strings, numbers, boolean). For example, if this field is "enum: ['hello', true]",
* then "type" will be either string or boolean, types will be at least both, and the values
* accepted will only be either 'hello' or true (not false or any other string).
* This mean that prefixing with `no-` will not work on this field.
*/
enum?: Value[];
/**
* If this option maps to a subcommand in the parent command, will contain all the subcommands
* supported. There is a maximum of 1 subcommand Option per command, and the type of this
* option will always be "string" (no other types). The value of this option will map into
* this map and return the extra information.
*/
subcommands?: {
[name: string]: SubCommandDescription;
};
/**
* Aliases supported by this option.
*/
aliases: string[];
/**
* Whether this option is required or not.
*/
required?: boolean;
/**
* Format field of this option.
*/
format?: string;
/**
* Whether this option should be hidden from the help output. It will still show up in JSON help.
*/
hidden?: boolean;
/**
* Default value of this option.
*/
default?: string | number | boolean;
/**
* If this option can be used as an argument, the position of the argument. Otherwise omitted.
*/
positional?: number;
/**
* Smart default object.
*/
$default?: OptionSmartDefault;
/**
* Whether or not to report this option to the Angular Team, and which custom field to use.
* If this is falsey, do not report this option.
*/
userAnalytics?: number;
/**
* Deprecation. If this flag is not false a warning will be shown on the console. Either `true`
* or a string to show the user as a notice.
*/
deprecated?: boolean | string;
}
/**
* Scope of the command.
*/
export declare enum CommandScope {
InProject = "in",
OutProject = "out",
Everywhere = "all",
Default = "in"
}
/**
* A description of a command and its options.
*/
export interface SubCommandDescription {
/**
* The name of the subcommand.
*/
name: string;
/**
* Short description (1-2 lines) of this sub command.
*/
description: string;
/**
* A long description of the sub command, in Markdown format.
*/
longDescription?: string;
/**
* Additional notes about usage of this sub command, in Markdown format.
*/
usageNotes?: string;
/**
* List of all supported options.
*/
options: Option[];
/**
* Aliases supported for this sub command.
*/
aliases: string[];
}
/**
* A description of a command, its metadata.
*/
export interface CommandDescription extends SubCommandDescription {
/**
* Scope of the command, whether it can be executed in a project, outside of a project or
* anywhere.
*/
scope: CommandScope;
/**
* Whether this command should be hidden from a list of all commands.
*/
hidden: boolean;
/**
* The constructor of the command, which should be extending the abstract Command<> class.
*/
impl: CommandConstructor;
}
export interface OptionSmartDefault {
$source: string;
[key: string]: json.JsonValue;
}
export interface CommandDescriptionMap {
[key: string]: CommandDescription;
}

31
node_modules/@angular/cli/models/interface.js generated vendored Executable file
View file

@ -0,0 +1,31 @@
"use strict";
/**
* @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
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommandScope = exports.OptionType = void 0;
/**
* Value types of an Option.
*/
var OptionType;
(function (OptionType) {
OptionType["Any"] = "any";
OptionType["Array"] = "array";
OptionType["Boolean"] = "boolean";
OptionType["Number"] = "number";
OptionType["String"] = "string";
})(OptionType = exports.OptionType || (exports.OptionType = {}));
/**
* Scope of the command.
*/
var CommandScope;
(function (CommandScope) {
CommandScope["InProject"] = "in";
CommandScope["OutProject"] = "out";
CommandScope["Everywhere"] = "all";
CommandScope["Default"] = "in";
})(CommandScope = exports.CommandScope || (exports.CommandScope = {}));

39
node_modules/@angular/cli/models/parser.d.ts generated vendored Executable file
View file

@ -0,0 +1,39 @@
/**
* @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
*/
import { BaseException, logging } from '@angular-devkit/core';
import { Arguments, Option } from './interface';
export declare class ParseArgumentException extends BaseException {
readonly comments: string[];
readonly parsed: Arguments;
readonly ignored: string[];
constructor(comments: string[], parsed: Arguments, ignored: string[]);
}
/**
* Parse the arguments in a consistent way, but without having any option definition. This tries
* to assess what the user wants in a free form. For example, using `--name=false` will set the
* name properties to a boolean type.
* This should only be used when there's no schema available or if a schema is "true" (anything is
* valid).
*
* @param args Argument list to parse.
* @returns An object that contains a property per flags from the args.
*/
export declare function parseFreeFormArguments(args: string[]): Arguments;
/**
* Parse the arguments in a consistent way, from a list of standardized options.
* The result object will have a key per option name, with the `_` key reserved for positional
* arguments, and `--` will contain everything that did not match. Any key that don't have an
* option will be pushed back in `--` and removed from the object. If you need to validate that
* there's no additionalProperties, you need to check the `--` key.
*
* @param args The argument array to parse.
* @param options List of supported options. {@see Option}.
* @param logger Logger to use to warn users.
* @returns An object that contains a property per option.
*/
export declare function parseArguments(args: string[], options: Option[] | null, logger?: logging.Logger): Arguments;

349
node_modules/@angular/cli/models/parser.js generated vendored Executable file
View file

@ -0,0 +1,349 @@
"use strict";
/**
* @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
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseArguments = exports.parseFreeFormArguments = exports.ParseArgumentException = void 0;
const core_1 = require("@angular-devkit/core");
const interface_1 = require("./interface");
class ParseArgumentException extends core_1.BaseException {
constructor(comments, parsed, ignored) {
super(`One or more errors occurred while parsing arguments:\n ${comments.join('\n ')}`);
this.comments = comments;
this.parsed = parsed;
this.ignored = ignored;
}
}
exports.ParseArgumentException = ParseArgumentException;
function _coerceType(str, type, v) {
switch (type) {
case interface_1.OptionType.Any:
if (Array.isArray(v)) {
return v.concat(str || '');
}
return _coerceType(str, interface_1.OptionType.Boolean, v) !== undefined
? _coerceType(str, interface_1.OptionType.Boolean, v)
: _coerceType(str, interface_1.OptionType.Number, v) !== undefined
? _coerceType(str, interface_1.OptionType.Number, v)
: _coerceType(str, interface_1.OptionType.String, v);
case interface_1.OptionType.String:
return str || '';
case interface_1.OptionType.Boolean:
switch (str) {
case 'false':
return false;
case undefined:
case '':
case 'true':
return true;
default:
return undefined;
}
case interface_1.OptionType.Number:
if (str === undefined) {
return 0;
}
else if (str === '') {
return undefined;
}
else if (Number.isFinite(+str)) {
return +str;
}
else {
return undefined;
}
case interface_1.OptionType.Array:
return Array.isArray(v)
? v.concat(str || '')
: v === undefined
? [str || '']
: [v + '', str || ''];
default:
return undefined;
}
}
function _coerce(str, o, v) {
if (!o) {
return _coerceType(str, interface_1.OptionType.Any, v);
}
else {
const types = o.types || [o.type];
// Try all the types one by one and pick the first one that returns a value contained in the
// enum. If there's no enum, just return the first one that matches.
for (const type of types) {
const maybeResult = _coerceType(str, type, v);
if (maybeResult !== undefined && (!o.enum || o.enum.includes(maybeResult))) {
return maybeResult;
}
}
return undefined;
}
}
function _getOptionFromName(name, options) {
const camelName = /(-|_)/.test(name) ? core_1.strings.camelize(name) : name;
for (const option of options) {
if (option.name === name || option.name === camelName) {
return option;
}
if (option.aliases.some((x) => x === name || x === camelName)) {
return option;
}
}
return undefined;
}
function _removeLeadingDashes(key) {
const from = key.startsWith('--') ? 2 : key.startsWith('-') ? 1 : 0;
return key.substr(from);
}
function _assignOption(arg, nextArg, { options, parsedOptions, leftovers, ignored, errors, warnings, }) {
const from = arg.startsWith('--') ? 2 : 1;
let consumedNextArg = false;
let key = arg.substr(from);
let option = null;
let value = '';
const i = arg.indexOf('=');
// If flag is --no-abc AND there's no equal sign.
if (i == -1) {
if (key.startsWith('no')) {
// Only use this key if the option matching the rest is a boolean.
const from = key.startsWith('no-') ? 3 : 2;
const maybeOption = _getOptionFromName(core_1.strings.camelize(key.substr(from)), options);
if (maybeOption && maybeOption.type == 'boolean') {
value = 'false';
option = maybeOption;
}
}
if (option === null) {
// Set it to true if it's a boolean and the next argument doesn't match true/false.
const maybeOption = _getOptionFromName(key, options);
if (maybeOption) {
value = nextArg;
let shouldShift = true;
if (value && value.startsWith('-') && _coerce(undefined, maybeOption) !== undefined) {
// Verify if not having a value results in a correct parse, if so don't shift.
shouldShift = false;
}
// Only absorb it if it leads to a better value.
if (shouldShift && _coerce(value, maybeOption) !== undefined) {
consumedNextArg = true;
}
else {
value = '';
}
option = maybeOption;
}
}
}
else {
key = arg.substring(0, i);
option = _getOptionFromName(_removeLeadingDashes(key), options) || null;
if (option) {
value = arg.substring(i + 1);
}
}
if (option === null) {
if (nextArg && !nextArg.startsWith('-')) {
leftovers.push(arg, nextArg);
consumedNextArg = true;
}
else {
leftovers.push(arg);
}
}
else {
const v = _coerce(value, option, parsedOptions[option.name]);
if (v !== undefined) {
if (parsedOptions[option.name] !== v) {
if (parsedOptions[option.name] !== undefined && option.type !== interface_1.OptionType.Array) {
warnings.push(`Option ${JSON.stringify(option.name)} was already specified with value ` +
`${JSON.stringify(parsedOptions[option.name])}. The new value ${JSON.stringify(v)} ` +
`will override it.`);
}
parsedOptions[option.name] = v;
}
}
else {
let error = `Argument ${key} could not be parsed using value ${JSON.stringify(value)}.`;
if (option.enum) {
error += ` Valid values are: ${option.enum.map((x) => JSON.stringify(x)).join(', ')}.`;
}
else {
error += `Valid type(s) is: ${(option.types || [option.type]).join(', ')}`;
}
errors.push(error);
ignored.push(arg);
}
if (/^[a-z]+[A-Z]/.test(key)) {
warnings.push('Support for camel case arguments has been deprecated and will be removed in a future major version.\n' +
`Use '--${core_1.strings.dasherize(key)}' instead of '--${key}'.`);
}
}
return consumedNextArg;
}
/**
* Parse the arguments in a consistent way, but without having any option definition. This tries
* to assess what the user wants in a free form. For example, using `--name=false` will set the
* name properties to a boolean type.
* This should only be used when there's no schema available or if a schema is "true" (anything is
* valid).
*
* @param args Argument list to parse.
* @returns An object that contains a property per flags from the args.
*/
function parseFreeFormArguments(args) {
const parsedOptions = {};
const leftovers = [];
for (let arg = args.shift(); arg !== undefined; arg = args.shift()) {
if (arg == '--') {
leftovers.push(...args);
break;
}
if (arg.startsWith('--')) {
const eqSign = arg.indexOf('=');
let name;
let value;
if (eqSign !== -1) {
name = arg.substring(2, eqSign);
value = arg.substring(eqSign + 1);
}
else {
name = arg.substr(2);
value = args.shift();
}
const v = _coerce(value, null, parsedOptions[name]);
if (v !== undefined) {
parsedOptions[name] = v;
}
}
else if (arg.startsWith('-')) {
arg.split('').forEach((x) => (parsedOptions[x] = true));
}
else {
leftovers.push(arg);
}
}
if (leftovers.length) {
parsedOptions['--'] = leftovers;
}
return parsedOptions;
}
exports.parseFreeFormArguments = parseFreeFormArguments;
/**
* Parse the arguments in a consistent way, from a list of standardized options.
* The result object will have a key per option name, with the `_` key reserved for positional
* arguments, and `--` will contain everything that did not match. Any key that don't have an
* option will be pushed back in `--` and removed from the object. If you need to validate that
* there's no additionalProperties, you need to check the `--` key.
*
* @param args The argument array to parse.
* @param options List of supported options. {@see Option}.
* @param logger Logger to use to warn users.
* @returns An object that contains a property per option.
*/
function parseArguments(args, options, logger) {
if (options === null) {
options = [];
}
const leftovers = [];
const positionals = [];
const parsedOptions = {};
const ignored = [];
const errors = [];
const warnings = [];
const state = { options, parsedOptions, positionals, leftovers, ignored, errors, warnings };
for (let argIndex = 0; argIndex < args.length; argIndex++) {
const arg = args[argIndex];
let consumedNextArg = false;
if (arg == '--') {
// If we find a --, we're done.
leftovers.push(...args.slice(argIndex + 1));
break;
}
if (arg.startsWith('--')) {
consumedNextArg = _assignOption(arg, args[argIndex + 1], state);
}
else if (arg.startsWith('-')) {
// Argument is of form -abcdef. Starts at 1 because we skip the `-`.
for (let i = 1; i < arg.length; i++) {
const flag = arg[i];
// If the next character is an '=', treat it as a long flag.
if (arg[i + 1] == '=') {
const f = '-' + flag + arg.slice(i + 1);
consumedNextArg = _assignOption(f, args[argIndex + 1], state);
break;
}
// Treat the last flag as `--a` (as if full flag but just one letter). We do this in
// the loop because it saves us a check to see if the arg is just `-`.
if (i == arg.length - 1) {
const arg = '-' + flag;
consumedNextArg = _assignOption(arg, args[argIndex + 1], state);
}
else {
const maybeOption = _getOptionFromName(flag, options);
if (maybeOption) {
const v = _coerce(undefined, maybeOption, parsedOptions[maybeOption.name]);
if (v !== undefined) {
parsedOptions[maybeOption.name] = v;
}
}
}
}
}
else {
positionals.push(arg);
}
if (consumedNextArg) {
argIndex++;
}
}
// Deal with positionals.
// TODO(hansl): this is by far the most complex piece of code in this file. Try to refactor it
// simpler.
if (positionals.length > 0) {
let pos = 0;
for (let i = 0; i < positionals.length;) {
let found = false;
let incrementPos = false;
let incrementI = true;
// We do this with a found flag because more than 1 option could have the same positional.
for (const option of options) {
// If any option has this positional and no value, AND fit the type, we need to remove it.
if (option.positional === pos) {
const coercedValue = _coerce(positionals[i], option, parsedOptions[option.name]);
if (parsedOptions[option.name] === undefined && coercedValue !== undefined) {
parsedOptions[option.name] = coercedValue;
found = true;
}
else {
incrementI = false;
}
incrementPos = true;
}
}
if (found) {
positionals.splice(i--, 1);
}
if (incrementPos) {
pos++;
}
if (incrementI) {
i++;
}
}
}
if (positionals.length > 0 || leftovers.length > 0) {
parsedOptions['--'] = [...positionals, ...leftovers];
}
if (warnings.length > 0 && logger) {
warnings.forEach((message) => logger.warn(message));
}
if (errors.length > 0) {
throw new ParseArgumentException(errors, parsedOptions, ignored);
}
return parsedOptions;
}
exports.parseArguments = parseArguments;

55
node_modules/@angular/cli/models/schematic-command.d.ts generated vendored Executable file
View file

@ -0,0 +1,55 @@
/**
* @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
*/
import { logging } from '@angular-devkit/core';
import { workflow } from '@angular-devkit/schematics';
import { FileSystemCollection, FileSystemEngine, FileSystemSchematic, NodeWorkflow } from '@angular-devkit/schematics/tools';
import { BaseCommandOptions, Command } from './command';
import { Arguments, CommandContext, CommandDescription, Option } from './interface';
export interface BaseSchematicSchema {
debug?: boolean;
dryRun?: boolean;
force?: boolean;
interactive?: boolean;
defaults?: boolean;
packageRegistry?: string;
}
export interface RunSchematicOptions extends BaseSchematicSchema {
collectionName: string;
schematicName: string;
additionalOptions?: {
[key: string]: {};
};
schematicOptions?: string[];
showNothingDone?: boolean;
}
export declare class UnknownCollectionError extends Error {
constructor(collectionName: string);
}
export declare abstract class SchematicCommand<T extends BaseSchematicSchema & BaseCommandOptions> extends Command<T> {
protected readonly allowPrivateSchematics: boolean;
protected readonly useReportAnalytics = false;
protected _workflow: NodeWorkflow;
protected defaultCollectionName: string;
protected collectionName: string;
protected schematicName?: string;
constructor(context: CommandContext, description: CommandDescription, logger: logging.Logger);
initialize(options: T & Arguments): Promise<void>;
printHelp(): Promise<number>;
printHelpUsage(): Promise<void>;
protected getEngine(): FileSystemEngine;
protected getCollection(collectionName: string): FileSystemCollection;
protected getSchematic(collection: FileSystemCollection, schematicName: string, allowPrivate?: boolean): FileSystemSchematic;
protected setPathOptions(options: Option[], workingDir: string): {
[name: string]: string;
};
protected createWorkflow(options: BaseSchematicSchema): Promise<workflow.BaseWorkflow>;
protected getDefaultSchematicCollection(): Promise<string>;
protected runSchematic(options: RunSchematicOptions): Promise<number | void>;
protected parseFreeFormArguments(schematicOptions: string[]): Promise<Arguments>;
protected parseArguments(schematicOptions: string[], options: Option[] | null): Promise<Arguments>;
}

485
node_modules/@angular/cli/models/schematic-command.js generated vendored Executable file
View file

@ -0,0 +1,485 @@
"use strict";
/**
* @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
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SchematicCommand = exports.UnknownCollectionError = void 0;
const core_1 = require("@angular-devkit/core");
const schematics_1 = require("@angular-devkit/schematics");
const tools_1 = require("@angular-devkit/schematics/tools");
const inquirer = __importStar(require("inquirer"));
const systemPath = __importStar(require("path"));
const color_1 = require("../utilities/color");
const config_1 = require("../utilities/config");
const json_schema_1 = require("../utilities/json-schema");
const package_manager_1 = require("../utilities/package-manager");
const tty_1 = require("../utilities/tty");
const analytics_1 = require("./analytics");
const command_1 = require("./command");
const parser_1 = require("./parser");
const schematic_engine_host_1 = require("./schematic-engine-host");
class UnknownCollectionError extends Error {
constructor(collectionName) {
super(`Invalid collection (${collectionName}).`);
}
}
exports.UnknownCollectionError = UnknownCollectionError;
class SchematicCommand extends command_1.Command {
constructor(context, description, logger) {
super(context, description, logger);
this.allowPrivateSchematics = false;
this.useReportAnalytics = false;
this.defaultCollectionName = '@schematics/angular';
this.collectionName = this.defaultCollectionName;
}
async initialize(options) {
await this.createWorkflow(options);
if (this.schematicName) {
// Set the options.
const collection = this.getCollection(this.collectionName);
const schematic = this.getSchematic(collection, this.schematicName, true);
const options = await json_schema_1.parseJsonSchemaToOptions(this._workflow.registry, schematic.description.schemaJson || {});
this.description.description = schematic.description.description;
this.description.options.push(...options.filter((x) => !x.hidden));
// Remove any user analytics from schematics that are NOT part of our safelist.
for (const o of this.description.options) {
if (o.userAnalytics && !analytics_1.isPackageNameSafeForAnalytics(this.collectionName)) {
o.userAnalytics = undefined;
}
}
}
}
async printHelp() {
await super.printHelp();
this.logger.info('');
const subCommandOption = this.description.options.filter((x) => x.subcommands)[0];
if (!subCommandOption || !subCommandOption.subcommands) {
return 0;
}
const schematicNames = Object.keys(subCommandOption.subcommands);
if (schematicNames.length > 1) {
this.logger.info('Available Schematics:');
const namesPerCollection = {};
schematicNames.forEach((name) => {
let [collectionName, schematicName] = name.split(/:/, 2);
if (!schematicName) {
schematicName = collectionName;
collectionName = this.collectionName;
}
if (!namesPerCollection[collectionName]) {
namesPerCollection[collectionName] = [];
}
namesPerCollection[collectionName].push(schematicName);
});
const defaultCollection = await this.getDefaultSchematicCollection();
Object.keys(namesPerCollection).forEach((collectionName) => {
const isDefault = defaultCollection == collectionName;
this.logger.info(` Collection "${collectionName}"${isDefault ? ' (default)' : ''}:`);
namesPerCollection[collectionName].forEach((schematicName) => {
this.logger.info(` ${schematicName}`);
});
});
}
return 0;
}
async printHelpUsage() {
const subCommandOption = this.description.options.filter((x) => x.subcommands)[0];
if (!subCommandOption || !subCommandOption.subcommands) {
return;
}
const schematicNames = Object.keys(subCommandOption.subcommands);
if (schematicNames.length == 1) {
this.logger.info(this.description.description);
const opts = this.description.options.filter((x) => x.positional === undefined);
const [collectionName, schematicName] = schematicNames[0].split(/:/)[0];
// Display <collectionName:schematicName> if this is not the default collectionName,
// otherwise just show the schematicName.
const displayName = collectionName == (await this.getDefaultSchematicCollection())
? schematicName
: schematicNames[0];
const schematicOptions = subCommandOption.subcommands[schematicNames[0]].options;
const schematicArgs = schematicOptions.filter((x) => x.positional !== undefined);
const argDisplay = schematicArgs.length > 0
? ' ' + schematicArgs.map((a) => `<${core_1.strings.dasherize(a.name)}>`).join(' ')
: '';
this.logger.info(core_1.tags.oneLine `
usage: ng ${this.description.name} ${displayName}${argDisplay}
${opts.length > 0 ? `[options]` : ``}
`);
this.logger.info('');
}
else {
await super.printHelpUsage();
}
}
getEngine() {
return this._workflow.engine;
}
getCollection(collectionName) {
const engine = this.getEngine();
const collection = engine.createCollection(collectionName);
if (collection === null) {
throw new UnknownCollectionError(collectionName);
}
return collection;
}
getSchematic(collection, schematicName, allowPrivate) {
return collection.createSchematic(schematicName, allowPrivate);
}
setPathOptions(options, workingDir) {
if (workingDir === '') {
return {};
}
return options
.filter((o) => o.format === 'path')
.map((o) => o.name)
.reduce((acc, curr) => {
acc[curr] = workingDir;
return acc;
}, {});
}
/*
* Runtime hook to allow specifying customized workflow
*/
async createWorkflow(options) {
if (this._workflow) {
return this._workflow;
}
const { force, dryRun } = options;
const root = this.context.root;
const workflow = new tools_1.NodeWorkflow(root, {
force,
dryRun,
packageManager: await package_manager_1.getPackageManager(root),
packageRegistry: options.packageRegistry,
// A schema registry is required to allow customizing addUndefinedDefaults
registry: new core_1.schema.CoreSchemaRegistry(schematics_1.formats.standardFormats),
resolvePaths: this.workspace
? // Workspace
this.collectionName === this.defaultCollectionName
? // Favor __dirname for @schematics/angular to use the build-in version
[__dirname, process.cwd(), root]
: [process.cwd(), root, __dirname]
: // Global
[__dirname, process.cwd()],
schemaValidation: true,
optionTransforms: [
// Add configuration file defaults
async (schematic, current) => {
const projectName = typeof current.project === 'string'
? current.project
: getProjectName();
return {
...(await config_1.getSchematicDefaults(schematic.collection.name, schematic.name, projectName)),
...current,
};
},
],
engineHostCreator: (options) => new schematic_engine_host_1.SchematicEngineHost(options.resolvePaths),
});
const getProjectName = () => {
if (this.workspace) {
const projectNames = getProjectsByPath(this.workspace, process.cwd(), this.workspace.basePath);
if (projectNames.length === 1) {
return projectNames[0];
}
else {
if (projectNames.length > 1) {
this.logger.warn(core_1.tags.oneLine `
Two or more projects are using identical roots.
Unable to determine project using current working directory.
Using default workspace project instead.
`);
}
const defaultProjectName = this.workspace.extensions['defaultProject'];
if (typeof defaultProjectName === 'string' && defaultProjectName) {
return defaultProjectName;
}
}
}
return undefined;
};
workflow.registry.addPostTransform(core_1.schema.transforms.addUndefinedDefaults);
workflow.registry.addSmartDefaultProvider('projectName', getProjectName);
workflow.registry.useXDeprecatedProvider((msg) => this.logger.warn(msg));
let shouldReportAnalytics = true;
workflow.engineHost.registerOptionsTransform(async (_, options) => {
if (shouldReportAnalytics) {
shouldReportAnalytics = false;
await this.reportAnalytics([this.description.name], options);
}
return options;
});
if (options.interactive !== false && tty_1.isTTY()) {
workflow.registry.usePromptProvider((definitions) => {
const questions = definitions
.filter((definition) => !options.defaults || definition.default === undefined)
.map((definition) => {
var _a;
const question = {
name: definition.id,
message: definition.message,
default: definition.default,
};
const validator = definition.validator;
if (validator) {
question.validate = (input) => validator(input);
// Filter allows transformation of the value prior to validation
question.filter = async (input) => {
for (const type of definition.propertyTypes) {
let value;
switch (type) {
case 'string':
value = String(input);
break;
case 'integer':
case 'number':
value = Number(input);
break;
default:
value = input;
break;
}
// Can be a string if validation fails
const isValid = (await validator(value)) === true;
if (isValid) {
return value;
}
}
return input;
};
}
switch (definition.type) {
case 'confirmation':
question.type = 'confirm';
break;
case 'list':
question.type = definition.multiselect ? 'checkbox' : 'list';
question.choices = (_a = definition.items) === null || _a === void 0 ? void 0 : _a.map((item) => {
return typeof item == 'string'
? item
: {
name: item.label,
value: item.value,
};
});
break;
default:
question.type = definition.type;
break;
}
return question;
});
return inquirer.prompt(questions);
});
}
return (this._workflow = workflow);
}
async getDefaultSchematicCollection() {
let workspace = await config_1.getWorkspace('local');
if (workspace) {
const project = config_1.getProjectByCwd(workspace);
if (project && workspace.getProjectCli(project)) {
const value = workspace.getProjectCli(project)['defaultCollection'];
if (typeof value == 'string') {
return value;
}
}
if (workspace.getCli()) {
const value = workspace.getCli()['defaultCollection'];
if (typeof value == 'string') {
return value;
}
}
}
workspace = await config_1.getWorkspace('global');
if (workspace && workspace.getCli()) {
const value = workspace.getCli()['defaultCollection'];
if (typeof value == 'string') {
return value;
}
}
return this.defaultCollectionName;
}
async runSchematic(options) {
const { schematicOptions, debug, dryRun } = options;
let { collectionName, schematicName } = options;
let nothingDone = true;
let loggingQueue = [];
let error = false;
const workflow = this._workflow;
const workingDir = core_1.normalize(systemPath.relative(this.context.root, process.cwd()));
// Get the option object from the schematic schema.
const schematic = this.getSchematic(this.getCollection(collectionName), schematicName, this.allowPrivateSchematics);
// Update the schematic and collection name in case they're not the same as the ones we
// received in our options, e.g. after alias resolution or extension.
collectionName = schematic.collection.description.name;
schematicName = schematic.description.name;
// Set the options of format "path".
let o = null;
let args;
if (!schematic.description.schemaJson) {
args = await this.parseFreeFormArguments(schematicOptions || []);
}
else {
o = await json_schema_1.parseJsonSchemaToOptions(workflow.registry, schematic.description.schemaJson);
args = await this.parseArguments(schematicOptions || [], o);
}
const allowAdditionalProperties = typeof schematic.description.schemaJson === 'object' &&
schematic.description.schemaJson.additionalProperties;
if (args['--'] && !allowAdditionalProperties) {
args['--'].forEach((additional) => {
this.logger.fatal(`Unknown option: '${additional.split(/=/)[0]}'`);
});
return 1;
}
const pathOptions = o ? this.setPathOptions(o, workingDir) : {};
const input = {
...pathOptions,
...args,
...options.additionalOptions,
};
workflow.reporter.subscribe((event) => {
nothingDone = false;
// Strip leading slash to prevent confusion.
const eventPath = event.path.startsWith('/') ? event.path.substr(1) : event.path;
switch (event.kind) {
case 'error':
error = true;
const desc = event.description == 'alreadyExist' ? 'already exists' : 'does not exist.';
this.logger.warn(`ERROR! ${eventPath} ${desc}.`);
break;
case 'update':
loggingQueue.push(core_1.tags.oneLine `
${color_1.colors.cyan('UPDATE')} ${eventPath} (${event.content.length} bytes)
`);
break;
case 'create':
loggingQueue.push(core_1.tags.oneLine `
${color_1.colors.green('CREATE')} ${eventPath} (${event.content.length} bytes)
`);
break;
case 'delete':
loggingQueue.push(`${color_1.colors.yellow('DELETE')} ${eventPath}`);
break;
case 'rename':
const eventToPath = event.to.startsWith('/') ? event.to.substr(1) : event.to;
loggingQueue.push(`${color_1.colors.blue('RENAME')} ${eventPath} => ${eventToPath}`);
break;
}
});
workflow.lifeCycle.subscribe((event) => {
if (event.kind == 'end' || event.kind == 'post-tasks-start') {
if (!error) {
// Output the logging queue, no error happened.
loggingQueue.forEach((log) => this.logger.info(log));
}
loggingQueue = [];
error = false;
}
});
// Temporary compatibility check for NPM 7
if (collectionName === '@schematics/angular' && schematicName === 'ng-new') {
if (!input.skipInstall &&
(input.packageManager === undefined || input.packageManager === 'npm')) {
await package_manager_1.ensureCompatibleNpm(this.context.root);
}
}
return new Promise((resolve) => {
workflow
.execute({
collection: collectionName,
schematic: schematicName,
options: input,
debug: debug,
logger: this.logger,
allowPrivate: this.allowPrivateSchematics,
})
.subscribe({
error: (err) => {
// In case the workflow was not successful, show an appropriate error message.
if (err instanceof schematics_1.UnsuccessfulWorkflowExecution) {
// "See above" because we already printed the error.
this.logger.fatal('The Schematic workflow failed. See above.');
}
else if (debug) {
this.logger.fatal(`An error occurred:\n${err.message}\n${err.stack}`);
}
else {
this.logger.fatal(err.message);
}
resolve(1);
},
complete: () => {
const showNothingDone = !(options.showNothingDone === false);
if (nothingDone && showNothingDone) {
this.logger.info('Nothing to be done.');
}
if (dryRun) {
this.logger.warn(`\nNOTE: The "dryRun" flag means no changes were made.`);
}
resolve();
},
});
});
}
async parseFreeFormArguments(schematicOptions) {
return parser_1.parseFreeFormArguments(schematicOptions);
}
async parseArguments(schematicOptions, options) {
return parser_1.parseArguments(schematicOptions, options, this.logger);
}
}
exports.SchematicCommand = SchematicCommand;
function getProjectsByPath(workspace, path, root) {
if (workspace.projects.size === 1) {
return Array.from(workspace.projects.keys());
}
const isInside = (base, potential) => {
const absoluteBase = systemPath.resolve(root, base);
const absolutePotential = systemPath.resolve(root, potential);
const relativePotential = systemPath.relative(absoluteBase, absolutePotential);
if (!relativePotential.startsWith('..') && !systemPath.isAbsolute(relativePotential)) {
return true;
}
return false;
};
const projects = Array.from(workspace.projects.entries())
.map(([name, project]) => [systemPath.resolve(root, project.root), name])
.filter((tuple) => isInside(tuple[0], path))
// Sort tuples by depth, with the deeper ones first. Since the first member is a path and
// we filtered all invalid paths, the longest will be the deepest (and in case of equality
// the sort is stable and the first declared project will win).
.sort((a, b) => b[0].length - a[0].length);
if (projects.length === 1) {
return [projects[0][1]];
}
else if (projects.length > 1) {
const firstPath = projects[0][0];
return projects.filter((v) => v[0] === firstPath).map((v) => v[1]);
}
return [];
}

15
node_modules/@angular/cli/models/schematic-engine-host.d.ts generated vendored Executable file
View file

@ -0,0 +1,15 @@
/**
* @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
*/
import { RuleFactory } from '@angular-devkit/schematics';
import { NodeModulesEngineHost } from '@angular-devkit/schematics/tools';
export declare class SchematicEngineHost extends NodeModulesEngineHost {
protected _resolveReferenceString(refString: string, parentPath: string): {
ref: RuleFactory<{}>;
path: string;
} | null;
}

159
node_modules/@angular/cli/models/schematic-engine-host.js generated vendored Executable file
View file

@ -0,0 +1,159 @@
"use strict";
/**
* @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
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SchematicEngineHost = void 0;
const schematics_1 = require("@angular-devkit/schematics");
const tools_1 = require("@angular-devkit/schematics/tools");
const fs_1 = require("fs");
const jsonc_parser_1 = require("jsonc-parser");
const module_1 = __importDefault(require("module"));
const path_1 = require("path");
const vm_1 = require("vm");
/**
* Environment variable to control schematic package redirection
* Default: Angular schematics only
*/
const schematicRedirectVariable = (_a = process.env['NG_SCHEMATIC_REDIRECT']) === null || _a === void 0 ? void 0 : _a.toLowerCase();
function shouldWrapSchematic(schematicFile) {
// Check environment variable if present
if (schematicRedirectVariable !== undefined) {
switch (schematicRedirectVariable) {
case '0':
case 'false':
case 'off':
case 'none':
return false;
case 'all':
return true;
}
}
const normalizedSchematicFile = schematicFile.replace(/\\/g, '/');
// Never wrap the internal update schematic when executed directly
// It communicates with the update command via `global`
// But we still want to redirect schematics located in `@angular/cli/node_modules`.
if (normalizedSchematicFile.includes('node_modules/@angular/cli/') &&
!normalizedSchematicFile.includes('node_modules/@angular/cli/node_modules/')) {
return false;
}
// Default is only first-party Angular schematic packages
// Angular schematics are safe to use in the wrapped VM context
return /\/node_modules\/@(?:angular|schematics|nguniversal)\//.test(normalizedSchematicFile);
}
class SchematicEngineHost extends tools_1.NodeModulesEngineHost {
_resolveReferenceString(refString, parentPath) {
const [path, name] = refString.split('#', 2);
// Mimic behavior of ExportStringRef class used in default behavior
const fullPath = path[0] === '.' ? path_1.resolve(parentPath !== null && parentPath !== void 0 ? parentPath : process.cwd(), path) : path;
const schematicFile = require.resolve(fullPath, { paths: [parentPath] });
if (shouldWrapSchematic(schematicFile)) {
const schematicPath = path_1.dirname(schematicFile);
const moduleCache = new Map();
const factoryInitializer = wrap(schematicFile, schematicPath, moduleCache, name || 'default');
const factory = factoryInitializer();
if (!factory || typeof factory !== 'function') {
return null;
}
return { ref: factory, path: schematicPath };
}
// All other schematics use default behavior
return super._resolveReferenceString(refString, parentPath);
}
}
exports.SchematicEngineHost = SchematicEngineHost;
/**
* Minimal shim modules for legacy deep imports of `@schematics/angular`
*/
const legacyModules = {
'@schematics/angular/utility/config': {
getWorkspace(host) {
const path = '/.angular.json';
const data = host.read(path);
if (!data) {
throw new schematics_1.SchematicsException(`Could not find (${path})`);
}
return jsonc_parser_1.parse(data.toString(), [], { allowTrailingComma: true });
},
},
'@schematics/angular/utility/project': {
buildDefaultPath(project) {
const root = project.sourceRoot ? `/${project.sourceRoot}/` : `/${project.root}/src/`;
return `${root}${project.projectType === 'application' ? 'app' : 'lib'}`;
},
},
};
/**
* Wrap a JavaScript file in a VM context to allow specific Angular dependencies to be redirected.
* This VM setup is ONLY intended to redirect dependencies.
*
* @param schematicFile A JavaScript schematic file path that should be wrapped.
* @param schematicDirectory A directory that will be used as the location of the JavaScript file.
* @param moduleCache A map to use for caching repeat module usage and proper `instanceof` support.
* @param exportName An optional name of a specific export to return. Otherwise, return all exports.
*/
function wrap(schematicFile, schematicDirectory, moduleCache, exportName) {
const scopedRequire = module_1.default.createRequire(schematicFile);
const customRequire = function (id) {
if (legacyModules[id]) {
// Provide compatibility modules for older versions of @angular/cdk
return legacyModules[id];
}
else if (id.startsWith('@angular-devkit/') || id.startsWith('@schematics/')) {
// Resolve from inside the `@angular/cli` project
const packagePath = require.resolve(id);
return require(packagePath);
}
else if (id.startsWith('.') || id.startsWith('@angular/cdk')) {
// Wrap relative files inside the schematic collection
// Also wrap `@angular/cdk`, it contains helper utilities that import core schematic packages
// Resolve from the original file
const modulePath = scopedRequire.resolve(id);
// Use cached module if available
const cachedModule = moduleCache.get(modulePath);
if (cachedModule) {
return cachedModule;
}
// Do not wrap vendored third-party packages or JSON files
if (!/[\/\\]node_modules[\/\\]@schematics[\/\\]angular[\/\\]third_party[\/\\]/.test(modulePath) &&
!modulePath.endsWith('.json')) {
// Wrap module and save in cache
const wrappedModule = wrap(modulePath, path_1.dirname(modulePath), moduleCache)();
moduleCache.set(modulePath, wrappedModule);
return wrappedModule;
}
}
// All others are required directly from the original file
return scopedRequire(id);
};
// Setup a wrapper function to capture the module's exports
const schematicCode = fs_1.readFileSync(schematicFile, 'utf8');
// `module` is required due to @angular/localize ng-add being in UMD format
const headerCode = '(function() {\nvar exports = {};\nvar module = { exports };\n';
const footerCode = exportName ? `\nreturn exports['${exportName}'];});` : '\nreturn exports;});';
const script = new vm_1.Script(headerCode + schematicCode + footerCode, {
filename: schematicFile,
lineOffset: 3,
});
const context = {
__dirname: schematicDirectory,
__filename: schematicFile,
Buffer,
console,
process,
get global() {
return this;
},
require: customRequire,
};
const exportsFactory = script.runInNewContext(context);
return exportsFactory;
}

15
node_modules/@angular/cli/models/version.d.ts generated vendored Executable file
View file

@ -0,0 +1,15 @@
/**
* @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
*/
export declare class Version {
readonly full: string;
readonly major: string;
readonly minor: string;
readonly patch: string;
constructor(full: string);
}
export declare const VERSION: Version;

21
node_modules/@angular/cli/models/version.js generated vendored Executable file
View file

@ -0,0 +1,21 @@
"use strict";
/**
* @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
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.VERSION = exports.Version = void 0;
// Same structure as used in framework packages
class Version {
constructor(full) {
this.full = full;
this.major = full.split('.')[0];
this.minor = full.split('.')[1];
this.patch = full.split('.').slice(2).join('.');
}
}
exports.Version = Version;
exports.VERSION = new Version(require('../package.json').version);