From 5253ecb2211d4ebd19e3728f75767e7d34893bde Mon Sep 17 00:00:00 2001 From: Chris Roberson Date: Mon, 26 Nov 2018 08:34:39 -0500 Subject: [PATCH 01/85] [Monitoring] Cluster alerts table to EUI (#26031) * Convert cluster alerts page to use EUI tables. Also adds baseline support for all monitoring tables * Fix tests * Remove these two files * Keep the original table but offer a new one so existing UIs still work * Use different base table controller for the EUI table * Use EUI specific asc and desc constants --- x-pack/plugins/monitoring/common/constants.js | 2 + .../public/components/alerts/alerts.js | 126 +++++++++++++ .../public/components/alerts/index.js | 7 + .../public/components/table/eui_table.js | 43 +++++ .../public/components/table/index.js | 3 +- .../public/components/table/storage.js | 23 +++ .../public/directives/alerts/index.js | 173 ------------------ .../monitoring/public/directives/all.js | 1 - .../monitoring/public/views/alerts/index.html | 5 +- .../monitoring/public/views/alerts/index.js | 45 ++++- .../public/views/base_eui_table_controller.js | 66 +++++++ .../public/views/base_table_controller.js | 1 - .../views/elasticsearch/ccr/shard/index.js | 4 +- .../lib/logstash/get_logstash_for_clusters.js | 1 + .../page_objects/monitoring_page.js | 6 + .../services/monitoring/cluster_alerts.js | 7 +- 16 files changed, 328 insertions(+), 185 deletions(-) create mode 100644 x-pack/plugins/monitoring/public/components/alerts/alerts.js create mode 100644 x-pack/plugins/monitoring/public/components/alerts/index.js create mode 100644 x-pack/plugins/monitoring/public/components/table/eui_table.js delete mode 100644 x-pack/plugins/monitoring/public/directives/alerts/index.js create mode 100644 x-pack/plugins/monitoring/public/views/base_eui_table_controller.js diff --git a/x-pack/plugins/monitoring/common/constants.js b/x-pack/plugins/monitoring/common/constants.js index 852afe74c461e..c391f243eaff6 100644 --- a/x-pack/plugins/monitoring/common/constants.js +++ b/x-pack/plugins/monitoring/common/constants.js @@ -51,6 +51,8 @@ export const NORMALIZED_DERIVATIVE_UNIT = '1s'; * Values for column sorting in table options * @type {number} 1 or -1 */ +export const EUI_SORT_ASCENDING = 'asc'; +export const EUI_SORT_DESCENDING = 'desc'; export const SORT_ASCENDING = 1; export const SORT_DESCENDING = -1; diff --git a/x-pack/plugins/monitoring/public/components/alerts/alerts.js b/x-pack/plugins/monitoring/public/components/alerts/alerts.js new file mode 100644 index 0000000000000..089ca454d584e --- /dev/null +++ b/x-pack/plugins/monitoring/public/components/alerts/alerts.js @@ -0,0 +1,126 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { capitalize } from 'lodash'; +import { formatDateTimeLocal } from '../../../common/formatting'; +import { formatTimestampToDuration } from '../../../common'; +import { CALCULATE_DURATION_SINCE, EUI_SORT_DESCENDING } from '../../../common/constants'; +import { mapSeverity } from './map_severity'; +import { Tooltip } from 'plugins/monitoring/components/tooltip'; +import { FormattedAlert } from 'plugins/monitoring/components/alerts/formatted_alert'; +import { EuiMonitoringTable } from 'plugins/monitoring/components/table'; +import { EuiHealth, EuiIcon } from '@elastic/eui'; + +const linkToCategories = { + 'elasticsearch/nodes': 'Elasticsearch Nodes', + 'elasticsearch/indices': 'Elasticsearch Indices', + 'kibana/instances': 'Kibana Instances', + 'logstash/instances': 'Logstash Nodes', +}; +const getColumns = (kbnUrl, scope) => ([ + { + name: 'Status', + field: 'metadata.severity', + sortable: true, + render: severity => { + const severityIcon = mapSeverity(severity); + + return ( + + + { capitalize(severityIcon.value) } + + + ); + } + }, + { + name: 'Resolved', + field: 'resolved_timestamp', + sortable: true, + render: (resolvedTimestamp) => { + const resolution = { + icon: null, + text: 'Not Resolved' + }; + + if (resolvedTimestamp) { + resolution.text = `${formatTimestampToDuration(resolvedTimestamp, CALCULATE_DURATION_SINCE)} ago`; + } else { + resolution.icon = ; + } + + return ( + + { resolution.icon } { resolution.text } + + ); + }, + }, + { + name: 'Message', + field: 'message', + sortable: true, + render: (message, alert) => ( + { + scope.$evalAsync(() => { + kbnUrl.changePath(target); + }); + }} + /> + ) + }, + { + name: 'Category', + field: 'metadata.link', + sortable: true, + render: link => linkToCategories[link] ? linkToCategories[link] : 'General' + }, + { + name: 'Last Checked', + field: 'update_timestamp', + sortable: true, + render: timestamp => formatDateTimeLocal(timestamp) + }, + { + name: 'Triggered', + field: 'timestamp', + sortable: true, + render: timestamp => formatTimestampToDuration(timestamp, CALCULATE_DURATION_SINCE) + ' ago' + }, +]); + +export const Alerts = ({ alerts, angular, sorting, pagination, onTableChange }) => { + return ( + + ); +}; diff --git a/x-pack/plugins/monitoring/public/components/alerts/index.js b/x-pack/plugins/monitoring/public/components/alerts/index.js new file mode 100644 index 0000000000000..c4eda37c2b252 --- /dev/null +++ b/x-pack/plugins/monitoring/public/components/alerts/index.js @@ -0,0 +1,7 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export { Alerts } from './alerts'; diff --git a/x-pack/plugins/monitoring/public/components/table/eui_table.js b/x-pack/plugins/monitoring/public/components/table/eui_table.js new file mode 100644 index 0000000000000..2cc7154a85c9a --- /dev/null +++ b/x-pack/plugins/monitoring/public/components/table/eui_table.js @@ -0,0 +1,43 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { + EuiInMemoryTable +} from '@elastic/eui'; + +export class EuiMonitoringTable extends React.PureComponent { + render() { + const { + rows: items, + search = {}, + columns: _columns, + ...props + } = this.props; + + if (search.box && !search.box['data-test-subj']) { + search.box['data-test-subj'] = 'monitoringTableToolBar'; + } + + const columns = _columns.map(column => { + if (!column['data-test-subj']) { + column['data-test-subj'] = 'monitoringTableHasData'; + } + return column; + }); + + return ( +
+ +
+ ); + } +} diff --git a/x-pack/plugins/monitoring/public/components/table/index.js b/x-pack/plugins/monitoring/public/components/table/index.js index 38b972c1b0245..85900144cd57f 100644 --- a/x-pack/plugins/monitoring/public/components/table/index.js +++ b/x-pack/plugins/monitoring/public/components/table/index.js @@ -5,4 +5,5 @@ */ export { MonitoringTable } from './table'; -export { tableStorageGetter, tableStorageSetter } from './storage'; +export { EuiMonitoringTable } from './eui_table'; +export { tableStorageGetter, tableStorageSetter, euiTableStorageGetter, euiTableStorageSetter } from './storage'; diff --git a/x-pack/plugins/monitoring/public/components/table/storage.js b/x-pack/plugins/monitoring/public/components/table/storage.js index 576dddbee8098..9ddb611331cd0 100644 --- a/x-pack/plugins/monitoring/public/components/table/storage.js +++ b/x-pack/plugins/monitoring/public/components/table/storage.js @@ -33,3 +33,26 @@ export const tableStorageSetter = keyPrefix => { return localStorageData; }; }; + +export const euiTableStorageGetter = keyPrefix => { + return storage => { + const localStorageData = storage.get(STORAGE_KEY) || {}; + const sort = get(localStorageData, [ keyPrefix, 'sort' ]); + const page = get(localStorageData, [ keyPrefix, 'page' ]); + + return { page, sort }; + }; +}; + +export const euiTableStorageSetter = keyPrefix => { + return (storage, { sort, page }) => { + const localStorageData = storage.get(STORAGE_KEY) || {}; + + set(localStorageData, [ keyPrefix, 'sort' ], sort || undefined); // don`t store empty data + set(localStorageData, [ keyPrefix, 'page' ], page || undefined); + + storage.set(STORAGE_KEY, localStorageData); + + return localStorageData; + }; +}; diff --git a/x-pack/plugins/monitoring/public/directives/alerts/index.js b/x-pack/plugins/monitoring/public/directives/alerts/index.js deleted file mode 100644 index d125b0f1c074b..0000000000000 --- a/x-pack/plugins/monitoring/public/directives/alerts/index.js +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { capitalize } from 'lodash'; -import React from 'react'; -import { render } from 'react-dom'; -import { EuiIcon, EuiHealth } from '@elastic/eui'; -import { uiModules } from 'ui/modules'; -import { KuiTableRowCell, KuiTableRow } from '@kbn/ui-framework/components'; -import { MonitoringTable } from 'plugins/monitoring/components/table'; -import { CALCULATE_DURATION_SINCE, SORT_DESCENDING } from '../../../common/constants'; -import { Tooltip } from 'plugins/monitoring/components/tooltip'; -import { FormattedAlert } from 'plugins/monitoring/components/alerts/formatted_alert'; -import { mapSeverity } from 'plugins/monitoring/components/alerts/map_severity'; -import { formatTimestampToDuration } from '../../../common/format_timestamp_to_duration'; -import { formatDateTimeLocal } from '../../../common/formatting'; -import { i18n } from '@kbn/i18n'; -import { injectI18n, I18nProvider, FormattedMessage } from '@kbn/i18n/react'; - -const linkToCategories = { - 'elasticsearch/nodes': i18n.translate('xpack.monitoring.alerts.esNodesCategoryLabel', { - defaultMessage: 'Elasticsearch Nodes', - }), - 'elasticsearch/indices': i18n.translate('xpack.monitoring.alerts.esIndicesCategoryLabel', { - defaultMessage: 'Elasticsearch Indices', - }), - 'kibana/instances': i18n.translate('xpack.monitoring.alerts.kibanaInstancesCategoryLabel', { - defaultMessage: 'Kibana Instances', - }), - 'logstash/instances': i18n.translate('xpack.monitoring.alerts.logstashNodesCategoryLabel', { - defaultMessage: 'Logstash Nodes', - }), -}; -const filterFields = [ 'message', 'severity_group', 'prefix', 'suffix', 'metadata.link', 'since', 'timestamp', 'update_timestamp' ]; -const columns = [ - { - title: i18n.translate('xpack.monitoring.alerts.statusColumnTitle', { - defaultMessage: 'Status', - }), - sortKey: 'metadata.severity', - sortOrder: SORT_DESCENDING - }, - { - title: i18n.translate('xpack.monitoring.alerts.resolvedColumnTitle', { - defaultMessage: 'Resolved', - }), - sortKey: 'resolved_timestamp' - }, - { - title: i18n.translate('xpack.monitoring.alerts.messageColumnTitle', { - defaultMessage: 'Message', - }), - sortKey: 'message' - }, - { - title: i18n.translate('xpack.monitoring.alerts.categoryColumnTitle', { - defaultMessage: 'Category', - }), - sortKey: 'metadata.link' - }, - { - title: i18n.translate('xpack.monitoring.alerts.lastCheckedColumnTitle', { - defaultMessage: 'Last Checked', - }), - sortKey: 'update_timestamp' - }, - { - title: i18n.translate('xpack.monitoring.alerts.triggeredColumnTitle', { - defaultMessage: 'Triggered', - }), - sortKey: 'timestamp' - }, -]; -const alertRowFactory = (scope, kbnUrl) => { - return injectI18n(props => { - const changeUrl = target => { - scope.$evalAsync(() => { - kbnUrl.changePath(target); - }); - }; - const severityIcon = mapSeverity(props.metadata.severity); - const resolution = { - icon: null, - text: props.intl.formatMessage({ id: 'xpack.monitoring.alerts.notResolvedDescription', - defaultMessage: 'Not Resolved', - }) - }; - - if (props.resolved_timestamp) { - resolution.text = props.intl.formatMessage({ id: 'xpack.monitoring.alerts.resolvedAgoDescription', - defaultMessage: '{duration} ago', - }, { duration: formatTimestampToDuration(props.resolved_timestamp, CALCULATE_DURATION_SINCE) } - ); - } else { - resolution.icon = ( - - ); - } - - return ( - - - - - { capitalize(severityIcon.value) } - - - - - { resolution.icon } { resolution.text } - - - - - - { linkToCategories[props.metadata.link] ? linkToCategories[props.metadata.link] : - props.intl.formatMessage({ id: 'xpack.monitoring.alerts.generalCategoryLabel', defaultMessage: 'General', }) } - - - { formatDateTimeLocal(props.update_timestamp) } - - - - - - ); - }); -}; - -const uiModule = uiModules.get('monitoring/directives', []); -uiModule.directive('monitoringClusterAlertsListing', (kbnUrl, i18n) => { - return { - restrict: 'E', - scope: { alerts: '=' }, - link(scope, $el) { - const filterAlertsPlaceholder = i18n('xpack.monitoring.alerts.filterAlertsPlaceholder', { defaultMessage: 'Filter Alerts…' }); - - scope.$watch('alerts', (alerts = []) => { - const alertsTable = ( - - - - ); - render(alertsTable, $el[0]); - }); - - } - }; -}); diff --git a/x-pack/plugins/monitoring/public/directives/all.js b/x-pack/plugins/monitoring/public/directives/all.js index 98b3a10237ba2..ad101f43a903d 100644 --- a/x-pack/plugins/monitoring/public/directives/all.js +++ b/x-pack/plugins/monitoring/public/directives/all.js @@ -7,7 +7,6 @@ import './main'; import './chart'; import './sparkline'; -import './alerts'; import './cluster/overview'; import './cluster/listing'; import './elasticsearch/cluster_status'; diff --git a/x-pack/plugins/monitoring/public/views/alerts/index.html b/x-pack/plugins/monitoring/public/views/alerts/index.html index 5ef9cc2b03473..ae92f9b6f8552 100644 --- a/x-pack/plugins/monitoring/public/views/alerts/index.html +++ b/x-pack/plugins/monitoring/public/views/alerts/index.html @@ -1,5 +1,6 @@ -
+
+ diff --git a/x-pack/plugins/monitoring/public/views/alerts/index.js b/x-pack/plugins/monitoring/public/views/alerts/index.js index 7b85d19bc8be0..ab8b57bff0723 100644 --- a/x-pack/plugins/monitoring/public/views/alerts/index.js +++ b/x-pack/plugins/monitoring/public/views/alerts/index.js @@ -4,13 +4,18 @@ * you may not use this file except in compliance with the Elastic License. */ +import React from 'react'; +import { render } from 'react-dom'; import { find, get } from 'lodash'; import uiRoutes from 'ui/routes'; import template from './index.html'; -import { MonitoringViewBaseController } from 'plugins/monitoring/views'; import { routeInitProvider } from 'plugins/monitoring/lib/route_init'; import { ajaxErrorHandlersProvider } from 'plugins/monitoring/lib/ajax_error_handler'; import { timefilter } from 'ui/timefilter'; +import { Alerts } from '../../components/alerts'; +import { MonitoringViewBaseEuiTableController } from '../base_eui_table_controller'; +import { I18nProvider, FormattedMessage } from '@kbn/i18n/react'; +import { EuiPage, EuiPageBody, EuiPageContent, EuiSpacer, EuiLink } from '@elastic/eui'; function getPageData($injector) { const globalState = $injector.get('globalState'); @@ -44,10 +49,11 @@ uiRoutes.when('/alerts', { alerts: getPageData }, controllerAs: 'alerts', - controller: class AlertsView extends MonitoringViewBaseController { + controller: class AlertsView extends MonitoringViewBaseEuiTableController { constructor($injector, $scope, i18n) { const $route = $injector.get('$route'); const globalState = $injector.get('globalState'); + const kbnUrl = $injector.get('kbnUrl'); // breadcrumbs + page title $scope.cluster = find($route.current.locals.clusters, { cluster_uuid: globalState.cluster_uuid }); @@ -60,6 +66,41 @@ uiRoutes.when('/alerts', { }); this.data = $route.current.locals.alerts; + + const renderReact = data => { + const app = data.message + ? (

{data.message}

) + : (); + + render( + + + + + {app} + + + + + + + + , + document.getElementById('monitoringAlertsApp') + ); + }; + $scope.$watch(() => this.data, data => renderReact(data)); } } }); diff --git a/x-pack/plugins/monitoring/public/views/base_eui_table_controller.js b/x-pack/plugins/monitoring/public/views/base_eui_table_controller.js new file mode 100644 index 0000000000000..c4f2ada58dff9 --- /dev/null +++ b/x-pack/plugins/monitoring/public/views/base_eui_table_controller.js @@ -0,0 +1,66 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { MonitoringViewBaseController } from './'; +import { euiTableStorageGetter, euiTableStorageSetter } from 'plugins/monitoring/components/table'; +import { SORT_ASCENDING } from '../../common/constants'; + +/** + * Class to manage common instantiation behaviors in a view controller + * And add persistent state to a table: + * - page index: in table pagination, which page are we looking at + * - filter text: what filter was entered in the table's filter bar + * - sortKey: which column field of table data is used for sorting + * - sortOrder: is sorting ordered ascending or descending + * + * This is expected to be extended, and behavior enabled using super(); + */ +export class MonitoringViewBaseEuiTableController extends MonitoringViewBaseController { + + /** + * Create a table view controller + * - used by parent class: + * @param {String} title - Title of the page + * @param {Function} getPageData - Function to fetch page data + * @param {Service} $injector - Angular dependency injection service + * @param {Service} $scope - Angular view data binding service + * @param {Boolean} options.enableTimeFilter - Whether to show the time filter + * @param {Boolean} options.enableAutoRefresh - Whether to show the auto refresh control + * - specific to this class: + * @param {String} storageKey - the namespace that will be used to keep the state data in the Monitoring localStorage object + * + */ + constructor(args) { + super(args); + const { storageKey, $injector } = args; + const storage = $injector.get('localStorage'); + + const getLocalStorageData = euiTableStorageGetter(storageKey); + const setLocalStorageData = euiTableStorageSetter(storageKey); + const { page, sort } = getLocalStorageData(storage); + + this.pagination = page || { + initialPageSize: 20, + pageSizeOptions: [5, 10, 20, 50] + }; + + this.sorting = sort || { + sort: { + field: 'name', + direction: SORT_ASCENDING + } + }; + + this.onTableChange = ({ page, sort }) => { + setLocalStorageData(storage, { + page, + sort: { + sort + } + }); + }; + } +} diff --git a/x-pack/plugins/monitoring/public/views/base_table_controller.js b/x-pack/plugins/monitoring/public/views/base_table_controller.js index 175a06aa92722..ad0a9678a36a6 100644 --- a/x-pack/plugins/monitoring/public/views/base_table_controller.js +++ b/x-pack/plugins/monitoring/public/views/base_table_controller.js @@ -50,5 +50,4 @@ export class MonitoringViewBaseTableController extends MonitoringViewBaseControl setLocalStorageData(storage, newState); }; } - } diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/ccr/shard/index.js b/x-pack/plugins/monitoring/public/views/elasticsearch/ccr/shard/index.js index 554aaaea31969..54164b06ce09b 100644 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/ccr/shard/index.js +++ b/x-pack/plugins/monitoring/public/views/elasticsearch/ccr/shard/index.js @@ -50,7 +50,9 @@ uiRoutes.when('/elasticsearch/ccr/:index/shard/:shardId', { this.renderReact = (props) => { super.renderReact( - + + + ); }; } diff --git a/x-pack/plugins/monitoring/server/lib/logstash/get_logstash_for_clusters.js b/x-pack/plugins/monitoring/server/lib/logstash/get_logstash_for_clusters.js index fae1a9431135d..0bd527523ad7d 100644 --- a/x-pack/plugins/monitoring/server/lib/logstash/get_logstash_for_clusters.js +++ b/x-pack/plugins/monitoring/server/lib/logstash/get_logstash_for_clusters.js @@ -182,6 +182,7 @@ export function getLogstashForClusters(req, lsIndexPattern, clusters) { const { callWithRequest } = req.server.plugins.elasticsearch.getCluster('monitoring'); return callWithRequest(req, 'search', params) .then(result => { + const aggregations = get(result, 'aggregations', {}); const logstashUuids = get(aggregations, 'logstash_uuids.buckets', []); const logstashVersions = get(aggregations, 'logstash_versions.buckets', []); diff --git a/x-pack/test/functional/page_objects/monitoring_page.js b/x-pack/test/functional/page_objects/monitoring_page.js index 12f148d255ebe..1c8f98119d54f 100644 --- a/x-pack/test/functional/page_objects/monitoring_page.js +++ b/x-pack/test/functional/page_objects/monitoring_page.js @@ -35,6 +35,12 @@ export function MonitoringPageProvider({ getPageObjects, getService }) { return table.findAllByTagName('tr'); } + async tableGetRowsFromContainer(subj) { + const table = await testSubjects.find(subj); + const tbody = await table.findByTagName('tbody'); + return tbody.findAllByTagName('tr'); + } + async tableSetFilter(subj, text) { return await testSubjects.setValue(subj, text); } diff --git a/x-pack/test/functional/services/monitoring/cluster_alerts.js b/x-pack/test/functional/services/monitoring/cluster_alerts.js index a47af62bfbdcd..6b51380600f04 100644 --- a/x-pack/test/functional/services/monitoring/cluster_alerts.js +++ b/x-pack/test/functional/services/monitoring/cluster_alerts.js @@ -23,8 +23,7 @@ export function MonitoringClusterAlertsProvider({ getService, getPageObjects }) const SUBJ_OVERVIEW_ACTIONS = `${SUBJ_OVERVIEW_CLUSTER_ALERTS} alertAction`; const SUBJ_OVERVIEW_VIEW_ALL = `${SUBJ_OVERVIEW_CLUSTER_ALERTS} viewAllAlerts`; - const SUBJ_LISTING_PAGE = 'clusterAlertsListingPage'; - const SUBJ_TABLE_BODY = 'alertsTableBody'; + const SUBJ_TABLE_BODY = 'alertsTableContainer'; const SUBJ_TABLE_ICONS = `${SUBJ_TABLE_BODY} alertIcon`; const SUBJ_TABLE_TEXTS = `${SUBJ_TABLE_BODY} alertText`; const SUBJ_TABLE_ACTIONS = `${SUBJ_TABLE_BODY} alertAction`; @@ -91,12 +90,12 @@ export function MonitoringClusterAlertsProvider({ getService, getPageObjects }) */ async isOnListingPage() { - const pageId = await retry.try(() => testSubjects.find(SUBJ_LISTING_PAGE)); + const pageId = await retry.try(() => testSubjects.find(SUBJ_TABLE_BODY)); return pageId !== null; } getTableAlerts() { - return PageObjects.monitoring.tableGetRows(SUBJ_TABLE_BODY); + return PageObjects.monitoring.tableGetRowsFromContainer(SUBJ_TABLE_BODY); } async getTableAlertsAll() { From 481dd131781875d98fbfc0e3c009f23e6b8eb52e Mon Sep 17 00:00:00 2001 From: Chris Roberson Date: Wed, 12 Dec 2018 10:02:03 -0500 Subject: [PATCH 02/85] [Monitoring] Elasticsearch monitoring to EUI (#26217) * Convert cluster alerts page to use EUI tables. Also adds baseline support for all monitoring tables * Fix tests * Remove these two files * Keep the original table but offer a new one so existing UIs still work * Use different base table controller for the EUI table * Use EUI specific asc and desc constants * Update summary status * ES nodes * Indices page * ML job listing * Fix tests up * Node listing page * Advanced node page * Advanced index * Fix tests * Fix onBrush * Cluster listing page * Update snapshots * Fix functional tests * Fix more tests * Remove commented out code --- .../public/components/apm/instance/status.js | 10 +- .../public/components/apm/instances/status.js | 6 +- .../public/components/beats/beat/beat.js | 91 +-- .../public/components/beats/stats.js | 107 +-- .../elasticsearch/ccr_shard/status.js | 10 +- .../elasticsearch/cluster_status/index.js | 14 +- .../elasticsearch/index/advanced.js | 59 ++ .../components/elasticsearch/index/index.js | 59 ++ .../index_detail_status/index.js | 10 +- .../elasticsearch/indices/indices.js | 250 +++---- .../components/elasticsearch/node/advanced.js | 63 ++ .../components/elasticsearch/node/node.js | 59 ++ .../elasticsearch/node_detail_status/index.js | 20 +- .../__snapshots__/cells.test.js.snap | 100 ++- .../components/elasticsearch/nodes/cells.js | 52 +- .../components/elasticsearch/nodes/nodes.js | 335 ++++----- .../elasticsearch/overview/overview.js | 19 +- .../shard_activity/recovery_index.js | 6 +- .../shard_activity/shard_activity.js | 124 ++-- .../shard_allocation/_index.scss | 0 .../shard_allocation/_shard_allocation.scss | 26 - .../shard_allocation/components/assigned.js | 4 +- .../components/cluster_view.js} | 8 +- .../shard_allocation/components/shard.js | 30 +- .../components/table_body.js} | 0 .../components/table_head.js} | 0 .../shard_allocation/components/unassigned.js | 0 .../elasticsearch/shard_allocation/index.js | 7 + .../shard_allocation/lib/calculate_class.js} | 0 .../shard_allocation/lib/decorate_shards.js | 0 .../lib/decorate_shards.test.js | 0 .../lib/generate_query_and_link.js} | 0 .../lib/has_primary_children.js} | 0 .../shard_allocation/lib/has_unassigned.js} | 0 .../shard_allocation/lib/labels.js | 0 .../shard_allocation/lib/vents.js | 0 .../shard_allocation/shard_allocation.js | 91 +++ .../transformers/indices_by_nodes.js | 0 .../transformers/nodes_by_indices.js | 2 +- .../components/kibana/cluster_status/index.js | 10 +- .../components/kibana/detail_status/index.js | 8 +- .../logstash/cluster_status/index.js | 8 +- .../logstash/detail_status/index.js | 18 +- .../__snapshots__/summary_status.test.js.snap | 349 +++++---- .../summary_status/summary_status.js | 89 +-- .../summary_status/summary_status.test.js | 12 +- .../monitoring/public/directives/all.js | 2 - .../directives/cluster/listing/index.js | 679 +++++++++--------- .../elasticsearch/ml_job_listing/index.js | 198 ++--- .../directives/clusterView.js | 42 -- .../elasticsearch/shard_allocation/index.html | 57 -- .../elasticsearch/shard_allocation/index.js | 45 -- x-pack/plugins/monitoring/public/index.scss | 2 +- .../public/views/base_eui_table_controller.js | 4 +- .../public/views/cluster/listing/index.html | 22 +- .../public/views/cluster/listing/index.js | 4 +- .../elasticsearch/index/advanced/index.html | 18 +- .../elasticsearch/index/advanced/index.js | 28 + .../views/elasticsearch/index/index.html | 21 +- .../public/views/elasticsearch/index/index.js | 42 ++ .../views/elasticsearch/indices/index.js | 7 +- .../views/elasticsearch/ml_jobs/index.html | 23 +- .../views/elasticsearch/ml_jobs/index.js | 4 +- .../elasticsearch/node/advanced/index.html | 22 +- .../elasticsearch/node/advanced/index.js | 28 + .../views/elasticsearch/node/index.html | 22 +- .../public/views/elasticsearch/node/index.js | 38 + .../public/views/elasticsearch/nodes/index.js | 7 +- .../plugins/monitoring/public/views/index.js | 1 + .../apps/monitoring/beats/listing.js | 4 +- .../apps/monitoring/beats/overview.js | 4 +- .../apps/monitoring/elasticsearch/indices.js | 44 +- .../monitoring/elasticsearch/node_detail.js | 6 +- .../apps/monitoring/elasticsearch/nodes.js | 37 +- .../page_objects/monitoring_page.js | 8 + .../services/monitoring/cluster_list.js | 5 +- .../monitoring/elasticsearch_indices.js | 23 +- .../monitoring/elasticsearch_nodes.js | 22 +- 78 files changed, 1833 insertions(+), 1692 deletions(-) create mode 100644 x-pack/plugins/monitoring/public/components/elasticsearch/index/advanced.js create mode 100644 x-pack/plugins/monitoring/public/components/elasticsearch/index/index.js create mode 100644 x-pack/plugins/monitoring/public/components/elasticsearch/node/advanced.js create mode 100644 x-pack/plugins/monitoring/public/components/elasticsearch/node/node.js rename x-pack/plugins/monitoring/public/{directives => components}/elasticsearch/shard_allocation/_index.scss (100%) rename x-pack/plugins/monitoring/public/{directives => components}/elasticsearch/shard_allocation/_shard_allocation.scss (77%) rename x-pack/plugins/monitoring/public/{directives => components}/elasticsearch/shard_allocation/components/assigned.js (94%) rename x-pack/plugins/monitoring/public/{directives/elasticsearch/shard_allocation/components/clusterView.js => components/elasticsearch/shard_allocation/components/cluster_view.js} (89%) rename x-pack/plugins/monitoring/public/{directives => components}/elasticsearch/shard_allocation/components/shard.js (78%) rename x-pack/plugins/monitoring/public/{directives/elasticsearch/shard_allocation/components/tableBody.js => components/elasticsearch/shard_allocation/components/table_body.js} (100%) rename x-pack/plugins/monitoring/public/{directives/elasticsearch/shard_allocation/components/tableHead.js => components/elasticsearch/shard_allocation/components/table_head.js} (100%) rename x-pack/plugins/monitoring/public/{directives => components}/elasticsearch/shard_allocation/components/unassigned.js (100%) create mode 100644 x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/index.js rename x-pack/plugins/monitoring/public/{directives/elasticsearch/shard_allocation/lib/calculateClass.js => components/elasticsearch/shard_allocation/lib/calculate_class.js} (100%) rename x-pack/plugins/monitoring/public/{directives => components}/elasticsearch/shard_allocation/lib/decorate_shards.js (100%) rename x-pack/plugins/monitoring/public/{directives => components}/elasticsearch/shard_allocation/lib/decorate_shards.test.js (100%) rename x-pack/plugins/monitoring/public/{directives/elasticsearch/shard_allocation/lib/generateQueryAndLink.js => components/elasticsearch/shard_allocation/lib/generate_query_and_link.js} (100%) rename x-pack/plugins/monitoring/public/{directives/elasticsearch/shard_allocation/lib/hasPrimaryChildren.js => components/elasticsearch/shard_allocation/lib/has_primary_children.js} (100%) rename x-pack/plugins/monitoring/public/{directives/elasticsearch/shard_allocation/lib/hasUnassigned.js => components/elasticsearch/shard_allocation/lib/has_unassigned.js} (100%) rename x-pack/plugins/monitoring/public/{directives => components}/elasticsearch/shard_allocation/lib/labels.js (100%) rename x-pack/plugins/monitoring/public/{directives => components}/elasticsearch/shard_allocation/lib/vents.js (100%) create mode 100644 x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/shard_allocation.js rename x-pack/plugins/monitoring/public/{directives => components}/elasticsearch/shard_allocation/transformers/indices_by_nodes.js (100%) rename x-pack/plugins/monitoring/public/{directives => components}/elasticsearch/shard_allocation/transformers/nodes_by_indices.js (97%) delete mode 100644 x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/directives/clusterView.js delete mode 100644 x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/index.html delete mode 100644 x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/index.js diff --git a/x-pack/plugins/monitoring/public/components/apm/instance/status.js b/x-pack/plugins/monitoring/public/components/apm/instance/status.js index 386ddeaa5bc10..c53339b917c18 100644 --- a/x-pack/plugins/monitoring/public/components/apm/instance/status.js +++ b/x-pack/plugins/monitoring/public/components/apm/instance/status.js @@ -29,7 +29,7 @@ function StatusUI({ stats, intl }) { defaultMessage: 'Name', }), value: name, - dataTestSubj: 'name' + 'data-test-subj': 'name' }, { label: intl.formatMessage({ @@ -37,7 +37,7 @@ function StatusUI({ stats, intl }) { defaultMessage: 'Output', }), value: output, - dataTestSubj: 'output' + 'data-test-subj': 'output' }, { label: intl.formatMessage({ @@ -45,7 +45,7 @@ function StatusUI({ stats, intl }) { defaultMessage: 'Version', }), value: version, - dataTestSubj: 'version' + 'data-test-subj': 'version' }, { label: intl.formatMessage({ @@ -53,7 +53,7 @@ function StatusUI({ stats, intl }) { defaultMessage: 'Uptime', }), value: formatMetric(uptime, 'time_since'), - dataTestSubj: 'uptime' + 'data-test-subj': 'uptime' }, { label: intl.formatMessage({ @@ -65,7 +65,7 @@ function StatusUI({ stats, intl }) { defaultMessage: '{timeOfLastEvent} ago' }, { timeOfLastEvent: formatTimestampToDuration(+moment(timeOfLastEvent), CALCULATE_DURATION_SINCE) }), - dataTestSubj: 'timeOfLastEvent', + 'data-test-subj': 'timeOfLastEvent', } ]; diff --git a/x-pack/plugins/monitoring/public/components/apm/instances/status.js b/x-pack/plugins/monitoring/public/components/apm/instances/status.js index fd32ce26bb294..e7cc42e8971f5 100644 --- a/x-pack/plugins/monitoring/public/components/apm/instances/status.js +++ b/x-pack/plugins/monitoring/public/components/apm/instances/status.js @@ -29,7 +29,7 @@ function StatusUI({ stats, intl }) { defaultMessage: 'Servers', }), value: total, - dataTestSubj: 'total' + 'data-test-subj': 'total' }, { label: intl.formatMessage({ @@ -37,7 +37,7 @@ function StatusUI({ stats, intl }) { defaultMessage: 'Total Events', }), value: formatMetric(totalEvents, '0.[0]a'), - dataTestSubj: 'totalEvents' + 'data-test-subj': 'totalEvents' }, { label: intl.formatMessage({ @@ -49,7 +49,7 @@ function StatusUI({ stats, intl }) { defaultMessage: '{timeOfLastEvent} ago' }, { timeOfLastEvent: formatTimestampToDuration(+moment(timeOfLastEvent), CALCULATE_DURATION_SINCE) }), - dataTestSubj: 'timeOfLastEvent', + 'data-test-subj': 'timeOfLastEvent', } ]; diff --git a/x-pack/plugins/monitoring/public/components/beats/beat/beat.js b/x-pack/plugins/monitoring/public/components/beats/beat/beat.js index b3c7aaa290fac..bc281c1bb7032 100644 --- a/x-pack/plugins/monitoring/public/components/beats/beat/beat.js +++ b/x-pack/plugins/monitoring/public/components/beats/beat/beat.js @@ -7,8 +7,9 @@ import React from 'react'; import { MonitoringTimeseriesContainer } from '../../chart'; import { formatMetric } from '../../../lib/format_number'; -import { EuiFlexItem, EuiFlexGroup, EuiPage, EuiPageBody, EuiFlexGrid, EuiSpacer } from '@elastic/eui'; +import { EuiFlexItem, EuiPage, EuiPageBody, EuiFlexGrid, EuiSpacer, EuiPageContent } from '@elastic/eui'; import { injectI18n } from '@kbn/i18n/react'; +import { SummaryStatus } from '../../summary_status'; function BeatUi({ summary, metrics, intl, ...props }) { @@ -23,58 +24,41 @@ function BeatUi({ summary, metrics, intl, ...props }) { metrics.beat_handles, ]; - const wrapChild = ({ label, value, dataTestSubj }, index) => ( - - - - {label ? label + ': ' : null} - - - {value} - - - - ); - const summarytStatsTop = [ { label: intl.formatMessage({ id: 'xpack.monitoring.beats.instance.nameLabel', defaultMessage: 'Name' }), value: summary.name, - dataTestSubj: 'name' + 'data-test-subj': 'name' }, { label: intl.formatMessage({ id: 'xpack.monitoring.beats.instance.hostLabel', defaultMessage: 'Host' }), value: summary.transportAddress, - dataTestSubj: 'host' + 'data-test-subj': 'host' }, { label: intl.formatMessage({ id: 'xpack.monitoring.beats.instance.versionLabel', defaultMessage: 'Version' }), value: summary.version, - dataTestSubj: 'version' + 'data-test-subj': 'version' }, { label: intl.formatMessage({ id: 'xpack.monitoring.beats.instance.typeLabel', defaultMessage: 'Type' }), value: summary.type, - dataTestSubj: 'type' + 'data-test-subj': 'type' }, { label: intl.formatMessage({ id: 'xpack.monitoring.beats.instance.outputLabel', defaultMessage: 'Output' }), value: summary.output, - dataTestSubj: 'output' + 'data-test-subj': 'output' }, { label: intl.formatMessage({ id: 'xpack.monitoring.beats.instance.configReloadsLabel', defaultMessage: 'Config reloads' }), value: formatMetric(summary.configReloads, 'int_commas'), - dataTestSubj: 'configReloads' + 'data-test-subj': 'configReloads' }, { label: intl.formatMessage({ id: 'xpack.monitoring.beats.instance.uptimeLabel', defaultMessage: 'Uptime' }), value: formatMetric(summary.uptime, 'time_since'), - dataTestSubj: 'uptime' + 'data-test-subj': 'uptime' }, ]; @@ -82,63 +66,48 @@ function BeatUi({ summary, metrics, intl, ...props }) { { label: intl.formatMessage({ id: 'xpack.monitoring.beats.instance.eventsTotalLabel', defaultMessage: 'Events total' }), value: formatMetric(summary.eventsTotal, 'int_commas'), - dataTestSubj: 'eventsTotal' + 'data-test-subj': 'eventsTotal' }, { label: intl.formatMessage({ id: 'xpack.monitoring.beats.instance.eventsEmittedLabel', defaultMessage: 'Events emitted' }), value: formatMetric(summary.eventsEmitted, 'int_commas'), - dataTestSubj: 'eventsEmitted' + 'data-test-subj': 'eventsEmitted' }, { label: intl.formatMessage({ id: 'xpack.monitoring.beats.instance.eventsDroppedLabel', defaultMessage: 'Events dropped' }), value: formatMetric(summary.eventsDropped, 'int_commas'), - dataTestSubj: 'eventsDropped' + 'data-test-subj': 'eventsDropped' }, { label: intl.formatMessage({ id: 'xpack.monitoring.beats.instance.bytesSentLabel', defaultMessage: 'Bytes sent' }), value: formatMetric(summary.bytesWritten, 'byte'), - dataTestSubj: 'bytesWritten' + 'data-test-subj': 'bytesWritten' }, { label: intl.formatMessage({ id: 'xpack.monitoring.beats.instance.handlesLimitSoftLabel', defaultMessage: 'Handles limit (soft)' }), value: formatMetric(summary.handlesSoftLimit, 'byte'), - dataTestSubj: 'handlesLimitSoft' + 'data-test-subj': 'handlesLimitSoft' }, { label: intl.formatMessage({ id: 'xpack.monitoring.beats.instance.handlesLimitHardLabel', defaultMessage: 'Handles limit (hard)' }), value: formatMetric(summary.handlesHardLimit, 'byte'), - dataTestSubj: 'handlesLimitHard' + 'data-test-subj': 'handlesLimitHard' }, ]; return ( -
-
-
- - - - {summarytStatsTop.map(wrapChild)} - - - -
-
- -
-
- - - - {summarytStatsBot.map(wrapChild)} - - - -
-
- - - + + + + + + {metricsToShow.map((metric, index) => ( @@ -150,9 +119,9 @@ function BeatUi({ summary, metrics, intl, ...props }) { ))} - - -
+ + + ); } diff --git a/x-pack/plugins/monitoring/public/components/beats/stats.js b/x-pack/plugins/monitoring/public/components/beats/stats.js index f5fceb04eccda..a509a90d01fdf 100644 --- a/x-pack/plugins/monitoring/public/components/beats/stats.js +++ b/x-pack/plugins/monitoring/public/components/beats/stats.js @@ -4,80 +4,51 @@ * you may not use this file except in compliance with the Elastic License. */ -import { get } from 'lodash'; import React from 'react'; import { formatMetric } from 'plugins/monitoring/lib/format_number'; -import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; -import { FormattedMessage } from '@kbn/i18n/react'; +import { SummaryStatus } from '../summary_status'; export function Stats({ stats }) { - const types = stats.types.map(({ type, count }, index) => { - return ( - - - - {type ? type + ': ' : null} - - - {formatMetric(count, 'int_commas')} - - - - ); + const { + total, + types, + stats: { + bytesSent, + totalEvents, + } + } = stats; + + const metrics = [ + { + label: 'Total Beats', + value: formatMetric(total, 'int_commas'), + 'data-test-subj': 'totalBeats' + }, + ]; + + metrics.push(...types.map(({ type, count }) => ({ + label: type, + value: formatMetric(count, 'int_commas'), + 'data-test-subj': 'typeCount', + 'data-test-type-count': `${type}:${count}` + }))); + + metrics.push({ + label: 'Total Events', + value: formatMetric(totalEvents, '0.[0]a'), + 'data-test-subj': 'totalEvents' }); - return ( -
- - - - - :  - - - - {formatMetric(get(stats, 'total'), 'int_commas')} - - - - {types} - - - - :  - - - - - {formatMetric(get(stats, 'stats.totalEvents'), '0.[0]a')} - - - - - - :  - - - - {formatMetric(get(stats, 'stats.bytesSent'), 'byte')} - - - + metrics.push({ + label: 'Bytes Sent', + value: formatMetric(bytesSent, 'byte'), + 'data-test-subj': 'bytesSent' + }); -
+ return ( + ); } diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/ccr_shard/status.js b/x-pack/plugins/monitoring/public/components/elasticsearch/ccr_shard/status.js index 89da6c6d4fac3..302aebf4667be 100644 --- a/x-pack/plugins/monitoring/public/components/elasticsearch/ccr_shard/status.js +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/ccr_shard/status.js @@ -29,7 +29,7 @@ function StatusUI({ stat, formattedLeader, oldestStat, intl }) { defaultMessage: 'Follower Index', }), value: followerIndex, - dataTestSubj: 'followerIndex' + 'data-test-subj': 'followerIndex' }, { label: intl.formatMessage({ @@ -37,7 +37,7 @@ function StatusUI({ stat, formattedLeader, oldestStat, intl }) { defaultMessage: 'Shard Id', }), value: shardId, - dataTestSubj: 'shardId' + 'data-test-subj': 'shardId' }, { label: intl.formatMessage({ @@ -45,7 +45,7 @@ function StatusUI({ stat, formattedLeader, oldestStat, intl }) { defaultMessage: 'Leader Index', }), value: formattedLeader, - dataTestSubj: 'leaderIndex' + 'data-test-subj': 'leaderIndex' }, { label: intl.formatMessage({ @@ -53,7 +53,7 @@ function StatusUI({ stat, formattedLeader, oldestStat, intl }) { defaultMessage: 'Ops Synced', }), value: formatMetric(operationsReceived - oldestOperationsReceived, 'int_commas'), - dataTestSubj: 'operationsReceived' + 'data-test-subj': 'operationsReceived' }, { label: intl.formatMessage({ @@ -61,7 +61,7 @@ function StatusUI({ stat, formattedLeader, oldestStat, intl }) { defaultMessage: 'Failed Fetches', }), value: formatMetric(failedFetches - oldestFailedFetches, 'int_commas'), - dataTestSubj: 'failedFetches' + 'data-test-subj': 'failedFetches' }, ]; diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/cluster_status/index.js b/x-pack/plugins/monitoring/public/components/elasticsearch/cluster_status/index.js index a7d007e4d22f1..2426b47d1787e 100644 --- a/x-pack/plugins/monitoring/public/components/elasticsearch/cluster_status/index.js +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/cluster_status/index.js @@ -30,7 +30,7 @@ function ClusterStatusUI({ stats, intl }) { defaultMessage: 'Nodes', }), value: nodesCount, - dataTestSubj: 'nodesCount' + 'data-test-subj': 'nodesCount' }, { label: intl.formatMessage({ @@ -38,7 +38,7 @@ function ClusterStatusUI({ stats, intl }) { defaultMessage: 'Indices', }), value: indicesCount, - dataTestSubj: 'indicesCount' + 'data-test-subj': 'indicesCount' }, { label: intl.formatMessage({ @@ -46,7 +46,7 @@ function ClusterStatusUI({ stats, intl }) { defaultMessage: 'Memory', }), value: formatMetric(memUsed, 'byte') + ' / ' + formatMetric(memMax, 'byte'), - dataTestSubj: 'memory' + 'data-test-subj': 'memory' }, { label: intl.formatMessage({ @@ -54,7 +54,7 @@ function ClusterStatusUI({ stats, intl }) { defaultMessage: 'Total Shards', }), value: totalShards, - dataTestSubj: 'totalShards' + 'data-test-subj': 'totalShards' }, { label: intl.formatMessage({ @@ -62,7 +62,7 @@ function ClusterStatusUI({ stats, intl }) { defaultMessage: 'Unassigned Shards', }), value: unassignedShards, - dataTestSubj: 'unassignedShards' + 'data-test-subj': 'unassignedShards' }, { label: intl.formatMessage({ @@ -70,7 +70,7 @@ function ClusterStatusUI({ stats, intl }) { defaultMessage: 'Documents', }), value: formatMetric(documentCount, 'int_commas'), - dataTestSubj: 'documentCount' + 'data-test-subj': 'documentCount' }, { label: intl.formatMessage({ @@ -78,7 +78,7 @@ function ClusterStatusUI({ stats, intl }) { defaultMessage: 'Data', }), value: formatMetric(dataSize, 'byte'), - dataTestSubj: 'dataSize' + 'data-test-subj': 'dataSize' } ]; diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/index/advanced.js b/x-pack/plugins/monitoring/public/components/elasticsearch/index/advanced.js new file mode 100644 index 0000000000000..e64b488635e9c --- /dev/null +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/index/advanced.js @@ -0,0 +1,59 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { + EuiPage, + EuiPageContent, + EuiPageBody, + EuiSpacer, + EuiFlexGrid, + EuiFlexItem, +} from '@elastic/eui'; +import { IndexDetailStatus } from '../index_detail_status'; +import { MonitoringTimeseriesContainer } from '../../chart'; + +export const AdvancedIndex = ({ + indexSummary, + metrics, + ...props +}) => { + const metricsToShow = [ + metrics.index_1, + metrics.index_2, + metrics.index_3, + metrics.index_4, + metrics.index_total, + metrics.index_time, + metrics.index_refresh, + metrics.index_throttling, + metrics.index_disk, + metrics.index_segment_count, + metrics.index_latency, + ]; + + return ( + + + + + + + {metricsToShow.map((metric, index) => ( + + + + + ))} + + + + + ); +}; diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/index/index.js b/x-pack/plugins/monitoring/public/components/elasticsearch/index/index.js new file mode 100644 index 0000000000000..8caf0d0b48b43 --- /dev/null +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/index/index.js @@ -0,0 +1,59 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { + EuiPage, + EuiPageContent, + EuiPageBody, + EuiSpacer, + EuiFlexGrid, + EuiFlexItem, +} from '@elastic/eui'; +import { IndexDetailStatus } from '../index_detail_status'; +import { MonitoringTimeseriesContainer } from '../../chart'; +import { ShardAllocation } from '../shard_allocation/shard_allocation'; + +export const Index = ({ + indexSummary, + metrics, + scope, + kbnUrl, + ...props +}) => { + const metricsToShow = [ + metrics.index_mem, + metrics.index_size, + metrics.index_search_request_rate, + metrics.index_request_rate, + metrics.index_segment_count, + metrics.index_document_count, + ]; + + return ( + + + + + + + {metricsToShow.map((metric, index) => ( + + + + + ))} + + + + + + + ); +}; diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/index_detail_status/index.js b/x-pack/plugins/monitoring/public/components/elasticsearch/index_detail_status/index.js index 55e65608b81f7..78e43538eaa91 100644 --- a/x-pack/plugins/monitoring/public/components/elasticsearch/index_detail_status/index.js +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/index_detail_status/index.js @@ -26,7 +26,7 @@ function IndexDetailStatusUI({ stats, intl }) { defaultMessage: 'Total', }), value: formatMetric(dataSize.total, '0.0 b'), - dataTestSubj: 'dataSize' + 'data-test-subj': 'dataSize' }, { label: intl.formatMessage({ @@ -34,7 +34,7 @@ function IndexDetailStatusUI({ stats, intl }) { defaultMessage: 'Primaries', }), value: formatMetric(dataSize.primaries, '0.0 b'), - dataTestSubj: 'dataSizePrimaries' + 'data-test-subj': 'dataSizePrimaries' }, { label: intl.formatMessage({ @@ -42,7 +42,7 @@ function IndexDetailStatusUI({ stats, intl }) { defaultMessage: 'Documents', }), value: formatMetric(documentCount, '0.[0]a'), - dataTestSubj: 'documentCount' + 'data-test-subj': 'documentCount' }, { label: intl.formatMessage({ @@ -50,7 +50,7 @@ function IndexDetailStatusUI({ stats, intl }) { defaultMessage: 'Total Shards', }), value: formatMetric(totalShards, 'int_commas'), - dataTestSubj: 'totalShards' + 'data-test-subj': 'totalShards' }, { label: intl.formatMessage({ @@ -58,7 +58,7 @@ function IndexDetailStatusUI({ stats, intl }) { defaultMessage: 'Unassigned Shards', }), value: formatMetric(unassignedShards, 'int_commas'), - dataTestSubj: 'unassignedShards' + 'data-test-subj': 'unassignedShards' } ]; diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/indices/indices.js b/x-pack/plugins/monitoring/public/components/elasticsearch/indices/indices.js index ba41ea8fb82d6..dceb2e2ab4e88 100644 --- a/x-pack/plugins/monitoring/public/components/elasticsearch/indices/indices.js +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/indices/indices.js @@ -4,133 +4,119 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { Fragment } from 'react'; -import { capitalize, get } from 'lodash'; -import { SORT_ASCENDING, SORT_DESCENDING } from '../../../../common/constants'; +import React from 'react'; +import { capitalize } from 'lodash'; import { LARGE_FLOAT, LARGE_BYTES, LARGE_ABBREVIATED } from '../../../../common/formatting'; import { formatMetric } from '../../../lib/format_number'; import { ElasticsearchStatusIcon } from '../status_icon'; import { ClusterStatus } from '../cluster_status'; -import { MonitoringTable } from '../../table'; -import { EuiLink } from '@elastic/eui'; -import { KuiTableRowCell, KuiTableRow } from '@kbn/ui-framework/components'; -import { SystemIndicesCheckbox } from './system_indices_checkbox'; +import { EuiMonitoringTable } from '../../table'; +import { + EuiLink, + EuiPage, + EuiPageContent, + EuiPageBody, + EuiSwitch, + EuiSpacer, +} from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage, injectI18n } from '@kbn/i18n/react'; -const filterFields = ['name', 'status']; const columns = [ { - title: i18n.translate('xpack.monitoring.elasticsearch.indices.nameTitle', { + name: i18n.translate('xpack.monitoring.elasticsearch.indices.nameTitle', { defaultMessage: 'Name', }), - sortKey: 'name', - secondarySortOrder: SORT_ASCENDING + field: 'name', + width: '350px', + sortable: true, + render: (value) => ( +
+ + {value} + +
+ ), }, { - title: i18n.translate('xpack.monitoring.elasticsearch.indices.statusTitle', { + name: i18n.translate('xpack.monitoring.elasticsearch.indices.statusTitle', { defaultMessage: 'Status', }), - sortKey: 'status_sort', - sortOrder: SORT_DESCENDING // default sort: red, then yellow, then green + field: 'status', + sortable: true, + render: (value) => ( +
+   + {capitalize(value)} +
+ ) }, { - title: i18n.translate('xpack.monitoring.elasticsearch.indices.documentCountTitle', { + name: i18n.translate('xpack.monitoring.elasticsearch.indices.documentCountTitle', { defaultMessage: 'Document Count', }), - sortKey: 'doc_count' + field: 'doc_count', + sortable: true, + render: value => ( +
+ {formatMetric(value, LARGE_ABBREVIATED)} +
+ ) }, { - title: i18n.translate('xpack.monitoring.elasticsearch.indices.dataTitle', { + name: i18n.translate('xpack.monitoring.elasticsearch.indices.dataTitle', { defaultMessage: 'Data', }), - sortKey: 'data_size' + field: 'data_size', + sortable: true, + render: value => ( +
+ {formatMetric(value, LARGE_BYTES)} +
+ ) }, { - title: i18n.translate('xpack.monitoring.elasticsearch.indices.indexRateTitle', { + name: i18n.translate('xpack.monitoring.elasticsearch.indices.indexRateTitle', { defaultMessage: 'Index Rate', }), - sortKey: 'index_rate' + field: 'index_rate', + sortable: true, + render: value => ( +
+ {formatMetric(value, LARGE_FLOAT, '/s')} +
+ ) }, { - title: i18n.translate('xpack.monitoring.elasticsearch.indices.searchRateTitle', { + name: i18n.translate('xpack.monitoring.elasticsearch.indices.searchRateTitle', { defaultMessage: 'Search Rate', }), - sortKey: 'search_rate' + field: 'search_rate', + sortable: true, + render: value => ( +
+ {formatMetric(value, LARGE_FLOAT, '/s')} +
+ ) }, { - title: i18n.translate('xpack.monitoring.elasticsearch.indices.unassignedShardsTitle', { + name: i18n.translate('xpack.monitoring.elasticsearch.indices.unassignedShardsTitle', { defaultMessage: 'Unassigned Shards', }), - sortKey: 'unassigned_shards' + field: 'unassigned_shards', + sortable: true, + render: value => ( +
+ {formatMetric(value, '0')} +
+ ) } ]; -const IndexRow = injectI18n(({ status, ...props }) => ( - - - - {props.name} - - - -
-   - {capitalize(status)} -
-
- - {formatMetric(get(props, 'doc_count'), LARGE_ABBREVIATED)} - - - {formatMetric(get(props, 'data_size'), LARGE_BYTES)} - - - {formatMetric(get(props, 'index_rate'), LARGE_FLOAT, '/s')} - - - {formatMetric(get(props, 'search_rate'), LARGE_FLOAT, '/s')} - - - {formatMetric(get(props, 'unassigned_shards'), '0')} - -
-)); -const getNoDataMessage = filterText => { - const howToShowSystemIndicesDescription = ( - - ); - if (filterText) { - return ( -
-

- -

-

- {howToShowSystemIndicesDescription} -

-
- ); - } +const getNoDataMessage = () => { return (

@@ -140,46 +126,64 @@ const getNoDataMessage = filterText => { />

- {howToShowSystemIndicesDescription} +

); }; -const renderToolBarSection = ({ showSystemIndices, toggleShowSystemIndices, ...props }) => ( - -); - -function ElasticsearchIndicesUI({ clusterStatus, indices, intl, ...props }) { +const ElasticsearchIndicesUI = ({ + clusterStatus, + indices, + intl, + sorting, + pagination, + onTableChange, + toggleShowSystemIndices, + showSystemIndices, +}) => { return ( - - - - + + + + + + + )} + checked={showSystemIndices} + onChange={e => toggleShowSystemIndices(e.target.checked)} + /> + + + + + ); -} +}; export const ElasticsearchIndices = injectI18n(ElasticsearchIndicesUI); diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/node/advanced.js b/x-pack/plugins/monitoring/public/components/elasticsearch/node/advanced.js new file mode 100644 index 0000000000000..012f7face71be --- /dev/null +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/node/advanced.js @@ -0,0 +1,63 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { + EuiPage, + EuiPageContent, + EuiPageBody, + EuiSpacer, + EuiFlexGrid, + EuiFlexItem, +} from '@elastic/eui'; +import { NodeDetailStatus } from '../node_detail_status'; +import { MonitoringTimeseriesContainer } from '../../chart'; + +export const AdvancedNode = ({ + nodeSummary, + metrics, + ...props +}) => { + const metricsToShow = [ + metrics.node_gc, + metrics.node_gc_time, + metrics.node_jvm_mem, + metrics.node_cpu_utilization, + metrics.node_index_1, + metrics.node_index_2, + metrics.node_index_3, + metrics.node_index_4, + metrics.node_index_time, + metrics.node_request_total, + metrics.node_index_threads, + metrics.node_read_threads, + metrics.node_cgroup_cpu, + metrics.node_cgroup_stats, + metrics.node_latency, + ]; + + return ( + + + + + + + {metricsToShow.map((metric, index) => ( + + + + + ))} + + + + + ); +}; diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/node/node.js b/x-pack/plugins/monitoring/public/components/elasticsearch/node/node.js new file mode 100644 index 0000000000000..2cb8db083a816 --- /dev/null +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/node/node.js @@ -0,0 +1,59 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { + EuiPage, + EuiPageContent, + EuiPageBody, + EuiSpacer, + EuiFlexGrid, + EuiFlexItem, +} from '@elastic/eui'; +import { NodeDetailStatus } from '../node_detail_status'; +import { MonitoringTimeseriesContainer } from '../../chart'; +import { ShardAllocation } from '../shard_allocation/shard_allocation'; + +export const Node = ({ + nodeSummary, + metrics, + scope, + kbnUrl, + ...props +}) => { + const metricsToShow = [ + metrics.node_jvm_mem, + metrics.node_mem, + metrics.node_cpu_metric, + metrics.node_load_average, + metrics.node_latency, + metrics.node_segment_count, + ]; + + return ( + + + + + + + {metricsToShow.map((metric, index) => ( + + + + + ))} + + + + + + + ); +}; diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/node_detail_status/index.js b/x-pack/plugins/monitoring/public/components/elasticsearch/node_detail_status/index.js index a901a36c7325a..9184b45eb159c 100644 --- a/x-pack/plugins/monitoring/public/components/elasticsearch/node_detail_status/index.js +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/node_detail_status/index.js @@ -26,8 +26,12 @@ function NodeDetailStatusUI({ stats, intl }) { const metrics = [ { + label: intl.formatMessage({ + id: 'xpack.monitoring.elasticsearch.nodeDetailStatus.transportAddress', + defaultMessage: 'Transport Address', + }), value: transportAddress, - dataTestSubj: 'transportAddress' + 'data-test-subj': 'transportAddress' }, { label: intl.formatMessage({ @@ -36,7 +40,7 @@ function NodeDetailStatusUI({ stats, intl }) { javaVirtualMachine: 'JVM' }), value: formatMetric(usedHeap, '0,0.[00]', '%', { prependSpace: false }), - dataTestSubj: 'jvmHeap' + 'data-test-subj': 'jvmHeap' }, { label: intl.formatMessage({ @@ -44,7 +48,7 @@ function NodeDetailStatusUI({ stats, intl }) { defaultMessage: 'Free Disk Space', }), value: formatMetric(freeSpace, '0.0 b'), - dataTestSubj: 'freeDiskSpace' + 'data-test-subj': 'freeDiskSpace' }, { label: intl.formatMessage({ @@ -52,7 +56,7 @@ function NodeDetailStatusUI({ stats, intl }) { defaultMessage: 'Documents', }), value: formatMetric(documents, '0.[0]a'), - dataTestSubj: 'documentCount' + 'data-test-subj': 'documentCount' }, { label: intl.formatMessage({ @@ -60,7 +64,7 @@ function NodeDetailStatusUI({ stats, intl }) { defaultMessage: 'Data', }), value: formatMetric(dataSize, '0.0 b'), - dataTestSubj: 'dataSize' + 'data-test-subj': 'dataSize' }, { label: intl.formatMessage({ @@ -68,7 +72,7 @@ function NodeDetailStatusUI({ stats, intl }) { defaultMessage: 'Indices', }), value: formatMetric(indexCount, 'int_commas'), - dataTestSubj: 'indicesCount' + 'data-test-subj': 'indicesCount' }, { label: intl.formatMessage({ @@ -76,7 +80,7 @@ function NodeDetailStatusUI({ stats, intl }) { defaultMessage: 'Shards', }), value: formatMetric(totalShards, 'int_commas'), - dataTestSubj: 'shardsCount' + 'data-test-subj': 'shardsCount' }, { label: intl.formatMessage({ @@ -84,7 +88,7 @@ function NodeDetailStatusUI({ stats, intl }) { defaultMessage: 'Type', }), value: nodeTypeLabel, - dataTestSubj: 'nodeType' + 'data-test-subj': 'nodeType' } ]; diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/nodes/__tests__/__snapshots__/cells.test.js.snap b/x-pack/plugins/monitoring/public/components/elasticsearch/nodes/__tests__/__snapshots__/cells.test.js.snap index 900f707856d4e..f737d2d435c0c 100644 --- a/x-pack/plugins/monitoring/public/components/elasticsearch/nodes/__tests__/__snapshots__/cells.test.js.snap +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/nodes/__tests__/__snapshots__/cells.test.js.snap @@ -1,75 +1,103 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Node Listing Metric Cell should format N/A as the metric for an offline node 1`] = ` - -
-
- N/A -
-
- + N/A +
`; exports[`Node Listing Metric Cell should format a non-percentage metric 1`] = ` -
+

+

+

+

- 206.3 GB +

+ 206.3 GB  + +

-
-
+
206.5 GB max
-
+
206.3 GB min
- +

+

`; exports[`Node Listing Metric Cell should format a percentage metric 1`] = ` -
+

+

+

+

- 0% +

+ 0%  + +

-
-
+
2% max
-
+
0% min
- +

+

`; diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/nodes/cells.js b/x-pack/plugins/monitoring/public/components/elasticsearch/nodes/cells.js index 8fb336a8fc85e..4c9144349917c 100644 --- a/x-pack/plugins/monitoring/public/components/elasticsearch/nodes/cells.js +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/nodes/cells.js @@ -7,19 +7,13 @@ import React from 'react'; import { get } from 'lodash'; import { formatMetric } from '../../../lib/format_number'; -import { KuiTableRowCell } from '@kbn/ui-framework/components'; -import { FormattedMessage } from '@kbn/i18n/react'; +import { EuiStat, EuiText, EuiTitle, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; function OfflineCell() { return ( - -
- -
-
+
+ N/A +
); } @@ -43,20 +37,30 @@ function MetricCell({ isOnline, metric = {}, isPercent, ...props }) { const format = get(metric, 'metric.format'); return ( - -
- { metricVal(lastVal, format, isPercent) } -
- -
-
- { metricVal(maxVal, format, isPercent) + ' max' } -
-
- { metricVal(minVal, format, isPercent) + ' min' } -
-
-
+ + + +

+ { metricVal(lastVal, format, isPercent) } +   + +

+
+
+ + + { metricVal(maxVal, format, isPercent) + ' max' } + + + { metricVal(minVal, format, isPercent) + ' min' } + + + + )} + /> ); } diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/nodes/nodes.js b/x-pack/plugins/monitoring/public/components/elasticsearch/nodes/nodes.js index 9f05ccf50ed15..31a8b6bcf0b6b 100644 --- a/x-pack/plugins/monitoring/public/components/elasticsearch/nodes/nodes.js +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/nodes/nodes.js @@ -4,227 +4,228 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { Fragment } from 'react'; -import { get } from 'lodash'; -import { SORT_ASCENDING } from '../../../../common/constants'; +import React from 'react'; import { NodeStatusIcon } from '../node'; import { extractIp } from '../../../lib/extract_ip'; // TODO this is only used for elasticsearch nodes summary / node detail, so it should be moved to components/elasticsearch/nodes/lib import { ClusterStatus } from '../cluster_status'; -import { MonitoringTable } from '../../table'; +import { EuiMonitoringTable } from '../../table'; import { MetricCell, OfflineCell } from './cells'; -import { EuiLink, EuiToolTip } from '@elastic/eui'; -import { KuiTableRowCell, KuiTableRow } from '@kbn/ui-framework/components'; +import { + EuiLink, + EuiToolTip, + EuiSpacer, + EuiPage, + EuiPageContent, + EuiPageBody, +} from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { injectI18n } from '@kbn/i18n/react'; -const filterFields = ['name']; const getColumns = showCgroupMetricsElasticsearch => { const cols = []; + + const cpuUsageColumnTitle = i18n.translate('xpack.monitoring.elasticsearch.nodes.cpuUsageColumnTitle', { + defaultMessage: 'CPU Usage', + }); + cols.push({ - title: i18n.translate('xpack.monitoring.elasticsearch.nodes.nameColumnTitle', { + name: i18n.translate('xpack.monitoring.elasticsearch.nodes.nameColumnTitle', { defaultMessage: 'Name', }), - sortKey: 'name', - sortOrder: SORT_ASCENDING + field: 'name', + sortable: true, + render: (value, node) => ( +
+
+ + + +   + + + {value} + + +
+
+ {extractIp(node.transport_address)} +
+
+ ) }); + cols.push({ - title: i18n.translate('xpack.monitoring.elasticsearch.nodes.statusColumnTitle', { + name: i18n.translate('xpack.monitoring.elasticsearch.nodes.statusColumnTitle', { defaultMessage: 'Status', }), - sortKey: 'isOnline' - }); - const cpuUsageColumnTitle = i18n.translate('xpack.monitoring.elasticsearch.nodes.cpuUsageColumnTitle', { - defaultMessage: 'CPU Usage', + field: 'isOnline', + sortable: true, + render: value => { + const status = value ? 'Online' : 'Offline'; + return ( +
+ {' '} + {status} +
+ ); + } }); + if (showCgroupMetricsElasticsearch) { cols.push({ - title: cpuUsageColumnTitle, - sortKey: 'node_cgroup_quota' + name: cpuUsageColumnTitle, + field: 'node_cgroup_quota', + sortable: true, + render: (value, node) => ( + + ) }); + cols.push({ - title: i18n.translate('xpack.monitoring.elasticsearch.nodes.cpuThrottlingColumnTitle', { + name: i18n.translate('xpack.monitoring.elasticsearch.nodes.cpuThrottlingColumnTitle', { defaultMessage: 'CPU Throttling', }), - sortKey: 'node_cgroup_throttled' + field: 'node_cgroup_throttled', + sortable: true, + render: (value, node) => ( + + ) }); } else { cols.push({ - title: cpuUsageColumnTitle, - sortKey: 'node_cpu_utilization' + name: cpuUsageColumnTitle, + field: 'node_cpu_utilization', + sortable: true, + render: (value, node) => ( + + ) }); + cols.push({ - title: i18n.translate('xpack.monitoring.elasticsearch.nodes.loadAverageColumnTitle', { + name: i18n.translate('xpack.monitoring.elasticsearch.nodes.loadAverageColumnTitle', { defaultMessage: 'Load Average', }), - sortKey: 'node_load_average' + field: 'node_load_average', + sortable: true, + render: (value, node) => ( + + ) }); } + cols.push({ - title: i18n.translate('xpack.monitoring.elasticsearch.nodes.jvmMemoryColumnTitle', { + name: i18n.translate('xpack.monitoring.elasticsearch.nodes.jvmMemoryColumnTitle', { defaultMessage: '{javaVirtualMachine} Memory', values: { javaVirtualMachine: 'JVM' } }), - sortKey: 'node_jvm_mem_percent' + field: 'node_jvm_mem_percent', + sortable: true, + render: (value, node) => ( + + ) }); + cols.push({ - title: i18n.translate('xpack.monitoring.elasticsearch.nodes.diskFreeSpaceColumnTitle', { + name: i18n.translate('xpack.monitoring.elasticsearch.nodes.diskFreeSpaceColumnTitle', { defaultMessage: 'Disk Free Space', }), - sortKey: 'node_free_space' + field: 'node_free_space', + sortable: true, + width: '300px', + render: (value, node) => ( + + ) }); + cols.push({ - title: i18n.translate('xpack.monitoring.elasticsearch.nodes.shardsColumnTitle', { + name: i18n.translate('xpack.monitoring.elasticsearch.nodes.shardsColumnTitle', { defaultMessage: 'Shards', }), - sortKey: 'shardCount' - }); - return cols; -}; - -const nodeRowFactory = showCgroupMetricsElasticsearch => { - return class NodeRow extends React.Component { - constructor(props) { - super(props); - } - - isOnline() { - return this.props.isOnline === true; - } - - getCpuComponents() { - const isOnline = this.isOnline(); - if (showCgroupMetricsElasticsearch) { - return [ - , - - ]; - } - return [ - , - - ]; - } - - getShardCount() { - if (this.isOnline()) { - return ( - -
- {get(this.props, 'shardCount')} -
-
- ); - } - return ; + field: 'shardCount', + sortable: true, + render: (value, node) => { + return node.isOnline ? ( +
+ {value} +
+ ) : ; } + }); - render() { - const isOnline = this.isOnline(); - const status = this.props.isOnline ? 'Online' : 'Offline'; - - return ( - - -
- - - -   - - - {this.props.name} - - -
-
- {extractIp(this.props.transport_address)} -
-
- -
- {' '} - {status} -
-
- {this.getCpuComponents()} - - - {this.getShardCount()} -
- ); - } - }; + return cols; }; function ElasticsearchNodesUI({ clusterStatus, nodes, showCgroupMetricsElasticsearch, intl, ...props }) { const columns = getColumns(showCgroupMetricsElasticsearch); + const { sorting, pagination, onTableChange } = props; return ( - - - - - + + + + + + + + + ); } diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/overview/overview.js b/x-pack/plugins/monitoring/public/components/elasticsearch/overview/overview.js index 55020955d00f4..3600f9713eae0 100644 --- a/x-pack/plugins/monitoring/public/components/elasticsearch/overview/overview.js +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/overview/overview.js @@ -4,11 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { Fragment } from 'react'; +import React from 'react'; import { ClusterStatus } from '../cluster_status'; import { ShardActivity } from '../shard_activity'; import { MonitoringTimeseriesContainer } from '../../chart'; -import { EuiPage, EuiFlexGrid, EuiFlexItem, EuiSpacer, EuiPageBody } from '@elastic/eui'; +import { EuiPage, EuiFlexGrid, EuiFlexItem, EuiSpacer, EuiPageBody, EuiPageContent } from '@elastic/eui'; export function ElasticsearchOverview({ clusterStatus, @@ -24,10 +24,11 @@ export function ElasticsearchOverview({ ]; return ( - - - - + + + + + {metricsToShow.map((metric, index) => ( @@ -40,8 +41,8 @@ export function ElasticsearchOverview({ ))} - - - + + + ); } diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/shard_activity/recovery_index.js b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_activity/recovery_index.js index 45c1a432a491d..58d55d7863ea0 100644 --- a/x-pack/plugins/monitoring/public/components/elasticsearch/shard_activity/recovery_index.js +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_activity/recovery_index.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { Fragment } from 'react'; +import React from 'react'; import { EuiLink } from '@elastic/eui'; import { Snapshot } from './snapshot'; import { FormattedMessage } from '@kbn/i18n/react'; @@ -13,7 +13,7 @@ export const RecoveryIndex = (props) => { const { name, shard, relocationType } = props; return ( - +
{name}
{
- +
); }; diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/shard_activity/shard_activity.js b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_activity/shard_activity.js index b41424bc6620f..c12b1ed59921c 100644 --- a/x-pack/plugins/monitoring/public/components/elasticsearch/shard_activity/shard_activity.js +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_activity/shard_activity.js @@ -6,13 +6,7 @@ import React, { Fragment } from 'react'; import { EuiText, EuiTitle, EuiLink, EuiSpacer, EuiSwitch } from '@elastic/eui'; -import { - KuiTableRowCell, - KuiTableRow, - KuiToolBarSection, - KuiToolBarText -} from '@kbn/ui-framework/components'; -import { MonitoringTable } from 'plugins/monitoring/components/table'; +import { EuiMonitoringTable } from 'plugins/monitoring/components/table'; import { RecoveryIndex } from './recovery_index'; import { TotalTime } from './total_time'; import { SourceDestination } from './source_destination'; @@ -23,89 +17,55 @@ import { FormattedMessage, injectI18n } from '@kbn/i18n/react'; const columns = [ { - title: i18n.translate('xpack.monitoring.kibana.shardActivity.indexTitle', { + name: i18n.translate('xpack.monitoring.kibana.shardActivity.indexTitle', { defaultMessage: 'Index' }), - sortKey: null + field: 'name', + render: (_name, shard) => }, { - title: i18n.translate('xpack.monitoring.kibana.shardActivity.stageTitle', { + name: i18n.translate('xpack.monitoring.kibana.shardActivity.stageTitle', { defaultMessage: 'Stage' }), - sortKey: null + field: 'stage' }, { - title: i18n.translate('xpack.monitoring.kibana.shardActivity.totalTimeTitle', { + name: i18n.translate('xpack.monitoring.kibana.shardActivity.totalTimeTitle', { defaultMessage: 'Total Time' }), - sortKey: null + field: null, + render: shard => }, { - title: i18n.translate('xpack.monitoring.kibana.shardActivity.sourceDestinationTitle', { + name: i18n.translate('xpack.monitoring.kibana.shardActivity.sourceDestinationTitle', { defaultMessage: 'Source / Destination' }), - sortKey: null + field: null, + render: shard => }, { - title: i18n.translate('xpack.monitoring.kibana.shardActivity.filesTitle', { + name: i18n.translate('xpack.monitoring.kibana.shardActivity.filesTitle', { defaultMessage: 'Files' }), - sortKey: null + field: null, + render: shard => }, { - title: i18n.translate('xpack.monitoring.kibana.shardActivity.bytesTitle', { + name: i18n.translate('xpack.monitoring.kibana.shardActivity.bytesTitle', { defaultMessage: 'Bytes' }), - sortKey: null + field: null, + render: shard => }, { - title: i18n.translate('xpack.monitoring.kibana.shardActivity.translogTitle', { + name: i18n.translate('xpack.monitoring.kibana.shardActivity.translogTitle', { defaultMessage: 'Translog' }), - sortKey: null + field: null, + render: shard => } ]; -const ActivityRow = props => ( - - - - - {props.stage} - - - - - - - - - - - - - - - - -); -const ToggleCompletedSwitch = ({ toggleHistory, showHistory }) => ( - - - - )} - onChange={toggleHistory} - checked={showHistory} - /> - - -); class ShardActivityUI extends React.Component { constructor(props) { @@ -146,18 +106,20 @@ class ShardActivityUI extends React.Component { render() { // data prop is an array of table row data, or null (which triggers no data message) - const { data: rawData } = this.props; + const { + data: rawData, + sorting, + pagination, + onTableChange, + toggleShardActivityHistory, + showShardActivityHistory + } = this.props; + if (rawData === null) { return null; } - const rows = rawData.map(parseProps); - const renderToolBarSection = props => ( - - ); + const rows = rawData.map(parseProps); return ( @@ -172,15 +134,27 @@ class ShardActivityUI extends React.Component { - + )} + onChange={toggleShardActivityHistory} + checked={showShardActivityHistory} + /> + + ); diff --git a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/_index.scss b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/_index.scss similarity index 100% rename from x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/_index.scss rename to x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/_index.scss diff --git a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/_shard_allocation.scss b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/_shard_allocation.scss similarity index 77% rename from x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/_shard_allocation.scss rename to x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/_shard_allocation.scss index 6ccb8f0796ee1..100075f50dba9 100644 --- a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/_shard_allocation.scss +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/_shard_allocation.scss @@ -80,44 +80,18 @@ monitoring-shard-allocation { .shard { align-self: center; padding: 5px 7px; - background-color: $euiColorPrimary; font: 10px sans-serif; border-left: 1px solid $euiColorEmptyShade; position: relative; - color: $euiColorGhost; .shard-tooltip { padding: 5px; bottom: 25px; left: 0; - background-color: $euiColorLightShade; position: absolute; - color: $euiColorDarkShade; border: 1px solid $euiColorLightShade; white-space: nowrap; } - - &.replica { - background-color: tintOrShade($euiColorPrimary, 15%, 15%); - } - - &.unassigned { - background-color: $euiColorMediumShade !important; - color: $euiColorFullShade; - } - - &.emergency { - background-color: $euiColorDanger !important; - color: $euiColorFullShade; - } - - &.relocating { - background-color: $euiColorVis3; - } - - &.initializing { - background-color: tintOrShade($euiColorVis3, 15%, 15%); - } } .legend { diff --git a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/components/assigned.js b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/components/assigned.js similarity index 94% rename from x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/components/assigned.js rename to x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/components/assigned.js index b63571806a570..ec1b36837af92 100644 --- a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/components/assigned.js +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/components/assigned.js @@ -9,8 +9,8 @@ import { get, sortBy } from 'lodash'; import React from 'react'; import { Shard } from './shard'; -import { calculateClass } from '../lib/calculateClass'; -import { generateQueryAndLink } from '../lib/generateQueryAndLink'; +import { calculateClass } from '../lib/calculate_class'; +import { generateQueryAndLink } from '../lib/generate_query_and_link'; import { EuiKeyboardAccessible, } from '@elastic/eui'; diff --git a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/components/clusterView.js b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/components/cluster_view.js similarity index 89% rename from x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/components/clusterView.js rename to x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/components/cluster_view.js index f9cf7d57ac1ac..8c85c40951777 100644 --- a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/components/clusterView.js +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/components/cluster_view.js @@ -7,8 +7,8 @@ import React from 'react'; -import { TableHead } from './tableHead'; -import { TableBody } from './tableBody'; +import { TableHead } from './table_head'; +import { TableBody } from './table_body'; import { i18n } from '@kbn/i18n'; export class ClusterView extends React.Component { @@ -24,7 +24,7 @@ export class ClusterView extends React.Component { this.state = { labels: props.scope.labels || [], showing: props.scope.showing || [], - shardStats: props.shardStats, + shardStats: props.scope.pageData.shardStats, showSystemIndices: props.showSystemIndices, toggleShowSystemIndices: props.toggleShowSystemIndices, angularChangeUrl: (url) => { @@ -45,7 +45,7 @@ export class ClusterView extends React.Component { componentWillMount() { this.props.scope.$watch('showing', this.setShowing); - this.props.scope.$watch('shardStats', this.setShardStats); + this.props.scope.$watch(() => this.props.scope.pageData.shardStats, this.setShardStats); } hasUnassigned = () => { diff --git a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/components/shard.js b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/components/shard.js similarity index 78% rename from x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/components/shard.js rename to x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/components/shard.js index ec41258263ed7..a0fcf36bb03c5 100644 --- a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/components/shard.js +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/components/shard.js @@ -7,9 +7,32 @@ import React from 'react'; -import { calculateClass } from '../lib/calculateClass'; +import { calculateClass } from '../lib/calculate_class'; import { vents } from '../lib/vents'; import { i18n } from '@kbn/i18n'; +import { EuiTextColor } from '@elastic/eui'; + +function getColor(classes) { + return classes.split(' ').reduce((color, cls) => { + if (color) { + return color; + } + + switch (cls) { + case 'primary': + return 'ghost'; + case 'replica': + return 'secondary'; + case 'relocation': + return 'accent'; + case 'initializing': + return 'default'; + case 'emergency': + case 'unassigned': + return 'danger'; + } + }, null); +} export class Shard extends React.Component { static displayName = i18n.translate('xpack.monitoring.elasticsearch.shardAllocation.shardDisplayName', { @@ -71,6 +94,7 @@ export class Shard extends React.Component { } const classes = calculateClass(shard); + const color = getColor(classes); const classification = classes + ' ' + shard.shard; // data attrs for automated testing verification @@ -83,7 +107,9 @@ export class Shard extends React.Component { data-shard-classification={classification} data-test-subj="shardIcon" > - {tooltip}{shard.shard} + + {tooltip}{shard.shard} +
); } diff --git a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/components/tableBody.js b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/components/table_body.js similarity index 100% rename from x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/components/tableBody.js rename to x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/components/table_body.js diff --git a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/components/tableHead.js b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/components/table_head.js similarity index 100% rename from x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/components/tableHead.js rename to x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/components/table_head.js diff --git a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/components/unassigned.js b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/components/unassigned.js similarity index 100% rename from x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/components/unassigned.js rename to x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/components/unassigned.js diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/index.js b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/index.js new file mode 100644 index 0000000000000..633c5c74f8b55 --- /dev/null +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/index.js @@ -0,0 +1,7 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export { ShardAllocation } from './shard_allocation'; diff --git a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/lib/calculateClass.js b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/lib/calculate_class.js similarity index 100% rename from x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/lib/calculateClass.js rename to x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/lib/calculate_class.js diff --git a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/lib/decorate_shards.js b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/lib/decorate_shards.js similarity index 100% rename from x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/lib/decorate_shards.js rename to x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/lib/decorate_shards.js diff --git a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/lib/decorate_shards.test.js b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/lib/decorate_shards.test.js similarity index 100% rename from x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/lib/decorate_shards.test.js rename to x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/lib/decorate_shards.test.js diff --git a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/lib/generateQueryAndLink.js b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/lib/generate_query_and_link.js similarity index 100% rename from x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/lib/generateQueryAndLink.js rename to x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/lib/generate_query_and_link.js diff --git a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/lib/hasPrimaryChildren.js b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/lib/has_primary_children.js similarity index 100% rename from x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/lib/hasPrimaryChildren.js rename to x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/lib/has_primary_children.js diff --git a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/lib/hasUnassigned.js b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/lib/has_unassigned.js similarity index 100% rename from x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/lib/hasUnassigned.js rename to x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/lib/has_unassigned.js diff --git a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/lib/labels.js b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/lib/labels.js similarity index 100% rename from x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/lib/labels.js rename to x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/lib/labels.js diff --git a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/lib/vents.js b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/lib/vents.js similarity index 100% rename from x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/lib/vents.js rename to x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/lib/vents.js diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/shard_allocation.js b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/shard_allocation.js new file mode 100644 index 0000000000000..50ab2653ced37 --- /dev/null +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/shard_allocation.js @@ -0,0 +1,91 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { EuiTitle, EuiBadge, EuiFlexGroup, EuiFlexItem, EuiSpacer } from '@elastic/eui'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { i18n } from '@kbn/i18n'; +import { ClusterView } from './components/cluster_view'; + +export const ShardAllocation = ({ + scope, + kbnUrl, + type, + shardStats, +}) => { + const types = [ + { + label: i18n.translate('xpack.monitoring.elasticsearch.shardAllocation.primaryLabel', { + defaultMessage: 'Primary' + }), + color: 'primary' + }, + { + label: i18n.translate('xpack.monitoring.elasticsearch.shardAllocation.replicaLabel', { + defaultMessage: 'Replica' + }), + color: 'secondary' + }, + { + label: i18n.translate('xpack.monitoring.elasticsearch.shardAllocation.relocatingLabel', { + defaultMessage: 'Relocating' + }), + color: 'accent' + }, + { + label: i18n.translate('xpack.monitoring.elasticsearch.shardAllocation.initializingLabel', { + defaultMessage: 'Initializing' + }), + color: 'default' + }, + { + label: i18n.translate('xpack.monitoring.elasticsearch.shardAllocation.unassignedPrimaryLabel', { + defaultMessage: 'Unassigned Primary' + }), + color: 'danger' + }, + { + label: i18n.translate('xpack.monitoring.elasticsearch.shardAllocation.unassignedReplicaLabel', { + defaultMessage: 'Unassigned Replica' + }), + color: 'warning' + }, + ]; + + return ( +
+ +

+ +

+
+ + + { + types.map(type => ( + + + {type.label} + + + )) + } + + + +
+ ); +}; diff --git a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/transformers/indices_by_nodes.js b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/transformers/indices_by_nodes.js similarity index 100% rename from x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/transformers/indices_by_nodes.js rename to x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/transformers/indices_by_nodes.js diff --git a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/transformers/nodes_by_indices.js b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/transformers/nodes_by_indices.js similarity index 97% rename from x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/transformers/nodes_by_indices.js rename to x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/transformers/nodes_by_indices.js index 30b674550550d..26ad4124c63a0 100644 --- a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/transformers/nodes_by_indices.js +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/shard_allocation/transformers/nodes_by_indices.js @@ -7,7 +7,7 @@ import _ from 'lodash'; -import { hasPrimaryChildren } from '../lib/hasPrimaryChildren'; +import { hasPrimaryChildren } from '../lib/has_primary_children'; import { decorateShards } from '../lib/decorate_shards'; export function nodesByIndices() { diff --git a/x-pack/plugins/monitoring/public/components/kibana/cluster_status/index.js b/x-pack/plugins/monitoring/public/components/kibana/cluster_status/index.js index 28b2dbbc87ca6..b1293fdd86388 100644 --- a/x-pack/plugins/monitoring/public/components/kibana/cluster_status/index.js +++ b/x-pack/plugins/monitoring/public/components/kibana/cluster_status/index.js @@ -28,7 +28,7 @@ function ClusterStatusUI({ stats, intl }) { defaultMessage: 'Instances' }), value: instances, - dataTestSubj: 'instances' + 'data-test-subj': 'instances' }, { label: intl.formatMessage({ @@ -36,7 +36,7 @@ function ClusterStatusUI({ stats, intl }) { defaultMessage: 'Memory' }), value: formatMetric(memSize, 'byte') + ' / ' + formatMetric(memLimit, 'byte'), - dataTestSubj: 'memory' + 'data-test-subj': 'memory' }, { label: intl.formatMessage({ @@ -44,7 +44,7 @@ function ClusterStatusUI({ stats, intl }) { defaultMessage: 'Requests' }), value: requests, - dataTestSubj: 'requests' + 'data-test-subj': 'requests' }, { label: intl.formatMessage({ @@ -52,7 +52,7 @@ function ClusterStatusUI({ stats, intl }) { defaultMessage: 'Connections' }), value: connections, - dataTestSubj: 'connections' + 'data-test-subj': 'connections' }, { label: intl.formatMessage({ @@ -60,7 +60,7 @@ function ClusterStatusUI({ stats, intl }) { defaultMessage: 'Max. Response Time' }), value: formatMetric(maxResponseTime, '0', 'ms'), - dataTestSubj: 'maxResponseTime' + 'data-test-subj': 'maxResponseTime' } ]; diff --git a/x-pack/plugins/monitoring/public/components/kibana/detail_status/index.js b/x-pack/plugins/monitoring/public/components/kibana/detail_status/index.js index b8b4cd2ce498b..0322f62591282 100644 --- a/x-pack/plugins/monitoring/public/components/kibana/detail_status/index.js +++ b/x-pack/plugins/monitoring/public/components/kibana/detail_status/index.js @@ -22,7 +22,7 @@ function DetailStatusUI({ stats, intl }) { const metrics = [ { value: transportAddress, - dataTestSubj: 'transportAddress' + 'data-test-subj': 'transportAddress' }, { label: intl.formatMessage({ @@ -30,7 +30,7 @@ function DetailStatusUI({ stats, intl }) { defaultMessage: 'OS Free Memory' }), value: formatMetric(osFreeMemory, 'byte'), - dataTestSubj: 'osFreeMemory' + 'data-test-subj': 'osFreeMemory' }, { label: intl.formatMessage({ @@ -38,7 +38,7 @@ function DetailStatusUI({ stats, intl }) { defaultMessage: 'Version' }), value: version, - dataTestSubj: 'version' + 'data-test-subj': 'version' }, { label: intl.formatMessage({ @@ -46,7 +46,7 @@ function DetailStatusUI({ stats, intl }) { defaultMessage: 'Uptime' }), value: formatMetric(uptime, 'time_since'), - dataTestSubj: 'uptime' + 'data-test-subj': 'uptime' } ]; diff --git a/x-pack/plugins/monitoring/public/components/logstash/cluster_status/index.js b/x-pack/plugins/monitoring/public/components/logstash/cluster_status/index.js index 2666924c9e0e8..e27d57d1a8ff0 100644 --- a/x-pack/plugins/monitoring/public/components/logstash/cluster_status/index.js +++ b/x-pack/plugins/monitoring/public/components/logstash/cluster_status/index.js @@ -24,28 +24,28 @@ function ClusterStatusUi({ stats, intl }) { id: 'xpack.monitoring.logstash.clusterStatus.nodesLabel', defaultMessage: 'Nodes' }), value: nodeCount, - dataTestSubj: 'node_count' + 'data-test-subj': 'node_count' }, { label: intl.formatMessage({ id: 'xpack.monitoring.logstash.clusterStatus.memoryLabel', defaultMessage: 'Memory' }), value: formatMetric(avgMemoryUsed, 'byte') + ' / ' + formatMetric(avgMemory, 'byte'), - dataTestSubj: 'memory_used' + 'data-test-subj': 'memory_used' }, { label: intl.formatMessage({ id: 'xpack.monitoring.logstash.clusterStatus.eventsReceivedLabel', defaultMessage: 'Events Received' }), value: formatMetric(eventsInTotal, '0.[0]a'), - dataTestSubj: 'events_in_total' + 'data-test-subj': 'events_in_total' }, { label: intl.formatMessage({ id: 'xpack.monitoring.logstash.clusterStatus.eventsEmittedLabel', defaultMessage: 'Events Emitted' }), value: formatMetric(eventsOutTotal, '0.[0]a'), - dataTestSubj: 'events_out_total' + 'data-test-subj': 'events_out_total' } ]; diff --git a/x-pack/plugins/monitoring/public/components/logstash/detail_status/index.js b/x-pack/plugins/monitoring/public/components/logstash/detail_status/index.js index c4ec3768dfc0b..ce95eac5a39ba 100644 --- a/x-pack/plugins/monitoring/public/components/logstash/detail_status/index.js +++ b/x-pack/plugins/monitoring/public/components/logstash/detail_status/index.js @@ -23,42 +23,42 @@ function DetailStatusUi({ stats, intl }) { const firstMetrics = [ { value: httpAddress, - dataTestSubj: 'httpAddress' + 'data-test-subj': 'httpAddress' }, { label: intl.formatMessage({ id: 'xpack.monitoring.logstash.detailStatus.eventsReceivedLabel', defaultMessage: 'Events Received' }), value: formatMetric(events.in, '0.[0]a'), - dataTestSubj: 'eventsIn' + 'data-test-subj': 'eventsIn' }, { label: intl.formatMessage({ id: 'xpack.monitoring.logstash.detailStatus.eventsEmittedLabel', defaultMessage: 'Events Emitted' }), value: formatMetric(events.out, '0.[0]a'), - dataTestSubj: 'eventsOut' + 'data-test-subj': 'eventsOut' }, { label: intl.formatMessage({ id: 'xpack.monitoring.logstash.detailStatus.configReloadsLabel', defaultMessage: 'Config Reloads' }), value: reloads.successes, - dataTestSubj: 'numReloads' + 'data-test-subj': 'numReloads' }, { label: intl.formatMessage({ id: 'xpack.monitoring.logstash.detailStatus.pipelineWorkersLabel', defaultMessage: 'Pipeline Workers' }), value: pipeline.workers, - dataTestSubj: 'pipelineWorkers' + 'data-test-subj': 'pipelineWorkers' }, { label: intl.formatMessage({ id: 'xpack.monitoring.logstash.detailStatus.batchSizeLabel', defaultMessage: 'Batch Size' }), value: pipeline.batch_size, - dataTestSubj: 'pipelineBatchSize' + 'data-test-subj': 'pipelineBatchSize' } ]; @@ -68,14 +68,14 @@ function DetailStatusUi({ stats, intl }) { id: 'xpack.monitoring.logstash.detailStatus.versionLabel', defaultMessage: 'Version' }), value: version, - dataTestSubj: 'version' + 'data-test-subj': 'version' }, { label: intl.formatMessage({ id: 'xpack.monitoring.logstash.detailStatus.uptimeLabel', defaultMessage: 'Uptime' }), value: formatMetric(uptime, 'time_since'), - dataTestSubj: 'uptime' + 'data-test-subj': 'uptime' } ]; @@ -87,7 +87,7 @@ function DetailStatusUi({ stats, intl }) { id: 'xpack.monitoring.logstash.detailStatus.queueTypeLabel', defaultMessage: 'Queue Type' }), value: queueType, - dataTestSubj: 'queueType' + 'data-test-subj': 'queueType' }); } metrics.push(...lastMetrics); diff --git a/x-pack/plugins/monitoring/public/components/summary_status/__snapshots__/summary_status.test.js.snap b/x-pack/plugins/monitoring/public/components/summary_status/__snapshots__/summary_status.test.js.snap index f55020e03f963..850ceed807382 100644 --- a/x-pack/plugins/monitoring/public/components/summary_status/__snapshots__/summary_status.test.js.snap +++ b/x-pack/plugins/monitoring/public/components/summary_status/__snapshots__/summary_status.test.js.snap @@ -2,249 +2,226 @@ exports[`Summary Status Component should allow label to be optional 1`] = `
-
+
-
-
-
-
- - 127.0.0.1:9300 - -
-
-
-
+ Status: +

+
+

+ Status: + -

-
- Documents: -
-
- - 24.8k - -
-
-
+ Status: yellow + +  Yellow +

+
+
+
+
+
+

+

+ 127.0.0.1:9300 +

+
+
-
- Status: - - Status: yellow - - -
-
- Yellow -
+

+ Documents: +

+

+ 24.8k +

+
`; exports[`Summary Status Component should allow status to be optional 1`] = `
-
+
-
-
-
- Free Disk Space: -
-
- - 173.9 GB - -
-
-
-
-
-
- Documents: -
-
- - 24.8k - -
-
-
+

+ Free Disk Space: +

+

+ 173.9 GB +

+
+
+ class="euiStat euiStat--leftAligned" + > +
+

+ Documents: +

+
+

+ 24.8k +

+
+
`; exports[`Summary Status Component should render metrics in a summary bar 1`] = `
-
+
-
-
-
- Free Disk Space: -
-
- - 173.9 GB - -
-
-
-
+ Status: +

+
+

+ Status: + -

-
- Documents: -
-
- - 24.8k - -
-
-
+ Status: green + +  Green +

+
+
+
+
+
+

+ Free Disk Space: +

+

+ 173.9 GB +

+
+
-
- Status: - - Status: green - - -
-
- Green -
+

+ Documents: +

+

+ 24.8k +

+
`; diff --git a/x-pack/plugins/monitoring/public/components/summary_status/summary_status.js b/x-pack/plugins/monitoring/public/components/summary_status/summary_status.js index 268500cb3fa5e..6aa649457c5cc 100644 --- a/x-pack/plugins/monitoring/public/components/summary_status/summary_status.js +++ b/x-pack/plugins/monitoring/public/components/summary_status/summary_status.js @@ -7,47 +7,29 @@ import React, { Fragment } from 'react'; import PropTypes from 'prop-types'; import { isEmpty, capitalize } from 'lodash'; -import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; +import { EuiFlexGroup, EuiFlexItem, EuiStat, EuiHorizontalRule } from '@elastic/eui'; import { StatusIcon } from '../status_icon/index.js'; -import { FormattedMessage } from '@kbn/i18n/react'; -import { i18n } from '@kbn/i18n'; -const wrapChild = ({ label, value, dataTestSubj }, index) => ( +const wrapChild = ({ label, value, ...props }, index) => ( - - - {label ? label + ': ' : null} - - - {value} - - + ); const DefaultIconComponent = ({ status }) => ( - - ) - }} - /> + Status: {( + + )} ); @@ -57,33 +39,34 @@ const StatusIndicator = ({ status, isOnline, IconComponent }) => { } return ( - - - {' '} - - - {capitalize(status)} - - + + + +   + {capitalize(status)} + + )} + titleSize="s" + textAlign="left" + description="Status:" + /> + ); }; -// eslint-disable-next-line no-unused-vars -export function SummaryStatus({ metrics, status, isOnline, IconComponent = DefaultIconComponent, intl, ...props }) { +export function SummaryStatus({ metrics, status, isOnline, IconComponent = DefaultIconComponent, ...props }) { return ( -
-
- - - - {metrics.map(wrapChild)} - - - - - - -
+
+ + + {metrics.map(wrapChild)} + +
); } diff --git a/x-pack/plugins/monitoring/public/components/summary_status/summary_status.test.js b/x-pack/plugins/monitoring/public/components/summary_status/summary_status.test.js index d66c1dd54619c..e48921d4e16f1 100644 --- a/x-pack/plugins/monitoring/public/components/summary_status/summary_status.test.js +++ b/x-pack/plugins/monitoring/public/components/summary_status/summary_status.test.js @@ -15,12 +15,12 @@ describe('Summary Status Component', () => { { label: 'Free Disk Space', value: '173.9 GB', - dataTestSubj: 'freeDiskSpace' + 'data-test-subj': 'freeDiskSpace' }, { label: 'Documents', value: '24.8k', - dataTestSubj: 'documentCount' + 'data-test-subj': 'documentCount' }, ], status: 'green' @@ -34,12 +34,12 @@ describe('Summary Status Component', () => { metrics: [ { value: '127.0.0.1:9300', - dataTestSubj: 'transportAddress' + 'data-test-subj': 'transportAddress' }, { label: 'Documents', value: '24.8k', - dataTestSubj: 'documentCount' + 'data-test-subj': 'documentCount' }, ], status: 'yellow' @@ -54,12 +54,12 @@ describe('Summary Status Component', () => { { label: 'Free Disk Space', value: '173.9 GB', - dataTestSubj: 'freeDiskSpace' + 'data-test-subj': 'freeDiskSpace' }, { label: 'Documents', value: '24.8k', - dataTestSubj: 'documentCount' + 'data-test-subj': 'documentCount' }, ] }; diff --git a/x-pack/plugins/monitoring/public/directives/all.js b/x-pack/plugins/monitoring/public/directives/all.js index ad101f43a903d..4aca3c22fd8af 100644 --- a/x-pack/plugins/monitoring/public/directives/all.js +++ b/x-pack/plugins/monitoring/public/directives/all.js @@ -13,8 +13,6 @@ import './elasticsearch/cluster_status'; import './elasticsearch/index_summary'; import './elasticsearch/node_summary'; import './elasticsearch/ml_job_listing'; -import './elasticsearch/shard_allocation'; -import './elasticsearch/shard_allocation/directives/clusterView'; import './logstash/cluster_status'; import './logstash/listing'; import './logstash/node_summary'; diff --git a/x-pack/plugins/monitoring/public/directives/cluster/listing/index.js b/x-pack/plugins/monitoring/public/directives/cluster/listing/index.js index c4d2e0bf46d62..f7ce4592a78a7 100644 --- a/x-pack/plugins/monitoring/public/directives/cluster/listing/index.js +++ b/x-pack/plugins/monitoring/public/directives/cluster/listing/index.js @@ -6,408 +6,403 @@ import React, { Fragment } from 'react'; import { render } from 'react-dom'; -import { capitalize, get } from 'lodash'; +import { capitalize, partial } from 'lodash'; import moment from 'moment'; import numeral from '@elastic/numeral'; import { uiModules } from 'ui/modules'; import chrome from 'ui/chrome'; -import { - KuiTableRowCell, - KuiTableRow -} from '@kbn/ui-framework/components'; import { EuiHealth, EuiLink, + EuiPage, + EuiPageBody, + EuiPageContent, } from '@elastic/eui'; import { toastNotifications } from 'ui/notify'; -import { MonitoringTable } from 'plugins/monitoring/components/table'; +import { EuiMonitoringTable } from 'plugins/monitoring/components/table'; import { Tooltip } from 'plugins/monitoring/components/tooltip'; import { AlertsIndicator } from 'plugins/monitoring/components/cluster/listing/alerts_indicator'; -import { SORT_ASCENDING } from '../../../../common/constants'; import { I18nProvider, FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; -const filterFields = [ 'cluster_name', 'status', 'license.type' ]; -const columns = [ - { - title: i18n.translate('xpack.monitoring.cluster.listing.nameColumnTitle', { - defaultMessage: 'Name', - }), - sortKey: 'cluster_name', sortOrder: SORT_ASCENDING - }, - { - title: i18n.translate('xpack.monitoring.cluster.listing.statusColumnTitle', { - defaultMessage: 'Status', - }), - sortKey: 'status' - }, - { - title: i18n.translate('xpack.monitoring.cluster.listing.nodesColumnTitle', { - defaultMessage: 'Nodes', - }), - sortKey: 'elasticsearch.cluster_stats.nodes.count.total' - }, - { - title: i18n.translate('xpack.monitoring.cluster.listing.indicesColumnTitle', { - defaultMessage: 'Indices', - }), - sortKey: 'elasticsearch.cluster_stats.indices.count' - }, - { - title: i18n.translate('xpack.monitoring.cluster.listing.dataColumnTitle', { - defaultMessage: 'Data', - }), - sortKey: 'elasticsearch.cluster_stats.indices.store.size_in_bytes' - }, - { - title: i18n.translate('xpack.monitoring.cluster.listing.logstashColumnTitle', { - defaultMessage: 'Logstash', - }), - sortKey: 'logstash.node_count' - }, - { - title: i18n.translate('xpack.monitoring.cluster.listing.kibanaColumnTitle', { - defaultMessage: 'Kibana', - }), - sortKey: 'kibana.count' - }, - { - title: i18n.translate('xpack.monitoring.cluster.listing.licenseColumnTitle', { - defaultMessage: 'License', - }), - sortKey: 'license.type' - } -]; - -const clusterRowFactory = (scope, globalState, kbnUrl, showLicenseExpiration) => { - return class ClusterRow extends React.Component { - constructor(props) { - super(props); - } - - changeCluster() { - scope.$evalAsync(() => { - globalState.cluster_uuid = this.props.cluster_uuid; - globalState.ccs = this.props.ccs; - globalState.save(); - kbnUrl.changePath('/overview'); - }); - } - - licenseWarning({ title, text }) { - scope.$evalAsync(() => { - toastNotifications.addWarning({ title, text, 'data-test-subj': 'monitoringLicenseWarning' }); - }); - } +const IsClusterSupported = ({ isSupported, children }) => { + return isSupported ? children : '-'; +}; - handleClickIncompatibleLicense() { - this.licenseWarning({ - title: ( - - ), - text: ( - -

- -

-

- - - - ) - }} - /> -

-
- ), - }); - } +/* + * This checks if alerts feature is supported via monitoring cluster + * license. If the alerts feature is not supported because the prod cluster + * license is basic, IsClusterSupported makes the status col hidden + * completely + */ +const IsAlertsSupported = (props) => { + const { + alertsMeta = { enabled: true }, + clusterMeta = { enabled: true } + } = props.cluster.alerts; + if (alertsMeta.enabled && clusterMeta.enabled) { + return { props.children }; + } - handleClickInvalidLicense() { - const licensingPath = `${chrome.getBasePath()}/app/kibana#/management/elasticsearch/license_management/home`; + const message = alertsMeta.message || clusterMeta.message; + return ( + + + N/A + + + ); +}; - this.licenseWarning({ - title: ( - - ), - text: ( - -

- -

-

- - - - ), - getLicenseInfoLink: ( - - - - ) - }} - /> -

-
- ), - }); - } +const getColumns = ( + showLicenseExpiration, + changeCluster, + handleClickIncompatibleLicense, + handleClickInvalidLicense +) => { + return [ + { + name: i18n.translate('xpack.monitoring.cluster.listing.nameColumnTitle', { + defaultMessage: 'Name', + }), + field: 'cluster_name', + sortable: true, + render: (value, cluster) => { + if (cluster.isSupported) { + return ( + changeCluster(cluster.cluster_uuid, cluster.ccs)} + data-test-subj="clusterLink" + > + { value } + + ); + } - getClusterAction() { - if (this.props.isSupported) { - return ( - - { this.props.cluster_name } - - ); - } + // not supported because license is basic/not compatible with multi-cluster + if (cluster.license) { + return ( + handleClickIncompatibleLicense(cluster.cluster_name)} + data-test-subj="clusterLink" + > + { value } + + ); + } - // not supported because license is basic/not compatible with multi-cluster - if (this.props.license) { + // not supported because license is invalid return ( handleClickInvalidLicense(cluster.cluster_name)} data-test-subj="clusterLink" > - { this.props.cluster_name } + { value } ); } + }, + { + name: i18n.translate('xpack.monitoring.cluster.listing.statusColumnTitle', { + defaultMessage: 'Status', + }), + field: 'status', + 'data-test-subj': 'alertsStatus', + sortable: true, + render: (_status, cluster) => ( + + + + + + ) + }, + { + name: i18n.translate('xpack.monitoring.cluster.listing.nodesColumnTitle', { + defaultMessage: 'Nodes', + }), + field: 'elasticsearch.cluster_stats.nodes.count.total', + 'data-test-subj': 'nodesCount', + sortable: true, + render: (total, cluster) => ( + + { numeral(total).format('0,0') } + + ) + }, + { + name: i18n.translate('xpack.monitoring.cluster.listing.indicesColumnTitle', { + defaultMessage: 'Indices', + }), + field: 'elasticsearch.cluster_stats.indices.count', + 'data-test-subj': 'indicesCount', + sortable: true, + render: (count, cluster) => ( + + { numeral(count).format('0,0') } + + ) + }, + { + name: i18n.translate('xpack.monitoring.cluster.listing.dataColumnTitle', { + defaultMessage: 'Data', + }), + field: 'elasticsearch.cluster_stats.indices.store.size_in_bytes', + 'data-test-subj': 'dataSize', + sortable: true, + render: (size, cluster) => ( + + { numeral(size).format('0,0[.]0 b')} + + ) + }, + { + name: i18n.translate('xpack.monitoring.cluster.listing.logstashColumnTitle', { + defaultMessage: 'Logstash', + }), + field: 'logstash.node_count', + 'data-test-subj': 'logstashCount', + sortable: true, + render: (count, cluster) => ( + + { numeral(count).format('0,0') } + + ) + }, + { + name: i18n.translate('xpack.monitoring.cluster.listing.kibanaColumnTitle', { + defaultMessage: 'Kibana', + }), + field: 'kibana.count', + 'data-test-subj': 'kibanaCount', + sortable: true, + render: (count, cluster) => ( + + { numeral(count).format('0,0') } + + ) + }, + { + name: i18n.translate('xpack.monitoring.cluster.listing.licenseColumnTitle', { + defaultMessage: 'License', + }), + field: 'license.type', + 'data-test-subj': 'clusterLicense', + sortable: true, + render: (licenseType, cluster) => { + const license = cluster.license; + if (license) { + const licenseExpiry = () => { + if (license.expiry_date_in_millis < moment().valueOf()) { + // license is expired + return ( + + Expired + + ); + } - // not supported because license is invalid - return ( - - { this.props.cluster_name } - - ); - } - - getLicenseInfo() { - if (this.props.license) { - const licenseExpiry = () => { - if (this.props.license.expiry_date_in_millis < moment().valueOf()) { - // license is expired + // license is fine return ( - - + + Expires { moment(license.expiry_date_in_millis).format('D MMM YY') } ); - } + }; - // license is fine return ( - - - +
+
+ { capitalize(licenseType) } +
+
+ { showLicenseExpiration ? licenseExpiry() : null } +
+
); - }; + } + // there is no license! return ( -
-
- { capitalize(this.props.license.type) } -
-
- { showLicenseExpiration ? licenseExpiry() : null } -
-
+ handleClickInvalidLicense(cluster.cluster_name)} + > + + N/A + + ); } - - // there is no license! - return ( - - - - - - ); } + ]; +}; - render() { - const isSupported = this.props.isSupported; - const isClusterSupportedFactory = () => { - return (props) => { - if (isSupported) { - return { props.children }; - } - return -; - }; - }; - const IsClusterSupported = isClusterSupportedFactory(isSupported); - const classes = []; - if (!isSupported) { - classes.push('basic'); - } +const changeCluster = (scope, globalState, kbnUrl, clusterUuid, ccs) => { + scope.$evalAsync(() => { + globalState.cluster_uuid = clusterUuid; + globalState.ccs = ccs; + globalState.save(); + kbnUrl.changePath('/overview'); + }); +}; - /* - * This checks if alerts feature is supported via monitoring cluster - * license. If the alerts feature is not supported because the prod cluster - * license is basic, IsClusterSupported makes the status col hidden - * completely - */ - const IsAlertsSupported = (props) => { - const { - alertsMeta = { enabled: true }, - clusterMeta = { enabled: true } - } = props.cluster.alerts; - if (alertsMeta.enabled && clusterMeta.enabled) { - return { props.children }; - } +const licenseWarning = (scope, { title, text }) => { + scope.$evalAsync(() => { + toastNotifications.addWarning({ title, text, 'data-test-subj': 'monitoringLicenseWarning' }); + }); +}; - const message = alertsMeta.message || clusterMeta.message; - return ( - - - - - - ); - }; +const handleClickIncompatibleLicense = (scope, clusterName) => { + licenseWarning(scope, { + title: ( + + ), + text: ( + +

+ +

+

+ + + + ) + }} + /> +

+
+ ), + }); +}; - return ( - - - - { this.getClusterAction() } - - - - - - - - - - - - { numeral(get(this.props, 'elasticsearch.cluster_stats.nodes.count.total')).format('0,0') } - - - - - { numeral(get(this.props, 'elasticsearch.cluster_stats.indices.count')).format('0,0') } - - - - - { numeral(get(this.props, 'elasticsearch.cluster_stats.indices.store.size_in_bytes')).format('0,0[.]0 b') } - - - - - { numeral(get(this.props, 'logstash.node_count')).format('0,0') } - - - - - { numeral(get(this.props, 'kibana.count')).format('0,0') } - - - - { this.getLicenseInfo() } - - - ); - } +const handleClickInvalidLicense = (scope, clusterName) => { + const licensingPath = `${chrome.getBasePath()}/app/kibana#/management/elasticsearch/license_management/home`; - }; + licenseWarning(scope, { + title: ( + + ), + text: ( + +

+ +

+

+ + + + ), + getLicenseInfoLink: ( + + + + ) + }} + /> +

+
+ ), + }); }; const uiModule = uiModules.get('monitoring/directives', []); -uiModule.directive('monitoringClusterListing', ($injector, i18n) => { +uiModule.directive('monitoringClusterListing', ($injector) => { return { restrict: 'E', scope: { clusters: '=', - pageIndex: '=', + sorting: '=', filterText: '=', - sortKey: '=', - sortOrder: '=', - onNewState: '=', + paginationSettings: '=pagination', + onTableChange: '=', }, link(scope, $el) { const globalState = $injector.get('globalState'); const kbnUrl = $injector.get('kbnUrl'); const showLicenseExpiration = $injector.get('showLicenseExpiration'); - const filterClustersPlaceholder = i18n('xpack.monitoring.cluster.listing.filterClustersPlaceholder', - { defaultMessage: 'Filter Clusters…' } - ); + + const _changeCluster = partial(changeCluster, scope, globalState, kbnUrl); + const _handleClickIncompatibleLicense = partial(handleClickIncompatibleLicense, scope); + const _handleClickInvalidLicense = partial(handleClickInvalidLicense, scope); + + const { sorting, pagination, onTableChange } = scope; scope.$watch('clusters', (clusters = []) => { const clusterTable = ( - + + + + { + return { + 'data-test-subj': `clusterRow_${item.cluster_uuid}` + }; + }} + sorting={{ + ...sorting, + sort: { + ...sorting.sort, + field: 'cluster_name' + } + }} + pagination={pagination} + search={{ + box: { + incremental: true, + placeholder: scope.filterText + }, + }} + onTableChange={onTableChange} + /> + + + ); render(clusterTable, $el[0]); diff --git a/x-pack/plugins/monitoring/public/directives/elasticsearch/ml_job_listing/index.js b/x-pack/plugins/monitoring/public/directives/elasticsearch/ml_job_listing/index.js index 2fac710fef7f4..bb63dc321627d 100644 --- a/x-pack/plugins/monitoring/public/directives/elasticsearch/ml_job_listing/index.js +++ b/x-pack/plugins/monitoring/public/directives/elasticsearch/ml_job_listing/index.js @@ -9,150 +9,156 @@ import numeral from '@elastic/numeral'; import React from 'react'; import { render } from 'react-dom'; import { uiModules } from 'ui/modules'; -import { - KuiTableRowCell, - KuiTableRow -} from '@kbn/ui-framework/components'; -import { MonitoringTable } from 'plugins/monitoring/components/table'; +import { EuiMonitoringTable } from 'plugins/monitoring/components/table'; import { MachineLearningJobStatusIcon } from 'plugins/monitoring/components/elasticsearch/ml_job_listing/status_icon'; -import { SORT_ASCENDING } from '../../../../common/constants'; import { LARGE_ABBREVIATED, LARGE_BYTES } from '../../../../common/formatting'; import { EuiLink, + EuiPage, + EuiPageContent, + EuiPageBody, } from '@elastic/eui'; +import { ClusterStatus } from '../../../components/elasticsearch/cluster_status'; import { i18n } from '@kbn/i18n'; -import { I18nProvider } from '@kbn/i18n/react'; +import { I18nProvider, FormattedMessage } from '@kbn/i18n/react'; -const filterFields = [ 'job_id', 'state', 'node.name' ]; -const columns = [ +const getColumns = (kbnUrl, scope) => ([ { - title: i18n.translate('xpack.monitoring.elasticsearch.mlJobListing.jobIdTitle', { + name: i18n.translate('xpack.monitoring.elasticsearch.mlJobListing.jobIdTitle', { defaultMessage: 'Job ID' }), - sortKey: 'job_id', - sortOrder: SORT_ASCENDING + field: 'job_id', + sortable: true }, { - title: i18n.translate('xpack.monitoring.elasticsearch.mlJobListing.stateTitle', { + name: i18n.translate('xpack.monitoring.elasticsearch.mlJobListing.stateTitle', { defaultMessage: 'State' }), - sortKey: 'state' + field: 'state', + sortable: true, + render: state => ( +
+   + { capitalize(state) } +
+ ) }, { - title: i18n.translate('xpack.monitoring.elasticsearch.mlJobListing.processedRecordsTitle', { + name: i18n.translate('xpack.monitoring.elasticsearch.mlJobListing.processedRecordsTitle', { defaultMessage: 'Processed Records' }), - sortKey: 'data_counts.processed_record_count' + field: 'data_counts.processed_record_count', + sortable: true, + render: value => ( + + {numeral(value).format(LARGE_ABBREVIATED)} + + ) }, { - title: i18n.translate('xpack.monitoring.elasticsearch.mlJobListing.modelSizeTitle', { + name: i18n.translate('xpack.monitoring.elasticsearch.mlJobListing.modelSizeTitle', { defaultMessage: 'Model Size' }), - sortKey: 'model_size_stats.model_bytes' + field: 'model_size_stats.model_bytes', + sortable: true, + render: value => ( + + {numeral(value).format(LARGE_BYTES)} + + ) }, { - title: i18n.translate('xpack.monitoring.elasticsearch.mlJobListing.forecastsTitle', { + name: i18n.translate('xpack.monitoring.elasticsearch.mlJobListing.forecastsTitle', { defaultMessage: 'Forecasts' }), - sortKey: 'forecasts_stats.total' + field: 'forecasts_stats.total', + sortable: true, + render: value => ( + + {numeral(value).format(LARGE_ABBREVIATED)} + + ) }, { - title: i18n.translate('xpack.monitoring.elasticsearch.mlJobListing.nodeTitle', { + name: i18n.translate('xpack.monitoring.elasticsearch.mlJobListing.nodeTitle', { defaultMessage: 'Node' }), - sortKey: 'node.name' - } -]; -const jobRowFactory = (scope, kbnUrl) => { - const goToNode = nodeId => { - scope.$evalAsync(() => kbnUrl.changePath(`/elasticsearch/nodes/${nodeId}`)); - }; - const getNode = node => { - if (node) { + field: 'node.name', + sortable: true, + render: (name, node) => { + if (node) { + return ( + { + scope.$evalAsync(() => kbnUrl.changePath(`/elasticsearch/nodes/${node.id}`)); + }} + > + { name } + + ); + } + return ( - - { node.name } - + ); } - return i18n.translate('xpack.monitoring.elasticsearch.mlJobListing.noDataLabel', { - defaultMessage: 'N/A' - }); - }; - - return function JobRow(props) { - return ( - - { props.job_id } - -   - { capitalize(props.state) } - - { numeral(props.data_counts.processed_record_count).format(LARGE_ABBREVIATED) } - { numeral(props.model_size_stats.model_bytes).format(LARGE_BYTES) } - { numeral(props.forecasts_stats.total).format(LARGE_ABBREVIATED) } - - { getNode(props.node) } - - - ); - }; -}; + } +]); const uiModule = uiModules.get('monitoring/directives', []); -uiModule.directive('monitoringMlListing', (kbnUrl, i18n) => { +uiModule.directive('monitoringMlListing', kbnUrl => { return { restrict: 'E', scope: { jobs: '=', - pageIndex: '=', - filterText: '=', - sortKey: '=', - sortOrder: '=', - onNewState: '=', + paginationSettings: '=', + sorting: '=', + onTableChange: '=', + status: '=', }, link(scope, $el) { + const columns = getColumns(kbnUrl, scope); - const getNoDataMessage = filterText => { - if (filterText) { - return ( - i18n('xpack.monitoring.elasticsearch.mlJobListing.noFilteredJobsDescription', { - // eslint-disable-next-line max-len - defaultMessage: 'There are no Machine Learning Jobs that match the filter [{filterText}] or the time range. Try changing the filter or time range.', - values: { - filterText: filterText.trim() - } - }) - ); - } - return i18n('xpack.monitoring.elasticsearch.mlJobListing.noJobsDescription', { - defaultMessage: 'There are no Machine Learning Jobs that match your query. Try changing the time range selection.' - }); - }; - - const filterJobsPlaceholder = i18n('xpack.monitoring.elasticsearch.mlJobListing.filterJobsPlaceholder', { + const filterJobsPlaceholder = i18n.translate('xpack.monitoring.elasticsearch.mlJobListing.filterJobsPlaceholder', { defaultMessage: 'Filter Jobs…' }); scope.$watch('jobs', (jobs = []) => { const mlTable = ( - + + + + + + + + ); render(mlTable, $el[0]); diff --git a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/directives/clusterView.js b/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/directives/clusterView.js deleted file mode 100644 index 83e052c3f5b52..0000000000000 --- a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/directives/clusterView.js +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - - - -import React from 'react'; -import ReactDOM from 'react-dom'; -import { ClusterView } from '../components/clusterView'; -import { uiModules } from 'ui/modules'; -import { I18nProvider } from '@kbn/i18n/react'; - -const uiModule = uiModules.get('monitoring/directives', []); -uiModule.directive('clusterView', kbnUrl => { - return { - restrict: 'E', - scope: { - totalCount: '=', - filter: '=', - showing: '=', - labels: '=', - shardStats: '=', - showSystemIndices: '=', - toggleShowSystemIndices: '=' - }, - link: function (scope, element) { - ReactDOM.render( - - - , - element[0] - ); - } - }; -}); diff --git a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/index.html b/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/index.html deleted file mode 100644 index f62b70882e90f..0000000000000 --- a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/index.html +++ /dev/null @@ -1,57 +0,0 @@ -
-
-

-
-   - -   - -   - -   - -   - -   - -
- -
-
diff --git a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/index.js b/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/index.js deleted file mode 100644 index 665c19eb1c391..0000000000000 --- a/x-pack/plugins/monitoring/public/directives/elasticsearch/shard_allocation/index.js +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { uiModules } from 'ui/modules'; -import { labels } from './lib/labels'; -import { indicesByNodes } from './transformers/indices_by_nodes'; -import { nodesByIndices } from './transformers/nodes_by_indices'; -import template from './index.html'; - -const uiModule = uiModules.get('monitoring/directives', []); -uiModule.directive('monitoringShardAllocation', () => { - return { - restrict: 'E', - template, - scope: { - view: '@', - shards: '=', - nodes: '=', - shardStats: '=', - showSystemIndices: '=', - toggleShowSystemIndices: '=' - }, - link: (scope) => { - - const isIndexView = scope.view === 'index'; - const transformer = (isIndexView) ? indicesByNodes() : nodesByIndices(); - - scope.isIndexView = isIndexView; - - scope.$watch('shards', (shards) => { - let view = scope.view; - scope.totalCount = shards.length; - scope.showing = transformer(shards, scope.nodes); - if (isIndexView && shards.some((shard) => shard.state === 'UNASSIGNED')) { - view = 'indexWithUnassigned'; - } - scope.labels = labels[view]; - }); - - } - }; -}); diff --git a/x-pack/plugins/monitoring/public/index.scss b/x-pack/plugins/monitoring/public/index.scss index 67974b71cd72f..24a577aa0901d 100644 --- a/x-pack/plugins/monitoring/public/index.scss +++ b/x-pack/plugins/monitoring/public/index.scss @@ -20,4 +20,4 @@ @import 'components/table/index'; @import 'components/logstash/pipeline_viewer/views/index'; @import 'directives/chart/index'; -@import 'directives/elasticsearch/shard_allocation/index'; +@import 'components/elasticsearch/shard_allocation/index'; diff --git a/x-pack/plugins/monitoring/public/views/base_eui_table_controller.js b/x-pack/plugins/monitoring/public/views/base_eui_table_controller.js index c4f2ada58dff9..dfc548aeb97f2 100644 --- a/x-pack/plugins/monitoring/public/views/base_eui_table_controller.js +++ b/x-pack/plugins/monitoring/public/views/base_eui_table_controller.js @@ -6,7 +6,7 @@ import { MonitoringViewBaseController } from './'; import { euiTableStorageGetter, euiTableStorageSetter } from 'plugins/monitoring/components/table'; -import { SORT_ASCENDING } from '../../common/constants'; +import { EUI_SORT_ASCENDING } from '../../common/constants'; /** * Class to manage common instantiation behaviors in a view controller @@ -50,7 +50,7 @@ export class MonitoringViewBaseEuiTableController extends MonitoringViewBaseCont this.sorting = sort || { sort: { field: 'name', - direction: SORT_ASCENDING + direction: EUI_SORT_ASCENDING } }; diff --git a/x-pack/plugins/monitoring/public/views/cluster/listing/index.html b/x-pack/plugins/monitoring/public/views/cluster/listing/index.html index 5030a67fe3ec5..4335a2fa282cf 100644 --- a/x-pack/plugins/monitoring/public/views/cluster/listing/index.html +++ b/x-pack/plugins/monitoring/public/views/cluster/listing/index.html @@ -1,18 +1,8 @@ -
-

-

- -
+
diff --git a/x-pack/plugins/monitoring/public/views/cluster/listing/index.js b/x-pack/plugins/monitoring/public/views/cluster/listing/index.js index 1ac9c633937d8..36bdb06da9fc0 100644 --- a/x-pack/plugins/monitoring/public/views/cluster/listing/index.js +++ b/x-pack/plugins/monitoring/public/views/cluster/listing/index.js @@ -6,7 +6,7 @@ import uiRoutes from 'ui/routes'; import { routeInitProvider } from 'plugins/monitoring/lib/route_init'; -import { MonitoringViewBaseTableController } from '../../'; +import { MonitoringViewBaseEuiTableController } from '../../'; import template from './index.html'; const getPageData = $injector => { @@ -35,7 +35,7 @@ uiRoutes.when('/home', { } }, controllerAs: 'clusters', - controller: class ClustersList extends MonitoringViewBaseTableController { + controller: class ClustersList extends MonitoringViewBaseEuiTableController { constructor($injector, $scope) { super({ diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/index/advanced/index.html b/x-pack/plugins/monitoring/public/views/elasticsearch/index/advanced/index.html index 72c1b450dd640..2abb73d52adb6 100644 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/index/advanced/index.html +++ b/x-pack/plugins/monitoring/public/views/elasticsearch/index/advanced/index.html @@ -4,21 +4,5 @@ resolver="{{ indexName }}" page="advanced" > - - -
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/index/advanced/index.js b/x-pack/plugins/monitoring/public/views/elasticsearch/index/advanced/index.js index c011e8540c5f1..8f575b7809e73 100644 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/index/advanced/index.js +++ b/x-pack/plugins/monitoring/public/views/elasticsearch/index/advanced/index.js @@ -7,12 +7,17 @@ /** * Controller for Advanced Index Detail */ +import React from 'react'; +import { render } from 'react-dom'; import { find } from 'lodash'; import uiRoutes from 'ui/routes'; import { ajaxErrorHandlersProvider } from 'plugins/monitoring/lib/ajax_error_handler'; import { routeInitProvider } from 'plugins/monitoring/lib/route_init'; import template from './index.html'; import { timefilter } from 'ui/timefilter'; +import { AdvancedIndex } from '../../../../components/elasticsearch/index/advanced'; +import { I18nProvider } from '@kbn/i18n/react'; +import moment from 'moment'; function getPageData($injector) { const globalState = $injector.get('globalState'); @@ -75,5 +80,28 @@ uiRoutes.when('/elasticsearch/indices/:index/advanced', { $executor.start($scope); $scope.$on('$destroy', $executor.destroy); + + function onBrush({ xaxis }) { + timefilter.setTime({ + from: moment(xaxis.from), + to: moment(xaxis.to), + mode: 'absolute', + }); + } + + this.renderReact = () => { + render( + + + , + document.getElementById('monitoringElasticsearchAdvancedIndexApp') + ); + }; + + $scope.$watch('pageData', this.renderReact); } }); diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/index/index.html b/x-pack/plugins/monitoring/public/views/elasticsearch/index/index.html index d7c201da9d0dd..87bdcd5c16037 100644 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/index/index.html +++ b/x-pack/plugins/monitoring/public/views/elasticsearch/index/index.html @@ -5,24 +5,5 @@ resolver="{{ indexName }}" page="overview" > - - -
-
-
-
-
-
-
-
-
-
- - +
diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/index/index.js b/x-pack/plugins/monitoring/public/views/elasticsearch/index/index.js index 12b2e961ceea9..7727239906af0 100644 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/index/index.js +++ b/x-pack/plugins/monitoring/public/views/elasticsearch/index/index.js @@ -7,12 +7,19 @@ /** * Controller for single index detail */ +import React from 'react'; +import { render } from 'react-dom'; import { find } from 'lodash'; +import moment from 'moment'; import uiRoutes from 'ui/routes'; import { routeInitProvider } from 'plugins/monitoring/lib/route_init'; import { ajaxErrorHandlersProvider } from 'plugins/monitoring/lib/ajax_error_handler'; import template from './index.html'; import { timefilter } from 'ui/timefilter'; +import { I18nProvider } from '@kbn/i18n/react'; +import { labels } from '../../../components/elasticsearch/shard_allocation/lib/labels'; +import { indicesByNodes } from '../../../components/elasticsearch/shard_allocation/transformers/indices_by_nodes'; +import { Index } from '../../../components/elasticsearch/index/index'; function getPageData($injector) { const $http = $injector.get('$http'); @@ -51,6 +58,7 @@ uiRoutes.when('/elasticsearch/indices/:index', { timefilter.enableAutoRefreshSelector(); const $route = $injector.get('$route'); + const kbnUrl = $injector.get('kbnUrl'); const globalState = $injector.get('globalState'); $scope.cluster = find($route.current.locals.clusters, { cluster_uuid: globalState.cluster_uuid }); $scope.pageData = $route.current.locals.pageData; @@ -75,5 +83,39 @@ uiRoutes.when('/elasticsearch/indices/:index', { $executor.start($scope); $scope.$on('$destroy', $executor.destroy); + + function onBrush({ xaxis }) { + timefilter.setTime({ + from: moment(xaxis.from), + to: moment(xaxis.to), + mode: 'absolute', + }); + } + + const transformer = indicesByNodes(); + this.renderReact = () => { + const shards = $scope.pageData.shards; + $scope.totalCount = shards.length; + $scope.showing = transformer(shards, $scope.pageData.nodes); + if (shards.some((shard) => shard.state === 'UNASSIGNED')) { + $scope.labels = labels.indexWithUnassigned; + } else { + $scope.labels = labels.index; + } + + render( + + + , + document.getElementById('monitoringElasticsearchIndexApp') + ); + }; + + $scope.$watch('pageData', this.renderReact); } }); diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/indices/index.js b/x-pack/plugins/monitoring/public/views/elasticsearch/indices/index.js index f8615657500d8..e91cb07169d33 100644 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/indices/index.js +++ b/x-pack/plugins/monitoring/public/views/elasticsearch/indices/index.js @@ -8,7 +8,7 @@ import React from 'react'; import { find } from 'lodash'; import uiRoutes from 'ui/routes'; import { routeInitProvider } from 'plugins/monitoring/lib/route_init'; -import { MonitoringViewBaseTableController } from '../../'; +import { MonitoringViewBaseEuiTableController } from '../../'; import { ElasticsearchIndices } from '../../../components'; import template from './index.html'; import { I18nProvider } from '@kbn/i18n/react'; @@ -22,7 +22,7 @@ uiRoutes.when('/elasticsearch/indices', { } }, controllerAs: 'elasticsearchIndices', - controller: class ElasticsearchIndicesController extends MonitoringViewBaseTableController { + controller: class ElasticsearchIndicesController extends MonitoringViewBaseEuiTableController { constructor($injector, $scope, i18n) { const $route = $injector.get('$route'); const globalState = $injector.get('globalState'); @@ -69,6 +69,9 @@ uiRoutes.when('/elasticsearch/indices', { indices={indices} showSystemIndices={showSystemIndices} toggleShowSystemIndices={toggleShowSystemIndices} + sorting={this.sorting} + pagination={this.pagination} + onTableChange={this.onTableChange} /> ); diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/ml_jobs/index.html b/x-pack/plugins/monitoring/public/views/elasticsearch/ml_jobs/index.html index 61aa9e49317da..b20c927841d4f 100644 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/ml_jobs/index.html +++ b/x-pack/plugins/monitoring/public/views/elasticsearch/ml_jobs/index.html @@ -1,18 +1,9 @@ - -
-

- -
+
diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/ml_jobs/index.js b/x-pack/plugins/monitoring/public/views/elasticsearch/ml_jobs/index.js index 579b84081c369..d8b3a7bc7a604 100644 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/ml_jobs/index.js +++ b/x-pack/plugins/monitoring/public/views/elasticsearch/ml_jobs/index.js @@ -7,7 +7,7 @@ import { find } from 'lodash'; import uiRoutes from 'ui/routes'; import { routeInitProvider } from 'plugins/monitoring/lib/route_init'; -import { MonitoringViewBaseTableController } from '../../'; +import { MonitoringViewBaseEuiTableController } from '../../'; import { getPageData } from './get_page_data'; import template from './index.html'; @@ -21,7 +21,7 @@ uiRoutes.when('/elasticsearch/ml_jobs', { pageData: getPageData }, controllerAs: 'mlJobs', - controller: class MlJobsList extends MonitoringViewBaseTableController { + controller: class MlJobsList extends MonitoringViewBaseEuiTableController { constructor($injector, $scope, i18n) { super({ diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/node/advanced/index.html b/x-pack/plugins/monitoring/public/views/elasticsearch/node/advanced/index.html index 4256c5bb5377b..c79c4eed46bb7 100644 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/node/advanced/index.html +++ b/x-pack/plugins/monitoring/public/views/elasticsearch/node/advanced/index.html @@ -7,25 +7,5 @@ tab-icon-class="{{ pageData.nodeSummary.nodeTypeClass }}" tab-icon-class="{{ pageData.nodeSummary.nodeTypeLabel }}" > - - -
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/node/advanced/index.js b/x-pack/plugins/monitoring/public/views/elasticsearch/node/advanced/index.js index 9a323cd8e5564..e48c12e06aefa 100644 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/node/advanced/index.js +++ b/x-pack/plugins/monitoring/public/views/elasticsearch/node/advanced/index.js @@ -7,12 +7,17 @@ /** * Controller for Advanced Node Detail */ +import React from 'react'; +import { render } from 'react-dom'; import { find } from 'lodash'; import uiRoutes from 'ui/routes'; import { ajaxErrorHandlersProvider } from 'plugins/monitoring/lib/ajax_error_handler'; import { routeInitProvider } from 'plugins/monitoring/lib/route_init'; import template from './index.html'; import { timefilter } from 'ui/timefilter'; +import { I18nProvider } from '@kbn/i18n/react'; +import { AdvancedNode } from '../../../../components/elasticsearch/node/advanced'; +import moment from 'moment'; function getPageData($injector) { const $http = $injector.get('$http'); @@ -76,5 +81,28 @@ uiRoutes.when('/elasticsearch/nodes/:node/advanced', { $executor.start($scope); $scope.$on('$destroy', $executor.destroy); + + function onBrush({ xaxis }) { + timefilter.setTime({ + from: moment(xaxis.from), + to: moment(xaxis.to), + mode: 'absolute', + }); + } + + this.renderReact = () => { + render( + + + , + document.getElementById('monitoringElasticsearchAdvancedNodeApp') + ); + }; + + $scope.$watch('pageData', this.renderReact); } }); diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/node/index.html b/x-pack/plugins/monitoring/public/views/elasticsearch/node/index.html index 5aca1c9625a15..ce43bed531011 100644 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/node/index.html +++ b/x-pack/plugins/monitoring/public/views/elasticsearch/node/index.html @@ -7,25 +7,5 @@ tab-icon-class="{{ pageData.nodeSummary.nodeTypeClass }}" tab-icon-class="{{ pageData.nodeSummary.nodeTypeLabel }}" > - - -
-
-
-
-
-
-
-
-
-
- - +
diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/node/index.js b/x-pack/plugins/monitoring/public/views/elasticsearch/node/index.js index 0e6825fefe002..52c3e310a656d 100644 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/node/index.js +++ b/x-pack/plugins/monitoring/public/views/elasticsearch/node/index.js @@ -7,12 +7,19 @@ /** * Controller for Node Detail */ +import React from 'react'; +import { render } from 'react-dom'; import { find, partial } from 'lodash'; import uiRoutes from 'ui/routes'; import { routeInitProvider } from 'plugins/monitoring/lib/route_init'; import { getPageData } from './get_page_data'; import template from './index.html'; import { timefilter } from 'ui/timefilter'; +import { Node } from '../../../components/elasticsearch/node/node'; +import { I18nProvider } from '@kbn/i18n/react'; +import { labels } from '../../../components/elasticsearch/shard_allocation/lib/labels'; +import { nodesByIndices } from '../../../components/elasticsearch/shard_allocation/transformers/nodes_by_indices'; +import moment from 'moment'; uiRoutes.when('/elasticsearch/nodes/:node', { template, @@ -28,6 +35,7 @@ uiRoutes.when('/elasticsearch/nodes/:node', { timefilter.enableAutoRefreshSelector(); const $route = $injector.get('$route'); + const kbnUrl = $injector.get('kbnUrl'); const globalState = $injector.get('globalState'); $scope.cluster = find($route.current.locals.clusters, { cluster_uuid: globalState.cluster_uuid }); $scope.pageData = $route.current.locals.pageData; @@ -65,5 +73,35 @@ uiRoutes.when('/elasticsearch/nodes/:node', { $executor.start($scope); $scope.$on('$destroy', $executor.destroy); + + function onBrush({ xaxis }) { + timefilter.setTime({ + from: moment(xaxis.from), + to: moment(xaxis.to), + mode: 'absolute', + }); + } + + const transformer = nodesByIndices(); + this.renderReact = () => { + const shards = $scope.pageData.shards; + $scope.totalCount = shards.length; + $scope.showing = transformer(shards, $scope.pageData.nodes); + $scope.labels = labels.node; + + render( + + + , + document.getElementById('monitoringElasticsearchNodeApp') + ); + }; + + $scope.$watch('pageData', this.renderReact); } }); diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/nodes/index.js b/x-pack/plugins/monitoring/public/views/elasticsearch/nodes/index.js index ba36c490a737c..472be27a00cbf 100644 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/nodes/index.js +++ b/x-pack/plugins/monitoring/public/views/elasticsearch/nodes/index.js @@ -9,7 +9,7 @@ import { find } from 'lodash'; import uiRoutes from 'ui/routes'; import template from './index.html'; import { routeInitProvider } from 'plugins/monitoring/lib/route_init'; -import { MonitoringViewBaseTableController } from '../../'; +import { MonitoringViewBaseEuiTableController } from '../../'; import { ElasticsearchNodes } from '../../../components'; import { I18nProvider } from '@kbn/i18n/react'; @@ -22,7 +22,7 @@ uiRoutes.when('/elasticsearch/nodes', { } }, controllerAs: 'elasticsearchNodes', - controller: class ElasticsearchNodesController extends MonitoringViewBaseTableController { + controller: class ElasticsearchNodesController extends MonitoringViewBaseEuiTableController { constructor($injector, $scope, i18n) { const $route = $injector.get('$route'); const globalState = $injector.get('globalState'); @@ -55,6 +55,9 @@ uiRoutes.when('/elasticsearch/nodes', { clusterStatus={clusterStatus} nodes={nodes} showCgroupMetricsElasticsearch={showCgroupMetricsElasticsearch} + sorting={this.sorting} + pagination={this.pagination} + onTableChange={this.onTableChange} /> ); diff --git a/x-pack/plugins/monitoring/public/views/index.js b/x-pack/plugins/monitoring/public/views/index.js index 0e0d9b9a03852..f696ba42b262f 100644 --- a/x-pack/plugins/monitoring/public/views/index.js +++ b/x-pack/plugins/monitoring/public/views/index.js @@ -6,3 +6,4 @@ export { MonitoringViewBaseController } from './base_controller'; export { MonitoringViewBaseTableController } from './base_table_controller'; +export { MonitoringViewBaseEuiTableController } from './base_eui_table_controller'; diff --git a/x-pack/test/functional/apps/monitoring/beats/listing.js b/x-pack/test/functional/apps/monitoring/beats/listing.js index 69c7a8da797c6..0194f1162511d 100644 --- a/x-pack/test/functional/apps/monitoring/beats/listing.js +++ b/x-pack/test/functional/apps/monitoring/beats/listing.js @@ -39,8 +39,8 @@ export default function ({ getService, getPageObjects }) { duckbeat: 1, sheepbeat: 1, winlogbeat: 1, - totalEvents: '699.9k', - bytesSent: '427.9 MB', + totalEvents: 'Total Events:\n699.9k', + bytesSent: 'Bytes Sent:\n427.9 MB', }); }); diff --git a/x-pack/test/functional/apps/monitoring/beats/overview.js b/x-pack/test/functional/apps/monitoring/beats/overview.js index d0beebce8bf90..bfd4058939568 100644 --- a/x-pack/test/functional/apps/monitoring/beats/overview.js +++ b/x-pack/test/functional/apps/monitoring/beats/overview.js @@ -43,8 +43,8 @@ export default function ({ getService, getPageObjects }) { duckbeat: 1, sheepbeat: 1, winlogbeat: 1, - totalEvents: '699.9k', - bytesSent: '427.9 MB', + totalEvents: 'Total Events:\n699.9k', + bytesSent: 'Bytes Sent:\n427.9 MB', }); }); diff --git a/x-pack/test/functional/apps/monitoring/elasticsearch/indices.js b/x-pack/test/functional/apps/monitoring/elasticsearch/indices.js index 3c9e4a1e4d022..58ec00cf6db1a 100644 --- a/x-pack/test/functional/apps/monitoring/elasticsearch/indices.js +++ b/x-pack/test/functional/apps/monitoring/elasticsearch/indices.js @@ -43,48 +43,8 @@ export default function ({ getService, getPageObjects }) { }); }); - it('should have an indices table with correct rows with default sorting', async () => { - const rows = await indicesList.getRows(); - expect(rows.length).to.be(20); - - const indicesAll = await indicesList.getIndicesAll(); - - const tableData = [ /*eslint-disable max-len*/ - { name: 'many-0007_milycdknpycp', status: 'Health: red', documentCount: '1', dataSize: '3.6 KB', indexRate: '0 /s', searchRate: '0 /s', unassignedShards: '1' }, - { name: 'many-0009_reolfgzjjtvh', status: 'Health: red', documentCount: '1', dataSize: '3.6 KB', indexRate: '0 /s', searchRate: '0 /s', unassignedShards: '1' }, - { name: 'many-0011_xtkcmlwmxcov', status: 'Health: red', documentCount: '1', dataSize: '3.6 KB', indexRate: '0 /s', searchRate: '0 /s', unassignedShards: '1' }, - { name: 'many-0013_smjuwdkhpduv', status: 'Health: red', documentCount: '1', dataSize: '3.6 KB', indexRate: '0 /s', searchRate: '0 /s', unassignedShards: '1' }, - { name: 'many-0015_vwmrucgzvohb', status: 'Health: red', documentCount: '1', dataSize: '3.6 KB', indexRate: '0 /s', searchRate: '0 /s', unassignedShards: '1' }, - { name: 'many-0017_zpyxggzmytun', status: 'Health: red', documentCount: '1', dataSize: '3.6 KB', indexRate: '0 /s', searchRate: '0 /s', unassignedShards: '1' }, - { name: 'many-0019_slpgftmneikv', status: 'Health: red', documentCount: '1', dataSize: '3.6 KB', indexRate: '0 /s', searchRate: '0 /s', unassignedShards: '1' }, - { name: 'many-0021_xjtlceanhvup', status: 'Health: red', documentCount: '1', dataSize: '3.6 KB', indexRate: '0 /s', searchRate: '0 /s', unassignedShards: '1' }, - { name: 'many-0023_hkbvktonytxh', status: 'Health: red', documentCount: '1', dataSize: '3.6 KB', indexRate: '0 /s', searchRate: '0 /s', unassignedShards: '1' }, - { name: 'many-0025_xmvpnfeuqxtp', status: 'Health: red', documentCount: '1', dataSize: '3.6 KB', indexRate: '0 /s', searchRate: '0 /s', unassignedShards: '1' }, - { name: 'phone-home', status: 'Health: yellow', documentCount: '1', dataSize: '66.2 KB', indexRate: '0 /s', searchRate: '0 /s', unassignedShards: '5' }, - { name: 'many-0006_gkuqbjonkjmg', status: 'Health: green', documentCount: '1', dataSize: '3.7 KB', indexRate: '0 /s', searchRate: '4.08 /s', unassignedShards: '0' }, - { name: 'many-0008_amnscruqlsnu', status: 'Health: green', documentCount: '1', dataSize: '3.7 KB', indexRate: '0 /s', searchRate: '4.08 /s', unassignedShards: '0' }, - { name: 'many-0010_dgnlpqtstfvi', status: 'Health: green', documentCount: '1', dataSize: '3.7 KB', indexRate: '0 /s', searchRate: '1.95 /s', unassignedShards: '0' }, - { name: 'many-0012_jwomwdgfpisl', status: 'Health: green', documentCount: '1', dataSize: '3.7 KB', indexRate: '0 /s', searchRate: '1.95 /s', unassignedShards: '0' }, - { name: 'many-0014_zrukbrvuluby', status: 'Health: green', documentCount: '1', dataSize: '3.7 KB', indexRate: '0 /s', searchRate: '1.95 /s', unassignedShards: '0' }, - { name: 'many-0016_gyvtsyauoqqg', status: 'Health: green', documentCount: '1', dataSize: '3.7 KB', indexRate: '0 /s', searchRate: '1.95 /s', unassignedShards: '0' }, - { name: 'many-0018_ipugjcmuagih', status: 'Health: green', documentCount: '1', dataSize: '3.7 KB', indexRate: '0 /s', searchRate: '1.95 /s', unassignedShards: '0' }, - { name: 'many-0020_fqfovcnznbus', status: 'Health: green', documentCount: '1', dataSize: '3.7 KB', indexRate: '0 /s', searchRate: '1.95 /s', unassignedShards: '0' }, - { name: 'many-0022_dqbcjopzejlk', status: 'Health: green', documentCount: '1', dataSize: '3.7 KB', indexRate: '0 /s', searchRate: '1.95 /s', unassignedShards: '0' }, - ]; /*eslint-enable*/ - - // check the all data in the table - indicesAll.forEach((obj, index) => { - expect(indicesAll[index].name).to.be(tableData[index].name); - expect(indicesAll[index].status).to.be(tableData[index].status); - expect(indicesAll[index].documentCount).to.be(tableData[index].documentCount); - expect(indicesAll[index].dataSize).to.be(tableData[index].dataSize); - expect(indicesAll[index].indexRate).to.be(tableData[index].indexRate); - expect(indicesAll[index].searchRate).to.be(tableData[index].searchRate); - expect(indicesAll[index].unassignedShards).to.be(tableData[index].unassignedShards); - }); - }); - - it('should show indices table with correct rows after sorting by Search Rate Desc', async () => { + // Revisit once https://github.com/elastic/eui/issues/1322 is resolved + it.skip('should show indices table with correct rows after sorting by Search Rate Desc', async () => { await indicesList.clickSearchCol(); await indicesList.clickSearchCol(); diff --git a/x-pack/test/functional/apps/monitoring/elasticsearch/node_detail.js b/x-pack/test/functional/apps/monitoring/elasticsearch/node_detail.js index a5ab5a2326673..1bf5dd28277a7 100644 --- a/x-pack/test/functional/apps/monitoring/elasticsearch/node_detail.js +++ b/x-pack/test/functional/apps/monitoring/elasticsearch/node_detail.js @@ -40,7 +40,7 @@ export default function ({ getService, getPageObjects }) { await nodesList.clickRowByResolver('jUT5KdxfRbORSCWkb5zjmA'); expect(await nodeDetail.getSummary()).to.eql({ - transportAddress: '127.0.0.1:9300', + transportAddress: 'Transport Address:\n127.0.0.1:9300', jvmHeap: 'JVM Heap:\n29%', freeDiskSpace: 'Free Disk Space:\n173.9 GB', documentCount: 'Documents:\n24.8k', @@ -56,7 +56,7 @@ export default function ({ getService, getPageObjects }) { await nodesList.clickRowByResolver('bwQWH-7IQY-mFPpfoaoFXQ'); expect(await nodeDetail.getSummary()).to.eql({ - transportAddress: '127.0.0.1:9302', + transportAddress: 'Transport Address:\n127.0.0.1:9302', jvmHeap: 'JVM Heap:\n17%', freeDiskSpace: 'Free Disk Space:\n173.9 GB', documentCount: 'Documents:\n240', @@ -91,7 +91,7 @@ export default function ({ getService, getPageObjects }) { await nodesList.clickRowByResolver('1jxg5T33TWub-jJL4qP0Wg'); expect(await nodeDetail.getSummary()).to.eql({ - transportAddress: '127.0.0.1:9302', + transportAddress: 'Transport Address:\n127.0.0.1:9302', jvmHeap: 'JVM Heap:\nN/A', freeDiskSpace: 'Free Disk Space:\nN/A', documentCount: 'Documents:\nN/A', diff --git a/x-pack/test/functional/apps/monitoring/elasticsearch/nodes.js b/x-pack/test/functional/apps/monitoring/elasticsearch/nodes.js index 1919bca3bffa0..c20050c9b4bc0 100644 --- a/x-pack/test/functional/apps/monitoring/elasticsearch/nodes.js +++ b/x-pack/test/functional/apps/monitoring/elasticsearch/nodes.js @@ -50,8 +50,24 @@ export default function ({ getService, getPageObjects }) { const nodesAll = await nodesList.getNodesAll(); const tableData = [ - { name: 'whatever-01', status: 'Status: Online', cpu: '0%', load: '3.28', memory: '39%', disk: '173.9 GB', shards: '38', }, - { name: 'whatever-02', status: 'Status: Online', cpu: '2%', load: '3.28', memory: '25%', disk: '173.9 GB', shards: '38', }, + { + name: 'whatever-01', + status: 'Status: Online', + cpu: '0% \n3% max\n0% min', + load: '3.28 \n3.71 max\n2.19 min', + memory: '39% \n52% max\n25% min', + disk: '173.9 GB \n173.9 GB max\n173.9 GB min', + shards: '38', + }, + { + name: 'whatever-02', + status: 'Status: Online', + cpu: '2% \n3% max\n0% min', + load: '3.28 \n3.73 max\n2.29 min', + memory: '25% \n49% max\n25% min', + disk: '173.9 GB \n173.9 GB max\n173.9 GB min', + shards: '38', + }, { name: 'whatever-03', status: 'Status: Offline' }, ]; nodesAll.forEach((obj, node) => { @@ -100,7 +116,7 @@ export default function ({ getService, getPageObjects }) { await nodesList.clickCpuCol(); const nodesAll = await nodesList.getNodesAll(); - const tableData = [{ cpu: '0%' }, { cpu: '2%' }, { cpu: undefined }]; + const tableData = [{ cpu: '0% \n3% max\n0% min' }, { cpu: '2% \n3% max\n0% min' }, { cpu: undefined }]; nodesAll.forEach((obj, node) => { expect(nodesAll[node].cpu).to.be(tableData[node].cpu); }); @@ -112,8 +128,8 @@ export default function ({ getService, getPageObjects }) { const nodesAll = await nodesList.getNodesAll(); const tableData = [ - { load: '3.28' }, - { load: '3.28' }, + { load: '3.28 \n3.71 max\n2.19 min' }, + { load: '3.28 \n3.73 max\n2.29 min' }, { load: undefined }, ]; nodesAll.forEach((obj, node) => { @@ -127,8 +143,8 @@ export default function ({ getService, getPageObjects }) { const nodesAll = await nodesList.getNodesAll(); const tableData = [ - { memory: '39%' }, - { memory: '25%' }, + { memory: '39% \n52% max\n25% min' }, + { memory: '25% \n49% max\n25% min' }, { memory: undefined }, ]; nodesAll.forEach((obj, node) => { @@ -142,8 +158,8 @@ export default function ({ getService, getPageObjects }) { const nodesAll = await nodesList.getNodesAll(); const tableData = [ - { disk: '173.9 GB' }, - { disk: '173.9 GB' }, + { disk: '173.9 GB \n173.9 GB max\n173.9 GB min' }, + { disk: '173.9 GB \n173.9 GB max\n173.9 GB min' }, { disk: undefined }, ]; nodesAll.forEach((obj, node) => { @@ -198,7 +214,8 @@ export default function ({ getService, getPageObjects }) { }); }); - it('should filter for specific indices', async () => { + // Skip until https://github.com/elastic/eui/issues/1318 is implemented + it.skip('should filter for specific indices', async () => { await nodesList.setFilter('01'); const rows = await nodesList.getRows(); expect(rows.length).to.be(1); diff --git a/x-pack/test/functional/page_objects/monitoring_page.js b/x-pack/test/functional/page_objects/monitoring_page.js index 1c8f98119d54f..9eef3dff01bba 100644 --- a/x-pack/test/functional/page_objects/monitoring_page.js +++ b/x-pack/test/functional/page_objects/monitoring_page.js @@ -30,6 +30,14 @@ export function MonitoringPageProvider({ getPageObjects, getService }) { }); } + async assertEuiTableNoData(subj) { + await retry.try(async () => { + if (await testSubjects.exists(subj)) { + throw new Error('Expected to find the no data message'); + } + }); + } + async tableGetRows(subj) { const table = await testSubjects.find(subj); return table.findAllByTagName('tr'); diff --git a/x-pack/test/functional/services/monitoring/cluster_list.js b/x-pack/test/functional/services/monitoring/cluster_list.js index a4e29c60e4b10..a157cf97827bb 100644 --- a/x-pack/test/functional/services/monitoring/cluster_list.js +++ b/x-pack/test/functional/services/monitoring/cluster_list.js @@ -10,7 +10,6 @@ export function MonitoringClusterListProvider({ getService, getPageObjects }) { const PageObjects = getPageObjects(['monitoring']); const SUBJ_TABLE_CONTAINER = 'clusterTableContainer'; - const SUBJ_TABLE_BODY = 'clusterTableBody'; const SUBJ_TABLE_NO_DATA = `${SUBJ_TABLE_CONTAINER} monitoringTableNoData`; const SUBJ_SEARCH_BAR = `${SUBJ_TABLE_CONTAINER} monitoringTableToolBar`; @@ -27,11 +26,11 @@ export function MonitoringClusterListProvider({ getService, getPageObjects }) { } assertNoData() { - return PageObjects.monitoring.assertTableNoData(SUBJ_TABLE_NO_DATA); + return PageObjects.monitoring.assertEuiTableNoData(SUBJ_TABLE_NO_DATA); } getRows() { - return PageObjects.monitoring.tableGetRows(SUBJ_TABLE_BODY); + return PageObjects.monitoring.tableGetRowsFromContainer(SUBJ_TABLE_CONTAINER); } setFilter(text) { diff --git a/x-pack/test/functional/services/monitoring/elasticsearch_indices.js b/x-pack/test/functional/services/monitoring/elasticsearch_indices.js index a57c5883dd8e2..fa1995d61b6b0 100644 --- a/x-pack/test/functional/services/monitoring/elasticsearch_indices.js +++ b/x-pack/test/functional/services/monitoring/elasticsearch_indices.js @@ -17,18 +17,17 @@ export function MonitoringElasticsearchIndicesProvider({ getService, getPageObje const SUBJ_TABLE_NO_DATA = `${SUBJ_TABLE_CONTAINER} monitoringTableNoData`; const SUBJ_SEARCH_BAR = `${SUBJ_TABLE_CONTAINER} monitoringTableToolBar`; - const SUBJ_TABLE_SORT_SEARCH_COL = `${SUBJ_TABLE_CONTAINER} tableHeaderCell-searchRate`; + const SUBJ_TABLE_SORT_SEARCH_COL = `${SUBJ_TABLE_CONTAINER} tableHeaderCell_search_rate_5`; - const SUBJ_TABLE_BODY = 'elasticsearchIndicesTableBody'; - const SUBJ_INDICES_NAMES = `${SUBJ_TABLE_BODY} name`; - const SUBJ_INDICES_STATUSES = `${SUBJ_TABLE_BODY} statusIcon`; - const SUBJ_INDICES_DOCUMENT_COUNTS = `${SUBJ_TABLE_BODY} documentCount`; - const SUBJ_INDICES_DATA_SIZES = `${SUBJ_TABLE_BODY} dataSize`; - const SUBJ_INDICES_INDEX_RATES = `${SUBJ_TABLE_BODY} indexRate`; - const SUBJ_INDICES_SEARCH_RATES = `${SUBJ_TABLE_BODY} searchRate`; - const SUBJ_INDICES_UNASSIGNED_SHARD_COUNTS = `${SUBJ_TABLE_BODY} unassignedShards`; + const SUBJ_INDICES_NAMES = `${SUBJ_TABLE_CONTAINER} name`; + const SUBJ_INDICES_STATUSES = `${SUBJ_TABLE_CONTAINER} statusIcon`; + const SUBJ_INDICES_DOCUMENT_COUNTS = `${SUBJ_TABLE_CONTAINER} documentCount`; + const SUBJ_INDICES_DATA_SIZES = `${SUBJ_TABLE_CONTAINER} dataSize`; + const SUBJ_INDICES_INDEX_RATES = `${SUBJ_TABLE_CONTAINER} indexRate`; + const SUBJ_INDICES_SEARCH_RATES = `${SUBJ_TABLE_CONTAINER} searchRate`; + const SUBJ_INDICES_UNASSIGNED_SHARD_COUNTS = `${SUBJ_TABLE_CONTAINER} unassignedShards`; - const SUBJ_INDEX_LINK_PREFIX = `${SUBJ_TABLE_BODY} indexLink-`; + const SUBJ_INDEX_LINK_PREFIX = `${SUBJ_TABLE_CONTAINER} indexLink-`; return new class ElasticsearchIndices { async isOnListing() { @@ -43,11 +42,11 @@ export function MonitoringElasticsearchIndicesProvider({ getService, getPageObje } assertNoData() { - return PageObjects.monitoring.assertTableNoData(SUBJ_TABLE_NO_DATA); + return PageObjects.monitoring.assertEuiTableNoData(SUBJ_TABLE_NO_DATA); } getRows() { - return PageObjects.monitoring.tableGetRows(SUBJ_TABLE_BODY); + return PageObjects.monitoring.tableGetRowsFromContainer(SUBJ_TABLE_CONTAINER); } setFilter(text) { diff --git a/x-pack/test/functional/services/monitoring/elasticsearch_nodes.js b/x-pack/test/functional/services/monitoring/elasticsearch_nodes.js index 6b7f9cdcc2d24..47863a83077d9 100644 --- a/x-pack/test/functional/services/monitoring/elasticsearch_nodes.js +++ b/x-pack/test/functional/services/monitoring/elasticsearch_nodes.js @@ -17,15 +17,15 @@ export function MonitoringElasticsearchNodesProvider({ getService, getPageObject const SUBJ_TABLE_NO_DATA = `${SUBJ_TABLE_CONTAINER} monitoringTableNoData`; const SUBJ_SEARCH_BAR = `${SUBJ_TABLE_CONTAINER} monitoringTableToolBar`; - const SUBJ_TABLE_SORT_NAME_COL = `${SUBJ_TABLE_CONTAINER} tableHeaderCell-name`; - const SUBJ_TABLE_SORT_STATUS_COL = `${SUBJ_TABLE_CONTAINER} tableHeaderCell-status`; - const SUBJ_TABLE_SORT_CPU_COL = `${SUBJ_TABLE_CONTAINER} tableHeaderCell-cpuUsage`; - const SUBJ_TABLE_SORT_LOAD_COL = `${SUBJ_TABLE_CONTAINER} tableHeaderCell-loadAverage`; - const SUBJ_TABLE_SORT_MEM_COL = `${SUBJ_TABLE_CONTAINER} tableHeaderCell-jvmMemory`; - const SUBJ_TABLE_SORT_DISK_COL = `${SUBJ_TABLE_CONTAINER} tableHeaderCell-diskFreeSpace`; - const SUBJ_TABLE_SORT_SHARDS_COL = `${SUBJ_TABLE_CONTAINER} tableHeaderCell-shards`; - - const SUBJ_TABLE_BODY = 'elasticsearchNodesTableBody'; + const SUBJ_TABLE_SORT_NAME_COL = `${SUBJ_TABLE_CONTAINER} tableHeaderCell_name_0`; + const SUBJ_TABLE_SORT_STATUS_COL = `${SUBJ_TABLE_CONTAINER} tableHeaderCell_isOnline_1`; + const SUBJ_TABLE_SORT_CPU_COL = `${SUBJ_TABLE_CONTAINER} tableHeaderCell_node_cpu_utilization_2`; + const SUBJ_TABLE_SORT_LOAD_COL = `${SUBJ_TABLE_CONTAINER} tableHeaderCell_node_load_average_3`; + const SUBJ_TABLE_SORT_MEM_COL = `${SUBJ_TABLE_CONTAINER} tableHeaderCell_node_jvm_mem_percent_4`; + const SUBJ_TABLE_SORT_DISK_COL = `${SUBJ_TABLE_CONTAINER} tableHeaderCell_node_free_space_5`; + const SUBJ_TABLE_SORT_SHARDS_COL = `${SUBJ_TABLE_CONTAINER} tableHeaderCell_shardCount_6`; + + const SUBJ_TABLE_BODY = 'elasticsearchNodesTableContainer'; const SUBJ_NODES_NAMES = `${SUBJ_TABLE_BODY} name`; const SUBJ_NODES_STATUSES = `${SUBJ_TABLE_BODY} statusIcon`; const SUBJ_NODES_CPUS = `${SUBJ_TABLE_BODY} cpuUsage`; @@ -89,7 +89,7 @@ export function MonitoringElasticsearchNodesProvider({ getService, getPageObject } getRows() { - return PageObjects.monitoring.tableGetRows(SUBJ_TABLE_BODY); + return PageObjects.monitoring.tableGetRowsFromContainer(SUBJ_TABLE_BODY); } setFilter(text) { @@ -101,7 +101,7 @@ export function MonitoringElasticsearchNodesProvider({ getService, getPageObject } assertNoData() { - return PageObjects.monitoring.assertTableNoData(SUBJ_TABLE_NO_DATA); + return PageObjects.monitoring.assertEuiTableNoData(SUBJ_TABLE_NO_DATA); } async getNodesAll() { From 37cc89f46bcbe935423206e63478917755da5714 Mon Sep 17 00:00:00 2001 From: Court Ewing Date: Thu, 6 Dec 2018 11:59:10 -0500 Subject: [PATCH 03/85] Update token API calls in elaticsearch.js (#26650) --- .../providers/__tests__/saml.js | 14 +++++------ .../lib/authentication/providers/saml.js | 4 ++-- x-pack/server/lib/esjs_shield_plugin.js | 24 +++++++++++++++++-- 3 files changed, 31 insertions(+), 11 deletions(-) diff --git a/x-pack/plugins/security/server/lib/authentication/providers/__tests__/saml.js b/x-pack/plugins/security/server/lib/authentication/providers/__tests__/saml.js index 0000afe96a0b5..ad9720422cfa3 100644 --- a/x-pack/plugins/security/server/lib/authentication/providers/__tests__/saml.js +++ b/x-pack/plugins/security/server/lib/authentication/providers/__tests__/saml.js @@ -236,7 +236,7 @@ describe('SAMLAuthenticationProvider', () => { expect(request.headers).to.not.have.property('authorization'); expect(authenticationResult.failed()).to.be(true); expect(authenticationResult.error).to.be(failureReason); - sinon.assert.neverCalledWith(callWithRequest, 'shield.samlRefreshAccessToken'); + sinon.assert.neverCalledWith(callWithRequest, 'shield.getAccessToken'); }); it('succeeds if token from the state is expired, but has been successfully refreshed.', async () => { @@ -259,7 +259,7 @@ describe('SAMLAuthenticationProvider', () => { callWithInternalUser .withArgs( - 'shield.samlRefreshAccessToken', + 'shield.getAccessToken', { body: { grant_type: 'refresh_token', refresh_token: 'valid-refresh-token' } } ) .returns(Promise.resolve({ access_token: 'new-access-token', refresh_token: 'new-refresh-token' })); @@ -291,7 +291,7 @@ describe('SAMLAuthenticationProvider', () => { const refreshFailureReason = new Error('Something is wrong with refresh token.'); callWithInternalUser .withArgs( - 'shield.samlRefreshAccessToken', + 'shield.getAccessToken', { body: { grant_type: 'refresh_token', refresh_token: 'invalid-refresh-token' } } ) .returns(Promise.reject(refreshFailureReason)); @@ -318,7 +318,7 @@ describe('SAMLAuthenticationProvider', () => { callWithInternalUser .withArgs( - 'shield.samlRefreshAccessToken', + 'shield.getAccessToken', { body: { grant_type: 'refresh_token', refresh_token: 'invalid-refresh-token' } } ) .returns(Promise.reject({ body: { error_description: 'token has already been refreshed' } })); @@ -352,7 +352,7 @@ describe('SAMLAuthenticationProvider', () => { callWithInternalUser .withArgs( - 'shield.samlRefreshAccessToken', + 'shield.getAccessToken', { body: { grant_type: 'refresh_token', refresh_token: 'invalid-refresh-token' } } ) .returns(Promise.reject({ body: { error_description: 'token has already been refreshed' } })); @@ -388,7 +388,7 @@ describe('SAMLAuthenticationProvider', () => { callWithInternalUser .withArgs( - 'shield.samlRefreshAccessToken', + 'shield.getAccessToken', { body: { grant_type: 'refresh_token', refresh_token: 'expired-refresh-token' } } ) .returns(Promise.reject({ body: { error_description: 'refresh token is expired' } })); @@ -422,7 +422,7 @@ describe('SAMLAuthenticationProvider', () => { callWithInternalUser .withArgs( - 'shield.samlRefreshAccessToken', + 'shield.getAccessToken', { body: { grant_type: 'refresh_token', refresh_token: 'expired-refresh-token' } } ) .returns(Promise.reject({ body: { error_description: 'refresh token is expired' } })); diff --git a/x-pack/plugins/security/server/lib/authentication/providers/saml.js b/x-pack/plugins/security/server/lib/authentication/providers/saml.js index fc364736e395b..dbe6091d987dd 100644 --- a/x-pack/plugins/security/server/lib/authentication/providers/saml.js +++ b/x-pack/plugins/security/server/lib/authentication/providers/saml.js @@ -34,7 +34,7 @@ function isAccessTokenExpiredError(err) { } /** - * Checks the error returned by Elasticsearch as the result of `samlRefreshAccessToken` call and returns `true` if + * Checks the error returned by Elasticsearch as the result of `getAccessToken` call and returns `true` if * request has been rejected because of invalid refresh token (expired after 24 hours or have been used already), * otherwise returns `false`. * @param {Object} err Error returned from Elasticsearch. @@ -269,7 +269,7 @@ export class SAMLAuthenticationProvider { access_token: newAccessToken, refresh_token: newRefreshToken } = await this._options.client.callWithInternalUser( - 'shield.samlRefreshAccessToken', + 'shield.getAccessToken', { body: { grant_type: 'refresh_token', refresh_token: refreshToken } } ); diff --git a/x-pack/server/lib/esjs_shield_plugin.js b/x-pack/server/lib/esjs_shield_plugin.js index fd1552e38bb5c..e8b962e89e7b8 100644 --- a/x-pack/server/lib/esjs_shield_plugin.js +++ b/x-pack/server/lib/esjs_shield_plugin.js @@ -360,14 +360,14 @@ }); /** - * Refreshes SAML access token. + * Refreshes an access token. * * @param {string} grant_type Currently only "refresh_token" grant type is supported. * @param {string} refresh_token One-time refresh token that will be exchanged to the new access/refresh token pair. * * @returns {{access_token: string, type: string, expires_in: number, refresh_token: string}} */ - shield.samlRefreshAccessToken = ca({ + shield.getAccessToken = ca({ method: 'POST', needBody: true, url: { @@ -375,6 +375,26 @@ } }); + /** + * Invalidates an access token. + * + * @param {string} token The access token to invalidate + * + * @returns {{created: boolean}} + */ + shield.deleteAccessToken = ca({ + method: 'DELETE', + needBody: true, + params: { + token: { + type: 'string' + } + }, + url: { + fmt: '/_xpack/security/oauth2/token' + } + }); + shield.getPrivilege = ca({ method: 'GET', urls: [{ From 1cc57e8c28d5b3b8d2574ccc0e91c1cbb57786a6 Mon Sep 17 00:00:00 2001 From: Ryan Keairns Date: Thu, 6 Dec 2018 11:38:19 -0600 Subject: [PATCH 04/85] make selection border 1px (#26739) --- .../border_connection/border_connection.scss | 7 ++----- .../components/rotation_handle/rotation_handle.scss | 11 ++++++----- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/x-pack/plugins/canvas/public/components/border_connection/border_connection.scss b/x-pack/plugins/canvas/public/components/border_connection/border_connection.scss index aa5d9ad1e0f41..ba09edd1090db 100644 --- a/x-pack/plugins/canvas/public/components/border_connection/border_connection.scss +++ b/x-pack/plugins/canvas/public/components/border_connection/border_connection.scss @@ -4,9 +4,6 @@ width: 100%; height: 100%; pointer-events: none; - //box-shadow: inset 0 0 1px 2px $euiColorPrimary; - border-top: $euiBorderThin; - border-left: $euiBorderThin; - border-style: dashed; - border-color: #d9d9d9; + border-top: 1px dashed $euiColorLightShade; + border-left: 1px dashed $euiColorLightShade; } diff --git a/x-pack/plugins/canvas/public/components/rotation_handle/rotation_handle.scss b/x-pack/plugins/canvas/public/components/rotation_handle/rotation_handle.scss index cd52e29e4f411..820107ff47a51 100644 --- a/x-pack/plugins/canvas/public/components/rotation_handle/rotation_handle.scss +++ b/x-pack/plugins/canvas/public/components/rotation_handle/rotation_handle.scss @@ -7,7 +7,8 @@ width: 0; margin-left: -1px; margin-top: -12px; - border: 1px dashed #d9d9d9; + border-top: 1px dashed $euiColorLightShade; + border-left: 1px dashed $euiColorLightShade; } .canvasRotationHandle--handle { @@ -15,10 +16,10 @@ transform-style: preserve-3d; display: block; position: absolute; - height: 8px; - width: 8px; - margin-left: -4px; + height: 9px; + width: 9px; + margin-left: -5px; margin-top: -3px; border-radius: 50%; - background-color: #999; + background-color: $euiColorMediumShade; } From b89da88237533921ca9bf099118381b9611ecf90 Mon Sep 17 00:00:00 2001 From: nicknak Date: Thu, 6 Dec 2018 13:45:40 -0500 Subject: [PATCH 05/85] Reporting phantom and chromium tests should run in parallel. (#26566) * Reporting phantom and chromium tests should run in parallel. * Chromium tests should be done in group 9. * Attempting to use group 2 in ci for chromium tests. * X-pack CI jobs should have 7 groups. * Phantom tests should be in group 7. --- .ci/jobs.yml | 1 + test/scripts/jenkins_xpack_ci_group.sh | 3 ++- x-pack/test/functional/apps/infra/index.ts | 2 +- x-pack/test/reporting/api/chromium_tests.js | 2 +- x-pack/test/reporting/api/phantom_tests.js | 2 +- 5 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.ci/jobs.yml b/.ci/jobs.yml index f9302db4b2910..84d8f75acbd30 100644 --- a/.ci/jobs.yml +++ b/.ci/jobs.yml @@ -21,6 +21,7 @@ JOB: - x-pack-ciGroup4 - x-pack-ciGroup5 - x-pack-ciGroup6 + - x-pack-ciGroup7 # `~` is yaml for `null` exclude: ~ diff --git a/test/scripts/jenkins_xpack_ci_group.sh b/test/scripts/jenkins_xpack_ci_group.sh index 4df6041639116..11b16ba27a328 100755 --- a/test/scripts/jenkins_xpack_ci_group.sh +++ b/test/scripts/jenkins_xpack_ci_group.sh @@ -14,7 +14,8 @@ node scripts/functional_tests --assert-none-excluded \ --include-tag ciGroup3 \ --include-tag ciGroup4 \ --include-tag ciGroup5 \ - --include-tag ciGroup6 + --include-tag ciGroup6 \ + --include-tag ciGroup7 echo " -> building and extracting default Kibana distributable for use in functional tests" cd "$KIBANA_DIR" diff --git a/x-pack/test/functional/apps/infra/index.ts b/x-pack/test/functional/apps/infra/index.ts index 117f309d9470e..322aea31e1263 100644 --- a/x-pack/test/functional/apps/infra/index.ts +++ b/x-pack/test/functional/apps/infra/index.ts @@ -9,7 +9,7 @@ import { KibanaFunctionalTestDefaultProviders } from '../../../types/providers'; // tslint:disable-next-line:no-default-export export default ({ loadTestFile }: KibanaFunctionalTestDefaultProviders) => { describe('InfraOps app', function() { - this.tags('ciGroup4'); + this.tags('ciGroup7'); loadTestFile(require.resolve('./home_page')); }); diff --git a/x-pack/test/reporting/api/chromium_tests.js b/x-pack/test/reporting/api/chromium_tests.js index b983f290eb085..892f561539387 100644 --- a/x-pack/test/reporting/api/chromium_tests.js +++ b/x-pack/test/reporting/api/chromium_tests.js @@ -11,7 +11,7 @@ export default function ({ loadTestFile, getService }) { const kibanaServer = getService('kibanaServer'); describe('chromium', function () { - this.tags('ciGroup6'); + this.tags('ciGroup2'); before(async () => { await esArchiver.load(OSS_KIBANA_ARCHIVE_PATH); diff --git a/x-pack/test/reporting/api/phantom_tests.js b/x-pack/test/reporting/api/phantom_tests.js index e0c8c11b326bd..62993ec40208e 100644 --- a/x-pack/test/reporting/api/phantom_tests.js +++ b/x-pack/test/reporting/api/phantom_tests.js @@ -11,7 +11,7 @@ export default function ({ loadTestFile, getService }) { const kibanaServer = getService('kibanaServer'); describe('phantom', function () { - this.tags('ciGroup6'); + this.tags('ciGroup7'); before(async () => { await esArchiver.load(OSS_KIBANA_ARCHIVE_PATH); From 1866d57643e14fdc337584f87ec371a9f19a7562 Mon Sep 17 00:00:00 2001 From: Spencer Date: Thu, 6 Dec 2018 10:58:24 -0800 Subject: [PATCH 06/85] [es-management/watcher] implement k7Breadcrumbs (#26719) --- .../plugins/watcher/public/lib/breadcrumbs.js | 49 +++++++++++++++++++ .../watch_detail/watch_detail_route.js | 2 + .../sections/watch_edit/watch_edit_route.js | 2 + .../watch_history_item_route.js | 2 + .../sections/watch_list/watch_list_route.js | 2 + 5 files changed, 57 insertions(+) create mode 100644 x-pack/plugins/watcher/public/lib/breadcrumbs.js diff --git a/x-pack/plugins/watcher/public/lib/breadcrumbs.js b/x-pack/plugins/watcher/public/lib/breadcrumbs.js new file mode 100644 index 0000000000000..c30bc4175375a --- /dev/null +++ b/x-pack/plugins/watcher/public/lib/breadcrumbs.js @@ -0,0 +1,49 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import chrome from 'ui/chrome'; +import { i18n } from '@kbn/i18n'; + +import { MANAGEMENT_BREADCRUMB } from 'ui/management'; + +const uiSettings = chrome.getUiSettingsClient(); + +export function getWatchListBreadcrumbs() { + return [ + MANAGEMENT_BREADCRUMB, + { + text: i18n.translate('xpack.watcher.list.breadcrumb', { + defaultMessage: 'Watcher' + }), + href: '#/management/elasticsearch/watcher/watches/' + } + ]; +} + +export function getWatchDetailBreadcrumbs($route) { + const watch = $route.current.locals.watch || $route.current.locals.xpackWatch; + + return [ + ...getWatchListBreadcrumbs(), + { + text: !watch.isNew + ? watch.name + : i18n.translate('xpack.watcher.create.breadcrumb', { defaultMessage: 'Create' }), + href: '#/management/elasticsearch/watcher/watches/watch/23eebf28-94fd-47e9-ac44-6fee6e427c33' + } + ]; +} + +export function getWatchHistoryBreadcrumbs($route) { + const { watchHistoryItem } = $route.current.locals; + + return [ + ...getWatchDetailBreadcrumbs($route), + { + text: watchHistoryItem.startTime.format(uiSettings.get('dateFormat')) + } + ]; +} diff --git a/x-pack/plugins/watcher/public/sections/watch_detail/watch_detail_route.js b/x-pack/plugins/watcher/public/sections/watch_detail/watch_detail_route.js index 2f7ee6e99265b..28830f7eb31fe 100644 --- a/x-pack/plugins/watcher/public/sections/watch_detail/watch_detail_route.js +++ b/x-pack/plugins/watcher/public/sections/watch_detail/watch_detail_route.js @@ -13,6 +13,7 @@ import './components/watch_detail'; import { WATCH_HISTORY } from '../../../common/constants'; import { updateWatchSections } from 'plugins/watcher/lib/update_management_sections'; import 'plugins/watcher/services/license'; +import { getWatchDetailBreadcrumbs } from '../../lib/breadcrumbs'; routes .when('/management/elasticsearch/watcher/watches/watch/:id', { @@ -22,6 +23,7 @@ routes routes .when('/management/elasticsearch/watcher/watches/watch/:id/status', { template: template, + k7Breadcrumbs: getWatchDetailBreadcrumbs, resolve: { watchTabs: ($injector) => { const $route = $injector.get('$route'); diff --git a/x-pack/plugins/watcher/public/sections/watch_edit/watch_edit_route.js b/x-pack/plugins/watcher/public/sections/watch_edit/watch_edit_route.js index 2dc2c47dfdc72..dc01f31e7cbdb 100644 --- a/x-pack/plugins/watcher/public/sections/watch_edit/watch_edit_route.js +++ b/x-pack/plugins/watcher/public/sections/watch_edit/watch_edit_route.js @@ -14,12 +14,14 @@ import './components/threshold_watch_edit'; import { WATCH_TYPES } from 'plugins/watcher/../common/constants'; import { updateWatchSections } from 'plugins/watcher/lib/update_management_sections'; import 'plugins/watcher/services/license'; +import { getWatchDetailBreadcrumbs } from '../../lib/breadcrumbs'; routes .when('/management/elasticsearch/watcher/watches/watch/:id/edit') .when('/management/elasticsearch/watcher/watches/new-watch/:watchType') .defaults(/management\/elasticsearch\/watcher\/watches\/(new-watch\/:watchType|watch\/:id\/edit)/, { template: template, + k7Breadcrumbs: getWatchDetailBreadcrumbs, controller: class WatchEditRouteController { constructor($injector) { const $route = $injector.get('$route'); diff --git a/x-pack/plugins/watcher/public/sections/watch_history_item/watch_history_item_route.js b/x-pack/plugins/watcher/public/sections/watch_history_item/watch_history_item_route.js index c6033ff7dcce1..491aaa2364cb7 100644 --- a/x-pack/plugins/watcher/public/sections/watch_history_item/watch_history_item_route.js +++ b/x-pack/plugins/watcher/public/sections/watch_history_item/watch_history_item_route.js @@ -12,10 +12,12 @@ import 'plugins/watcher/services/watch'; import 'plugins/watcher/services/watch_history'; import './components/watch_history_item'; import { updateHistorySection } from 'plugins/watcher/lib/update_management_sections'; +import { getWatchHistoryBreadcrumbs } from '../../lib/breadcrumbs'; routes .when('/management/elasticsearch/watcher/watches/watch/:watchId/history-item/:watchHistoryItemId', { template: template, + k7Breadcrumbs: getWatchHistoryBreadcrumbs, resolve: { watch: function ($injector) { const $route = $injector.get('$route'); diff --git a/x-pack/plugins/watcher/public/sections/watch_list/watch_list_route.js b/x-pack/plugins/watcher/public/sections/watch_list/watch_list_route.js index d37ea75a1a916..822ac71eaebfc 100644 --- a/x-pack/plugins/watcher/public/sections/watch_list/watch_list_route.js +++ b/x-pack/plugins/watcher/public/sections/watch_list/watch_list_route.js @@ -10,6 +10,7 @@ import { toastNotifications } from 'ui/notify'; import template from './watch_list_route.html'; import './components/watch_list'; import 'plugins/watcher/services/license'; +import { getWatchListBreadcrumbs } from '../../lib/breadcrumbs'; routes .when('/management/elasticsearch/watcher/', { @@ -26,6 +27,7 @@ routes } }, controllerAs: 'watchListRoute', + k7Breadcrumbs: getWatchListBreadcrumbs, resolve: { watches: ($injector) => { const watchesService = $injector.get('xpackWatcherWatchesService'); From 02cd34550ded130fcb223c4ebbf019a624c4e394 Mon Sep 17 00:00:00 2001 From: Spencer Date: Thu, 6 Dec 2018 11:00:42 -0800 Subject: [PATCH 07/85] [timelion] implement k7Breadcrumbs (#26729) * [timelion] implement k7Breadcrumbs * [timelion] show "Create" breadcrumb by default --- .../core_plugins/timelion/public/_app.scss | 1 + .../core_plugins/timelion/public/app.js | 9 ++++ .../timelion/public/breadcrumbs.js | 48 +++++++++++++++++++ .../core_plugins/timelion/public/index.html | 15 +++--- 4 files changed, 67 insertions(+), 6 deletions(-) create mode 100644 src/legacy/core_plugins/timelion/public/breadcrumbs.js diff --git a/src/legacy/core_plugins/timelion/public/_app.scss b/src/legacy/core_plugins/timelion/public/_app.scss index 591d1f801fef3..e15b047cba3a1 100644 --- a/src/legacy/core_plugins/timelion/public/_app.scss +++ b/src/legacy/core_plugins/timelion/public/_app.scss @@ -14,4 +14,5 @@ .timApp__stats { font-weight: $euiFontWeightRegular; + color: $euiColorMediumShade } diff --git a/src/legacy/core_plugins/timelion/public/app.js b/src/legacy/core_plugins/timelion/public/app.js index 210db2191e4b3..18e2862a52faa 100644 --- a/src/legacy/core_plugins/timelion/public/app.js +++ b/src/legacy/core_plugins/timelion/public/app.js @@ -25,6 +25,7 @@ import { notify, fatalError, toastNotifications } from 'ui/notify'; import { timezoneProvider } from 'ui/vis/lib/timezone'; import { recentlyAccessed } from 'ui/persisted_log'; import { timefilter } from 'ui/timefilter'; +import { getSavedSheetBreadcrumbs, getCreateBreadcrumbs } from './breadcrumbs'; // import the uiExports that we want to "use" import 'uiExports/fieldFormats'; @@ -57,6 +58,11 @@ require('ui/routes') .when('/:id?', { template: require('plugins/timelion/index.html'), reloadOnSearch: false, + k7Breadcrumbs: ($injector, $route) => $injector.invoke( + $route.current.params.id + ? getSavedSheetBreadcrumbs + : getCreateBreadcrumbs + ), resolve: { savedSheet: function (redirectWhenMissing, savedSheets, $route) { return savedSheets.get($route.current.params.id) @@ -73,6 +79,9 @@ require('ui/routes') 'search': '/' })); } + }, + controller($scope, config) { + config.bindToScope($scope, 'k7design'); } }); diff --git a/src/legacy/core_plugins/timelion/public/breadcrumbs.js b/src/legacy/core_plugins/timelion/public/breadcrumbs.js new file mode 100644 index 0000000000000..883c95dfdc1a6 --- /dev/null +++ b/src/legacy/core_plugins/timelion/public/breadcrumbs.js @@ -0,0 +1,48 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { i18n } from '@kbn/i18n'; + +const ROOT_BREADCRUMB = { + text: i18n.translate('timelion.breadcrumbs.root', { + defaultMessage: 'Timelion' + }), + href: '#' +}; + +export function getCreateBreadcrumbs() { + return [ + ROOT_BREADCRUMB, + { + text: i18n.translate('timelion.breadcrumbs.create', { + defaultMessage: 'Create' + }), + } + ]; +} + +export function getSavedSheetBreadcrumbs($route) { + const { savedSheet } = $route.current.locals; + return [ + ROOT_BREADCRUMB, + { + text: savedSheet.title, + } + ]; +} diff --git a/src/legacy/core_plugins/timelion/public/index.html b/src/legacy/core_plugins/timelion/public/index.html index 14cad2dd80542..c8afc5442196b 100644 --- a/src/legacy/core_plugins/timelion/public/index.html +++ b/src/legacy/core_plugins/timelion/public/index.html @@ -4,12 +4,15 @@
- - {{opts.savedSheet.lastSavedTitle}} -   - -   - + + + {{opts.savedSheet.lastSavedTitle}} +   + +   + + + Date: Thu, 6 Dec 2018 11:28:16 -0800 Subject: [PATCH 08/85] [es-management] implement k7Breadcrumbs (#26711) * [es-manaagement] implement k7Breadcrumbs * fix i18n ids --- .../public/register_routes.js | 10 ++++++ .../license_management/public/breadcrumbs.js | 32 +++++++++++++++++++ .../public/register_route.js | 13 +++++++- 3 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 x-pack/plugins/license_management/public/breadcrumbs.js diff --git a/x-pack/plugins/index_management/public/register_routes.js b/x-pack/plugins/index_management/public/register_routes.js index 02666e81a0b5c..a9623231e57d9 100644 --- a/x-pack/plugins/index_management/public/register_routes.js +++ b/x-pack/plugins/index_management/public/register_routes.js @@ -8,6 +8,7 @@ import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { HashRouter } from 'react-router-dom'; +import { i18n } from '@kbn/i18n'; import { I18nProvider } from '@kbn/i18n/react'; import { setHttpClient } from './services/api'; @@ -15,6 +16,7 @@ import { App } from './app'; import { BASE_PATH } from '../common/constants/base_path'; import routes from 'ui/routes'; +import { MANAGEMENT_BREADCRUMB } from 'ui/management'; import template from './main.html'; import { manageAngularLifecycle } from './lib/manage_angular_lifecycle'; @@ -35,6 +37,14 @@ const renderReact = async (elem) => { routes.when(`${BASE_PATH}:view?/:id?`, { template: template, + k7Breadcrumbs: () => [ + MANAGEMENT_BREADCRUMB, + { + text: i18n.translate('xpack.idxMgmt.breadcrumb', { + defaultMessage: 'Index management' + }), + } + ], controllerAs: 'indexManagement', controller: class IndexManagementController { constructor($scope, $route, $http) { diff --git a/x-pack/plugins/license_management/public/breadcrumbs.js b/x-pack/plugins/license_management/public/breadcrumbs.js new file mode 100644 index 0000000000000..0de04f4bd70fc --- /dev/null +++ b/x-pack/plugins/license_management/public/breadcrumbs.js @@ -0,0 +1,32 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { i18n } from '@kbn/i18n'; +import { MANAGEMENT_BREADCRUMB } from 'ui/management'; +import { BASE_PATH } from '../common/constants'; + +export function getDashboardBreadcrumbs() { + return [ + MANAGEMENT_BREADCRUMB, + { + text: i18n.translate('xpack.licenseMgmt.dashboard.breadcrumb', { + defaultMessage: 'License management' + }), + href: `#${BASE_PATH}home` + } + ]; +} + +export function getUploadBreadcrumbs() { + return [ + ...getDashboardBreadcrumbs(), + { + text: i18n.translate('xpack.licenseMgmt.upload.breadcrumb', { + defaultMessage: 'Upload' + }) + } + ]; +} diff --git a/x-pack/plugins/license_management/public/register_route.js b/x-pack/plugins/license_management/public/register_route.js index edb2542f3b1be..99ff1e57b5761 100644 --- a/x-pack/plugins/license_management/public/register_route.js +++ b/x-pack/plugins/license_management/public/register_route.js @@ -10,7 +10,7 @@ import { Provider } from 'react-redux'; import { HashRouter } from 'react-router-dom'; import { setTelemetryOptInService, setTelemetryEnabled, setHttpClient, TelemetryOptInProvider } from './lib/telemetry'; import { I18nProvider } from '@kbn/i18n/react'; - +import chrome from 'ui/chrome'; import App from './app'; import { BASE_PATH } from "../common/constants/base_path"; @@ -20,6 +20,7 @@ import { XPackInfoProvider as xpackInfoProvider } from 'plugins/xpack_main/servi import template from './main.html'; import { licenseManagementStore } from './store'; +import { getDashboardBreadcrumbs, getUploadBreadcrumbs } from './breadcrumbs'; const renderReact = (elem, store) => { render( @@ -44,6 +45,8 @@ const manageAngularLifecycle = ($scope, $route, elem) => { const currentRoute = $route.current; // if templates are the same we are on the same route if (lastRoute.$$route.template === currentRoute.$$route.template) { + // update the breadcrumbs by re-running the k7Breadcrumbs function + chrome.breadcrumbs.set(currentRoute.$$route.k7Breadcrumbs($route)); // this prevents angular from destroying scope $route.current = lastRoute; } @@ -65,6 +68,14 @@ const initializeTelemetry = ($injector) => { routes .when(`${BASE_PATH}:view?`, { template: template, + k7Breadcrumbs($route) { + switch ($route.current.params.view) { + case 'upload_license': + return getUploadBreadcrumbs(); + default: + return getDashboardBreadcrumbs(); + } + }, controllerAs: 'licenseManagement', controller: class LicenseManagementController { From 90e88b206f25fbfc3c43f3230edc0df3397af1c7 Mon Sep 17 00:00:00 2001 From: Larry Gregory Date: Thu, 6 Dec 2018 14:48:14 -0500 Subject: [PATCH 09/85] Fixes i18n issue in space nav selector (#26742) ## Summary Wraps the Spaces `NavControlPopover` in ``. Fixes #26736 --- .../public/views/nav_control/nav_control.tsx | 35 +++++++++++-------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/x-pack/plugins/spaces/public/views/nav_control/nav_control.tsx b/x-pack/plugins/spaces/public/views/nav_control/nav_control.tsx index 1c03e1a85db95..8535358fc8fbf 100644 --- a/x-pack/plugins/spaces/public/views/nav_control/nav_control.tsx +++ b/x-pack/plugins/spaces/public/views/nav_control/nav_control.tsx @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ +import { I18nProvider } from '@kbn/i18n/react'; import { constant } from 'lodash'; import { SpacesManager } from 'plugins/spaces/lib/spaces_manager'; // @ts-ignore @@ -13,8 +14,8 @@ import { NavControlPopover } from 'plugins/spaces/views/nav_control/nav_control_ import { PathProvider } from 'plugins/xpack_main/services/path'; import { UserProfileProvider } from 'plugins/xpack_main/services/user_profile'; import React from 'react'; -import ReactDOM from 'react-dom'; import { render, unmountComponentAtNode } from 'react-dom'; +import ReactDOM from 'react-dom'; import { NavControlSide } from 'ui/chrome/directives/header_global_nav'; // @ts-ignore import { uiModules } from 'ui/modules'; @@ -59,13 +60,15 @@ module.controller( $scope.$parent.$watch('isVisible', function isVisibleWatcher(isVisible: boolean) { if (isVisible && !mounted && !pathProvider.isUnauthenticated()) { render( - , + + + , domNode ); mounted = true; @@ -113,13 +116,15 @@ chromeHeaderNavControlsRegistry.register( spacesManager = new SpacesManager($http, chrome, spaceSelectorURL); ReactDOM.render( - , + + + , el ); }, From 72f0c7b23eab215d56074d28ac47b7249d4fe1b4 Mon Sep 17 00:00:00 2001 From: DeDe Morton Date: Thu, 6 Dec 2018 12:50:44 -0800 Subject: [PATCH 10/85] [Docs] Add beta flag to central management docs (#26558) --- docs/management/managing-beats.asciidoc | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/management/managing-beats.asciidoc b/docs/management/managing-beats.asciidoc index 380a8a061beb2..a3802c2e301c7 100644 --- a/docs/management/managing-beats.asciidoc +++ b/docs/management/managing-beats.asciidoc @@ -1,6 +1,9 @@ [[managing-beats]] +[role="xpack"] == Managing {beats} +beta[] + Use the Central Management UI under *Management > {beats}* to define and manage configurations in a central location in {kib} and quickly deploy configuration changes to all {beats} running across your enterprise. For more From cab577b3336ab6e590d140bac2278b1c60ea874f Mon Sep 17 00:00:00 2001 From: Nox911 Date: Fri, 7 Dec 2018 11:05:01 +0300 Subject: [PATCH 11/85] Feature/translate ml-jobs-jobs_list(part_1) (#25466) Translate ml -> jobsList(part_1) --- .i18nrc.json | 1 + .../delete_job_modal/delete_job_modal.js | 49 +++++++++++--- .../edit_job_flyout/edit_job_flyout.js | 62 ++++++++++++++---- .../edit_job_flyout/tabs/custom_urls.js | 56 ++++++++++++---- .../edit_job_flyout/tabs/datafeed.js | 21 ++++-- .../edit_job_flyout/tabs/job_details.js | 27 ++++++-- .../components/job_actions/management.js | 49 ++++++++++---- .../components/job_actions/results.js | 27 ++++++-- .../components/jobs_list/jobs_list.js | 65 +++++++++++++++---- .../jobs_stats_bar/jobs_stats_bar.js | 49 ++++++++++++-- .../multi_job_actions/actions_menu.js | 37 ++++++++--- .../multi_job_actions/multi_job_actions.js | 10 ++- .../new_job_button/new_job_button.js | 6 +- .../node_available_warning.js | 39 ++++++++--- .../refresh_jobs_list_button.js | 6 +- .../start_datafeed_modal.js | 26 ++++++-- .../time_range_selector.js | 56 ++++++++++++++-- .../ml/public/jobs/jobs_list/directive.js | 3 +- 18 files changed, 480 insertions(+), 109 deletions(-) diff --git a/.i18nrc.json b/.i18nrc.json index 6e1ca0c88939f..6f72f29cbc4c7 100644 --- a/.i18nrc.json +++ b/.i18nrc.json @@ -22,6 +22,7 @@ "xpack.idxMgmt": "x-pack/plugins/index_management", "xpack.infra": "x-pack/plugins/infra", "xpack.licenseMgmt": "x-pack/plugins/license_management", + "xpack.ml": "x-pack/plugins/ml", "xpack.logstash": "x-pack/plugins/logstash", "xpack.monitoring": "x-pack/plugins/monitoring", "xpack.reporting": "x-pack/plugins/reporting", diff --git a/x-pack/plugins/ml/public/jobs/jobs_list/components/delete_job_modal/delete_job_modal.js b/x-pack/plugins/ml/public/jobs/jobs_list/components/delete_job_modal/delete_job_modal.js index fd148bd37ea9a..7b80a3678dd09 100644 --- a/x-pack/plugins/ml/public/jobs/jobs_list/components/delete_job_modal/delete_job_modal.js +++ b/x-pack/plugins/ml/public/jobs/jobs_list/components/delete_job_modal/delete_job_modal.js @@ -19,6 +19,7 @@ import { } from '@elastic/eui'; import { deleteJobs } from '../utils'; +import { FormattedMessage } from '@kbn/i18n/react'; export class DeleteJobModal extends Component { constructor(props) { @@ -79,10 +80,21 @@ export class DeleteJobModal extends Component { if (this.el && this.state.deleting === true) { // work around to disable the modal's buttons if the jobs are being deleted this.el.confirmButton.style.display = 'none'; - this.el.cancelButton.textContent = 'Close'; + this.el.cancelButton.textContent = (); } - const title = `Delete ${(this.state.jobs.length > 1) ? `${this.state.jobs.length} jobs` : this.state.jobs[0].id}`; + const title = ( + ); modal = ( )} + confirmButtonText={()} buttonColor="danger" defaultFocusedButton={EUI_MODAL_CONFIRM_BUTTON} className="eui-textBreakWord" > {(this.state.deleting === true) &&
- Deleting jobs +
@@ -108,10 +129,22 @@ export class DeleteJobModal extends Component { {(this.state.deleting === false) && -

Are you sure you want to delete {(this.state.jobs.length > 1) ? 'these jobs' : 'this job'}?

+

+ +

{(this.state.jobs.length > 1) && -

Deleting multiple jobs can be time consuming. - They will be deleted in the background and may not disappear from the jobs list instantly +

+

}
diff --git a/x-pack/plugins/ml/public/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js b/x-pack/plugins/ml/public/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js index 734e38844bd73..51eb70098aebe 100644 --- a/x-pack/plugins/ml/public/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js +++ b/x-pack/plugins/ml/public/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js @@ -32,8 +32,9 @@ import { isValidCustomUrls } from '../validate_job'; import { mlMessageBarService } from '../../../../components/messagebar/messagebar_service'; import { toastNotifications } from 'ui/notify'; +import { FormattedMessage, injectI18n } from '@kbn/i18n/react'; -export class EditJobFlyout extends Component { +class EditJobFlyoutUI extends Component { constructor(props) { super(props); @@ -134,7 +135,10 @@ export class EditJobFlyout extends Component { if (jobDetails.jobGroups !== undefined) { if (jobDetails.jobGroups.some(j => this.props.allJobIds.includes(j))) { - jobGroupsValidationError = 'A job with this ID already exists. Groups and jobs cannot use the same ID.'; + jobGroupsValidationError = this.props.intl.formatMessage({ + id: 'xpack.ml.jobsList.editJobFlyout.groupsAndJobsHasSameIdErrorMessage', + defaultMessage: 'A job with this ID already exists. Groups and jobs cannot use the same ID.' + }); } else { jobGroupsValidationError = validateGroupNames(jobDetails.jobGroups).message; } @@ -185,13 +189,21 @@ export class EditJobFlyout extends Component { saveJob(this.state.job, newJobData) .then(() => { - toastNotifications.addSuccess(`Changes to ${this.state.job.job_id} saved`); + toastNotifications.addSuccess(this.props.intl.formatMessage({ + id: 'xpack.ml.jobsList.editJobFlyout.changesSavedNotificationMessage', + defaultMessage: 'Changes to {jobId} saved' }, { + jobId: this.state.job.job_id } + )); this.refreshJobs(); this.closeFlyout(); }) .catch((error) => { console.error(error); - toastNotifications.addDanger(`Could not save changes to ${this.state.job.job_id}`); + toastNotifications.addDanger(this.props.intl.formatMessage({ + id: 'xpack.ml.jobsList.editJobFlyout.changesNotSavedNotificationMessage', + defaultMessage: 'Could not save changes to {jobId}' }, { + jobId: this.state.job.job_id } + )); mlMessageBarService.notify.error(error); }); } @@ -219,9 +231,14 @@ export class EditJobFlyout extends Component { isValidJobCustomUrls, } = this.state; + const { intl } = this.props; + const tabs = [{ id: 'job-details', - name: 'Job details', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.editJobFlyout.jobDetailsTitle', + defaultMessage: 'Job details' + }), content: , }, { id: 'detectors', - name: 'Detectors', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.editJobFlyout.detectorsTitle', + defaultMessage: 'Detectors' + }), content: , }, { id: 'datafeed', - name: 'Datafeed', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.editJobFlyout.datafeedTitle', + defaultMessage: 'Datafeed' + }), content: , }, { id: 'custom-urls', - name: 'Custom URLs', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.editJobFlyout.customUrlsTitle', + defaultMessage: 'Custom URLs' + }), content:

- Edit {job.id} +

@@ -290,7 +320,10 @@ export class EditJobFlyout extends Component { onClick={this.closeFlyout} flush="left" > - Close + @@ -299,7 +332,10 @@ export class EditJobFlyout extends Component { fill isDisabled={(isValidJobDetails === false) || (isValidJobCustomUrls === false)} > - Save + @@ -317,9 +353,11 @@ export class EditJobFlyout extends Component { } } -EditJobFlyout.propTypes = { +EditJobFlyoutUI.propTypes = { setShowFunction: PropTypes.func.isRequired, unsetShowFunction: PropTypes.func.isRequired, refreshJobs: PropTypes.func.isRequired, allJobIds: PropTypes.array.isRequired, }; + +export const EditJobFlyout = injectI18n(EditJobFlyoutUI); diff --git a/x-pack/plugins/ml/public/jobs/jobs_list/components/edit_job_flyout/tabs/custom_urls.js b/x-pack/plugins/ml/public/jobs/jobs_list/components/edit_job_flyout/tabs/custom_urls.js index 1a8e36b539099..49964514a21fa 100644 --- a/x-pack/plugins/ml/public/jobs/jobs_list/components/edit_job_flyout/tabs/custom_urls.js +++ b/x-pack/plugins/ml/public/jobs/jobs_list/components/edit_job_flyout/tabs/custom_urls.js @@ -37,10 +37,12 @@ import { loadIndexPatterns, } from '../edit_utils'; +import { FormattedMessage, injectI18n } from '@kbn/i18n/react'; + const MAX_NUMBER_DASHBOARDS = 1000; const MAX_NUMBER_INDEX_PATTERNS = 1000; -export class CustomUrls extends Component { +class CustomUrlsUI extends Component { constructor(props) { super(props); @@ -65,13 +67,18 @@ export class CustomUrls extends Component { } componentDidMount() { + const { intl } = this.props; + loadSavedDashboards(MAX_NUMBER_DASHBOARDS) .then((dashboards)=> { this.setState({ dashboards }); }) .catch((resp) => { console.log('Error loading list of dashboards:', resp); - toastNotifications.addDanger('An error occurred loading the list of saved Kibana dashboards'); + toastNotifications.addDanger(intl.formatMessage({ + id: 'xpack.ml.jobsList.editJobFlyout.customUrls.loadSavedDashboardsErrorNotificationMessage', + defaultMessage: 'An error occurred loading the list of saved Kibana dashboards' + })); }); loadIndexPatterns(MAX_NUMBER_INDEX_PATTERNS) @@ -80,7 +87,10 @@ export class CustomUrls extends Component { }) .catch((resp) => { console.log('Error loading list of dashboards:', resp); - toastNotifications.addDanger('An error occurred loading the list of saved index patterns'); + toastNotifications.addDanger(intl.formatMessage({ + id: 'xpack.ml.jobsList.editJobFlyout.customUrls.loadIndexPatternsErrorNotificationMessage', + defaultMessage: 'An error occurred loading the list of saved index patterns' + })); }); } @@ -111,12 +121,16 @@ export class CustomUrls extends Component { }) .catch((resp) => { console.log('Error building custom URL from settings:', resp); - toastNotifications.addDanger('An error occurred building the new custom URL from the supplied settings'); + toastNotifications.addDanger(this.props.intl.formatMessage({ + id: 'xpack.ml.jobsList.editJobFlyout.customUrls.addNewUrlErrorNotificationMessage', + defaultMessage: 'An error occurred building the new custom URL from the supplied settings' + })); }); } onTestButtonClick = () => { const job = this.props.job; + const { intl } = this.props; buildCustomUrlFromSettings(this.state.editorSettings, job) .then((customUrl) => { getTestUrl(job, customUrl) @@ -125,12 +139,18 @@ export class CustomUrls extends Component { }) .catch((resp) => { console.log('Error obtaining URL for test:', resp); - toastNotifications.addWarning('An error occurred obtaining the URL to test the configuration'); + toastNotifications.addWarning(intl.formatMessage({ + id: 'xpack.ml.jobsList.editJobFlyout.customUrls.getTestUrlErrorNotificationMessage', + defaultMessage: 'An error occurred obtaining the URL to test the configuration' + })); }); }) .catch((resp) => { console.log('Error building custom URL from settings:', resp); - toastNotifications.addWarning('An error occurred building the custom URL for testing from the supplied settings'); + toastNotifications.addWarning(intl.formatMessage({ + id: 'xpack.ml.jobsList.editJobFlyout.customUrls.buildUrlErrorNotificationMessage', + defaultMessage: 'An error occurred building the custom URL for testing from the supplied settings' + })); }); } @@ -160,7 +180,10 @@ export class CustomUrls extends Component { size="s" onClick={() => this.editNewCustomUrl()} > - Add custom URL + ) : ( @@ -170,7 +193,10 @@ export class CustomUrls extends Component { color="text" onClick={() => this.closeEditor()} iconType="cross" - aria-label="Close custom URL editor" + aria-label={this.props.intl.formatMessage({ + id: 'xpack.ml.jobsList.editJobFlyout.customUrls.closeEditorAriaLabel', + defaultMessage: 'Close custom URL editor' + })} className="close-editor-button" /> this.addNewCustomUrl()} isDisabled={!isValidEditorSettings} > - Add + @@ -198,7 +227,10 @@ export class CustomUrls extends Component { onClick={() => this.onTestButtonClick()} isDisabled={!isValidEditorSettings} > - Test + @@ -217,8 +249,10 @@ export class CustomUrls extends Component { ); } } -CustomUrls.propTypes = { +CustomUrlsUI.propTypes = { job: PropTypes.object.isRequired, jobCustomUrls: PropTypes.array.isRequired, setCustomUrls: PropTypes.func.isRequired, }; + +export const CustomUrls = injectI18n(CustomUrlsUI); diff --git a/x-pack/plugins/ml/public/jobs/jobs_list/components/edit_job_flyout/tabs/datafeed.js b/x-pack/plugins/ml/public/jobs/jobs_list/components/edit_job_flyout/tabs/datafeed.js index 4d1dca27389ad..c9e431dee846e 100644 --- a/x-pack/plugins/ml/public/jobs/jobs_list/components/edit_job_flyout/tabs/datafeed.js +++ b/x-pack/plugins/ml/public/jobs/jobs_list/components/edit_job_flyout/tabs/datafeed.js @@ -22,6 +22,7 @@ import { calculateDatafeedFrequencyDefaultSeconds } from 'plugins/ml/../common/u import { newJobDefaults } from 'plugins/ml/jobs/new_job/utils/new_job_defaults'; import { parseInterval } from 'plugins/ml/../common/util/parse_interval'; import { MLJobEditor } from '../../ml_job_editor'; +import { FormattedMessage } from '@kbn/i18n/react'; function getDefaults(bucketSpan, jobDefaults) { const bucketSpanSeconds = (bucketSpan !== undefined) ? parseInterval(bucketSpan).asSeconds() : ''; @@ -91,7 +92,10 @@ export class Datafeed extends Component { )} style={{ maxWidth: 'inherit' }} > )} > )} > )} > )} > )} isInvalid={(groupsValidationError !== '')} error={groupsValidationError} > )} isInvalid={(mmlValidationError !== '')} error={mmlValidationError} > @@ -155,9 +168,11 @@ export class JobDetails extends Component { ); } } -JobDetails.propTypes = { +JobDetailsUI.propTypes = { jobDescription: PropTypes.string.isRequired, jobGroups: PropTypes.array.isRequired, jobModelMemoryLimit: PropTypes.string.isRequired, setJobDetails: PropTypes.func.isRequired, }; + +export const JobDetails = injectI18n(JobDetailsUI); diff --git a/x-pack/plugins/ml/public/jobs/jobs_list/components/job_actions/management.js b/x-pack/plugins/ml/public/jobs/jobs_list/components/job_actions/management.js index 4aa47dfd177fa..7234e3f9252d9 100644 --- a/x-pack/plugins/ml/public/jobs/jobs_list/components/job_actions/management.js +++ b/x-pack/plugins/ml/public/jobs/jobs_list/components/job_actions/management.js @@ -15,6 +15,7 @@ import { isStoppable, isClosable, } from '../utils'; +import { i18n } from '@kbn/i18n'; export function actionsMenuContent(showEditJobFlyout, showDeleteJobModal, showStartDatafeedModal, refreshJobs) { const canCreateJob = (checkPermission('canCreateJob') && mlNodesAvailable()); @@ -26,8 +27,12 @@ export function actionsMenuContent(showEditJobFlyout, showDeleteJobModal, showSt return [ { - name: 'Start datafeed', - description: 'Start datafeed', + name: i18n.translate('xpack.ml.jobsList.managementActions.startDatafeedLabel', { + defaultMessage: 'Start datafeed' + }), + description: i18n.translate('xpack.ml.jobsList.managementActions.startDatafeedDescription', { + defaultMessage: 'Start datafeed' + }), icon: 'play', enabled: () => (canStartStopDatafeed), available: (item) => (isStartable([item])), @@ -36,8 +41,12 @@ export function actionsMenuContent(showEditJobFlyout, showDeleteJobModal, showSt closeMenu(); } }, { - name: 'Stop datafeed', - description: 'Stop datafeed', + name: i18n.translate('xpack.ml.jobsList.managementActions.stopDatafeedLabel', { + defaultMessage: 'Stop datafeed' + }), + description: i18n.translate('xpack.ml.jobsList.managementActions.stopDatafeedDescription', { + defaultMessage: 'Stop datafeed' + }), icon: 'stop', enabled: () => (canStartStopDatafeed), available: (item) => (isStoppable([item])), @@ -46,8 +55,12 @@ export function actionsMenuContent(showEditJobFlyout, showDeleteJobModal, showSt closeMenu(true); } }, { - name: 'Close job', - description: 'Close job', + name: i18n.translate('xpack.ml.jobsList.managementActions.closeJobLabel', { + defaultMessage: 'Close job' + }), + description: i18n.translate('xpack.ml.jobsList.managementActions.closeJobDescription', { + defaultMessage: 'Close job' + }), icon: 'cross', enabled: () => (canCloseJob), available: (item) => (isClosable([item])), @@ -56,8 +69,12 @@ export function actionsMenuContent(showEditJobFlyout, showDeleteJobModal, showSt closeMenu(true); } }, { - name: 'Clone job', - description: 'Clone job', + name: i18n.translate('xpack.ml.jobsList.managementActions.cloneJobLabel', { + defaultMessage: 'Clone job' + }), + description: i18n.translate('xpack.ml.jobsList.managementActions.cloneJobDescription', { + defaultMessage: 'Clone job' + }), icon: 'copy', enabled: () => (canCreateJob), onClick: (item) => { @@ -65,8 +82,12 @@ export function actionsMenuContent(showEditJobFlyout, showDeleteJobModal, showSt closeMenu(true); } }, { - name: 'Edit job', - description: 'Edit job', + name: i18n.translate('xpack.ml.jobsList.managementActions.editJobLabel', { + defaultMessage: 'Edit job' + }), + description: i18n.translate('xpack.ml.jobsList.managementActions.editJobDescription', { + defaultMessage: 'Edit job' + }), icon: 'pencil', enabled: () => (canUpdateJob && canUpdateDatafeed), onClick: (item) => { @@ -74,8 +95,12 @@ export function actionsMenuContent(showEditJobFlyout, showDeleteJobModal, showSt closeMenu(); } }, { - name: 'Delete job', - description: 'Delete job', + name: i18n.translate('xpack.ml.jobsList.managementActions.deleteJobLabel', { + defaultMessage: 'Delete job' + }), + description: i18n.translate('xpack.ml.jobsList.managementActions.deleteJobDescription', { + defaultMessage: 'Delete job' + }), icon: 'trash', color: 'danger', enabled: () => (canDeleteJob), diff --git a/x-pack/plugins/ml/public/jobs/jobs_list/components/job_actions/results.js b/x-pack/plugins/ml/public/jobs/jobs_list/components/job_actions/results.js index 486d27e8b9dbb..054ce12f65935 100644 --- a/x-pack/plugins/ml/public/jobs/jobs_list/components/job_actions/results.js +++ b/x-pack/plugins/ml/public/jobs/jobs_list/components/job_actions/results.js @@ -18,6 +18,7 @@ import moment from 'moment'; const TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss'; import { mlJobService } from 'plugins/ml/services/job_service'; +import { injectI18n } from '@kbn/i18n/react'; function getLink(location, jobs) { let from = 0; @@ -38,8 +39,19 @@ function getLink(location, jobs) { return `${chrome.getBasePath()}/app/${url}`; } -export function ResultLinks({ jobs }) { - const tooltipJobs = (jobs.length === 1) ? jobs[0].id : `${jobs.length} jobs`; +function ResultLinksUI({ jobs, intl }) { + const openJobsInSingleMetricViewerText = intl.formatMessage({ + id: 'xpack.ml.jobsList.resultActions.openJobsInSingleMetricViewerText', + defaultMessage: 'Open {jobsCount, plural, one {{jobId}} other {# jobs}} in Single Metric Viewer' }, { + jobsCount: jobs.length, + jobId: jobs[0].id + }); + const openJobsInAnomalyExplorerText = intl.formatMessage({ + id: 'xpack.ml.jobsList.resultActions.openJobsInAnomalyExplorerText', + defaultMessage: 'Open {jobsCount, plural, one {{jobId}} other {# jobs}} in Anomaly Explorer' }, { + jobsCount: jobs.length, + jobId: jobs[0].id + }); const singleMetricVisible = (jobs.length < 2); const singleMetricEnabled = (jobs.length === 1 && jobs[0].isSingleMetricViewerJob); return ( @@ -47,12 +59,12 @@ export function ResultLinks({ jobs }) { {(singleMetricVisible) && @@ -60,12 +72,12 @@ export function ResultLinks({ jobs }) { } @@ -73,7 +85,8 @@ export function ResultLinks({ jobs }) { ); } -ResultLinks.propTypes = { +ResultLinksUI.propTypes = { jobs: PropTypes.array.isRequired, }; +export const ResultLinks = injectI18n(ResultLinksUI); diff --git a/x-pack/plugins/ml/public/jobs/jobs_list/components/jobs_list/jobs_list.js b/x-pack/plugins/ml/public/jobs/jobs_list/components/jobs_list/jobs_list.js index 0165b26095b16..5a495352bdb6f 100644 --- a/x-pack/plugins/ml/public/jobs/jobs_list/components/jobs_list/jobs_list.js +++ b/x-pack/plugins/ml/public/jobs/jobs_list/components/jobs_list/jobs_list.js @@ -22,12 +22,13 @@ import { EuiBasicTable, EuiButtonIcon, } from '@elastic/eui'; +import { injectI18n } from '@kbn/i18n/react'; const PAGE_SIZE = 10; const PAGE_SIZE_OPTIONS = [10, 25, 50]; const TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss'; -export class JobsList extends Component { +class JobsListUI extends Component { constructor(props) { super(props); @@ -97,9 +98,13 @@ export class JobsList extends Component { } render() { + const { intl } = this.props; const selectionControls = { selectable: () => true, - selectableMessage: (selectable) => (!selectable) ? 'Cannot select job' : undefined, + selectableMessage: (selectable) => (!selectable) ? intl.formatMessage({ + id: 'xpack.ml.jobsList.cannotSelectJobTooltip', + defaultMessage: 'Cannot select job' }) + : undefined, onSelectionChange: this.props.selectJobChange }; @@ -110,13 +115,26 @@ export class JobsList extends Component { this.toggleRow(item)} iconType={this.state.itemIdToExpandedRowMap[item.id] ? 'arrowDown' : 'arrowRight'} - aria-label={`${this.state.itemIdToExpandedRowMap[item.id] ? 'Hide' : 'Show'} details for ${item.id}`} + aria-label={this.state.itemIdToExpandedRowMap[item.id] + ? intl.formatMessage({ + id: 'xpack.ml.jobsList.collapseJobDetailsAriaLabel', + defaultMessage: 'Hide details for {itemId}' }, + { itemId: item.id } + ) + : intl.formatMessage({ + id: 'xpack.ml.jobsList.expandJobDetailsAriaLabel', + defaultMessage: 'Show details for {itemId}' }, + { itemId: item.id } + )} data-row-id={item.id} /> ) }, { field: 'id', - name: 'ID', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.idLabel', + defaultMessage: 'ID' + }), sortable: true, truncateText: false, @@ -127,7 +145,10 @@ export class JobsList extends Component { ) }, { - name: 'Description', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.descriptionLabel', + defaultMessage: 'Description' + }), sortable: true, field: 'description', render: (description, item) => ( @@ -135,28 +156,43 @@ export class JobsList extends Component { ) }, { field: 'processed_record_count', - name: 'Processed records', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.processedRecordsLabel', + defaultMessage: 'Processed records' + }), sortable: true, truncateText: false, dataType: 'number', render: count => toLocaleString(count) }, { field: 'memory_status', - name: 'Memory status', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.memoryStatusLabel', + defaultMessage: 'Memory status' + }), sortable: true, truncateText: false, }, { field: 'jobState', - name: 'Job state', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobStateLabel', + defaultMessage: 'Job state' + }), sortable: true, truncateText: false, }, { field: 'datafeedState', - name: 'Datafeed state', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.datafeedStateLabel', + defaultMessage: 'Datafeed state' + }), sortable: true, truncateText: false, }, { - name: 'Latest timestamp', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.latestTimestampLabel', + defaultMessage: 'Latest timestamp' + }), truncateText: false, field: 'latestTimestampSortValue', sortable: true, @@ -168,7 +204,10 @@ export class JobsList extends Component { ) }, { - name: 'Actions', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.actionsLabel', + defaultMessage: 'Actions' + }), render: (item) => ( ) @@ -228,7 +267,7 @@ export class JobsList extends Component { ); } } -JobsList.propTypes = { +JobsListUI.propTypes = { jobsSummaryList: PropTypes.array.isRequired, fullJobsList: PropTypes.object.isRequired, itemIdToExpandedRowMap: PropTypes.object.isRequired, @@ -240,3 +279,5 @@ JobsList.propTypes = { refreshJobs: PropTypes.func.isRequired, selectedJobsCount: PropTypes.number.isRequired, }; + +export const JobsList = injectI18n(JobsListUI); diff --git a/x-pack/plugins/ml/public/jobs/jobs_list/components/jobs_stats_bar/jobs_stats_bar.js b/x-pack/plugins/ml/public/jobs/jobs_list/components/jobs_stats_bar/jobs_stats_bar.js index 79cc8bf8ee861..5af623cb82449 100644 --- a/x-pack/plugins/ml/public/jobs/jobs_list/components/jobs_stats_bar/jobs_stats_bar.js +++ b/x-pack/plugins/ml/public/jobs/jobs_list/components/jobs_stats_bar/jobs_stats_bar.js @@ -9,16 +9,53 @@ import { JOB_STATE, DATAFEED_STATE } from 'plugins/ml/../common/constants/states import PropTypes from 'prop-types'; import React from 'react'; +import { i18n } from '@kbn/i18n'; function createJobStats(jobsSummaryList) { const jobStats = { - activeNodes: { label: 'Active ML Nodes', value: 0, show: true }, - total: { label: 'Total jobs', value: 0, show: true }, - open: { label: 'Open jobs', value: 0, show: true }, - closed: { label: 'Closed jobs', value: 0, show: true }, - failed: { label: 'Failed jobs', value: 0, show: false }, - activeDatafeeds: { label: 'Active datafeeds', value: 0, show: true } + activeNodes: { + label: i18n.translate('xpack.ml.jobsList.statsBar.activeMLNodesLabel', { + defaultMessage: 'Active ML Nodes' + }), + value: 0, + show: true + }, + total: { + label: i18n.translate('xpack.ml.jobsList.statsBar.totalJobsLabel', { + defaultMessage: 'Total jobs' + }), + value: 0, + show: true + }, + open: { + label: i18n.translate('xpack.ml.jobsList.statsBar.openJobsLabel', { + defaultMessage: 'Open jobs' + }), + value: 0, + show: true + }, + closed: { + label: i18n.translate('xpack.ml.jobsList.statsBar.closedJobsLabel', { + defaultMessage: 'Closed jobs' + }), + value: 0, + show: true + }, + failed: { + label: i18n.translate('xpack.ml.jobsList.statsBar.failedJobsLabel', { + defaultMessage: 'Failed jobs' + }), + value: 0, + show: false + }, + activeDatafeeds: { + label: i18n.translate('xpack.ml.jobsList.statsBar.activeDatafeedsLabel', { + defaultMessage: 'Active datafeeds' + }), + value: 0, + show: true + } }; if (jobsSummaryList === undefined) { diff --git a/x-pack/plugins/ml/public/jobs/jobs_list/components/multi_job_actions/actions_menu.js b/x-pack/plugins/ml/public/jobs/jobs_list/components/multi_job_actions/actions_menu.js index c4fbc39eba7c7..571203b5fa99e 100644 --- a/x-pack/plugins/ml/public/jobs/jobs_list/components/multi_job_actions/actions_menu.js +++ b/x-pack/plugins/ml/public/jobs/jobs_list/components/multi_job_actions/actions_menu.js @@ -26,8 +26,9 @@ import { isStoppable, isClosable, } from '../utils'; +import { FormattedMessage, injectI18n } from '@kbn/i18n/react'; -export class MultiJobActionsMenu extends Component { +class MultiJobActionsMenuUI extends Component { constructor(props) { super(props); @@ -58,13 +59,15 @@ export class MultiJobActionsMenu extends Component { size="s" onClick={this.onButtonClick} iconType="gear" - aria-label="Management actions" + aria-label={this.props.intl.formatMessage({ + id: 'xpack.ml.jobsList.multiJobActionsMenu.managementActionsAriaLabel', + defaultMessage: 'Management actions' + })} color="text" disabled={(this.canDeleteJob === false && this.canStartStopDatafeed === false)} /> ); - const s = (this.props.jobs.length > 1) ? 's' : ''; const items = [ ( { this.props.showDeleteJobModal(this.props.jobs); this.closePopover(); }} > - Delete job{s} + ) ]; @@ -86,7 +93,11 @@ export class MultiJobActionsMenu extends Component { disabled={(this.canCloseJob === false)} onClick={() => { closeJobs(this.props.jobs); this.closePopover(); }} > - Close job{s} + ); } @@ -99,7 +110,11 @@ export class MultiJobActionsMenu extends Component { disabled={(this.canStartStopDatafeed === false)} onClick={() => { stopDatafeeds(this.props.jobs, this.props.refreshJobs); this.closePopover(); }} > - Stop datafeed{s} + ); } @@ -112,7 +127,11 @@ export class MultiJobActionsMenu extends Component { disabled={(this.canStartStopDatafeed === false)} onClick={() => { this.props.showStartDatafeedModal(this.props.jobs); this.closePopover(); }} > - Start datafeed{s} + ); } @@ -132,9 +151,11 @@ export class MultiJobActionsMenu extends Component { ); } } -MultiJobActionsMenu.propTypes = { +MultiJobActionsMenuUI.propTypes = { jobs: PropTypes.array.isRequired, showStartDatafeedModal: PropTypes.func.isRequired, showDeleteJobModal: PropTypes.func.isRequired, refreshJobs: PropTypes.func.isRequired, }; + +export const MultiJobActionsMenu = injectI18n(MultiJobActionsMenuUI); diff --git a/x-pack/plugins/ml/public/jobs/jobs_list/components/multi_job_actions/multi_job_actions.js b/x-pack/plugins/ml/public/jobs/jobs_list/components/multi_job_actions/multi_job_actions.js index 4089b2b3e5881..26017bad23ea6 100644 --- a/x-pack/plugins/ml/public/jobs/jobs_list/components/multi_job_actions/multi_job_actions.js +++ b/x-pack/plugins/ml/public/jobs/jobs_list/components/multi_job_actions/multi_job_actions.js @@ -13,6 +13,7 @@ import React, { import { ResultLinks } from '../job_actions'; import { MultiJobActionsMenu } from './actions_menu'; import { GroupSelector } from './group_selector'; +import { FormattedMessage } from '@kbn/i18n/react'; export class MultiJobActions extends Component { constructor(props) { @@ -22,13 +23,18 @@ export class MultiJobActions extends Component { } render() { - const s = (this.props.selectedJobs.length > 1) ? 's' : ''; const jobsSelected = (this.props.selectedJobs.length > 0); return (
{jobsSelected && - {this.props.selectedJobs.length} job{s} selected + + +
diff --git a/x-pack/plugins/ml/public/jobs/jobs_list/components/new_job_button/new_job_button.js b/x-pack/plugins/ml/public/jobs/jobs_list/components/new_job_button/new_job_button.js index df61ddf6decdb..6c56b4c8b1076 100644 --- a/x-pack/plugins/ml/public/jobs/jobs_list/components/new_job_button/new_job_button.js +++ b/x-pack/plugins/ml/public/jobs/jobs_list/components/new_job_button/new_job_button.js @@ -14,6 +14,7 @@ import React from 'react'; import { EuiButton, } from '@elastic/eui'; +import { FormattedMessage } from '@kbn/i18n/react'; function newJob() { window.location.href = `#/jobs/new_job`; @@ -29,7 +30,10 @@ export function NewJobButton() { fill iconType="plusInCircle" > - Create new job + ); } diff --git a/x-pack/plugins/ml/public/jobs/jobs_list/components/node_available_warning/node_available_warning.js b/x-pack/plugins/ml/public/jobs/jobs_list/components/node_available_warning/node_available_warning.js index 7e0d39ffd4c07..b8bf465eea576 100644 --- a/x-pack/plugins/ml/public/jobs/jobs_list/components/node_available_warning/node_available_warning.js +++ b/x-pack/plugins/ml/public/jobs/jobs_list/components/node_available_warning/node_available_warning.js @@ -14,6 +14,7 @@ import { EuiLink, EuiSpacer, } from '@elastic/eui'; +import { FormattedMessage } from '@kbn/i18n/react'; export function NodeAvailableWarning() { const isCloud = false; // placeholder for future specific cloud functionality @@ -23,18 +24,40 @@ export function NodeAvailableWarning() { return ( )} color="warning" iconType="alert" >

- There are no ML nodes available.
- You will not be able to create or run jobs. - {isCloud && - -  This can be configured in Cloud here. - - } +
+ + + + ) + }} + /> + : '', + }} + />

diff --git a/x-pack/plugins/ml/public/jobs/jobs_list/components/refresh_jobs_list_button/refresh_jobs_list_button.js b/x-pack/plugins/ml/public/jobs/jobs_list/components/refresh_jobs_list_button/refresh_jobs_list_button.js index 3aecf95d55f56..72338915cc1fc 100644 --- a/x-pack/plugins/ml/public/jobs/jobs_list/components/refresh_jobs_list_button/refresh_jobs_list_button.js +++ b/x-pack/plugins/ml/public/jobs/jobs_list/components/refresh_jobs_list_button/refresh_jobs_list_button.js @@ -12,6 +12,7 @@ import PropTypes from 'prop-types'; import { EuiButtonEmpty, } from '@elastic/eui'; +import { FormattedMessage } from '@kbn/i18n/react'; export const RefreshJobsListButton = ({ onRefreshClick, isRefreshing }) => ( @@ -19,7 +20,10 @@ export const RefreshJobsListButton = ({ onRefreshClick, isRefreshing }) => ( onClick={onRefreshClick} isLoading={isRefreshing} > - Refresh + ); diff --git a/x-pack/plugins/ml/public/jobs/jobs_list/components/start_datafeed_modal/start_datafeed_modal.js b/x-pack/plugins/ml/public/jobs/jobs_list/components/start_datafeed_modal/start_datafeed_modal.js index f37db8d6309fc..6617f3cdc81ae 100644 --- a/x-pack/plugins/ml/public/jobs/jobs_list/components/start_datafeed_modal/start_datafeed_modal.js +++ b/x-pack/plugins/ml/public/jobs/jobs_list/components/start_datafeed_modal/start_datafeed_modal.js @@ -30,6 +30,8 @@ import { forceStartDatafeeds } from '../utils'; import { TimeRangeSelector } from './time_range_selector'; +import { FormattedMessage } from '@kbn/i18n/react'; + export class StartDatafeedModal extends Component { constructor(props) { super(props); @@ -136,7 +138,14 @@ export class StartDatafeedModal extends Component { > - Start {(startableJobs.length > 1) ? `${startableJobs.length} jobs` : startableJobs[0].id} + @@ -154,7 +163,10 @@ export class StartDatafeedModal extends Component { )} checked={createWatch} onChange={this.setCreateWatch} /> @@ -166,7 +178,10 @@ export class StartDatafeedModal extends Component { - Cancel + - Start + diff --git a/x-pack/plugins/ml/public/jobs/jobs_list/components/start_datafeed_modal/time_range_selector/time_range_selector.js b/x-pack/plugins/ml/public/jobs/jobs_list/components/start_datafeed_modal/time_range_selector/time_range_selector.js index d3b815ac253d5..d7b2b5ddf18ea 100644 --- a/x-pack/plugins/ml/public/jobs/jobs_list/components/start_datafeed_modal/time_range_selector/time_range_selector.js +++ b/x-pack/plugins/ml/public/jobs/jobs_list/components/start_datafeed_modal/time_range_selector/time_range_selector.js @@ -15,6 +15,7 @@ import { } from '@elastic/eui'; import moment from 'moment'; +import { FormattedMessage } from '@kbn/i18n/react'; const TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss'; @@ -78,8 +79,34 @@ export class TimeRangeSelector extends Component { // the job has seen any data yet const showContinueLabels = (this.latestTimestamp.valueOf() > 0); const startLabels = (showContinueLabels === true) ? - [`Continue from ${formattedStartTime}`, 'Continue from now', 'Continue from specified time'] : - ['Start at beginning of data', 'Start from now', 'Specify start time']; + [ + (), + (), + () + ] : [ + (), + (), + () + ]; const startItems = [ { index: 0, label: startLabels[0] }, @@ -96,8 +123,19 @@ export class TimeRangeSelector extends Component { }, ]; const endItems = [ - { index: 0, label: 'No end time (Real-time search)' }, - { index: 1, label: 'Specify end time', + { + index: 0, + label: () + }, + { + index: 1, + label: (), body: (
)} items={startItems} switchState={this.state.startTab} switchFunc={this.setStartTab} /> )} items={endItems} switchState={this.state.endTab} switchFunc={this.setEndTab} diff --git a/x-pack/plugins/ml/public/jobs/jobs_list/directive.js b/x-pack/plugins/ml/public/jobs/jobs_list/directive.js index 84164c5213e70..030524baff642 100644 --- a/x-pack/plugins/ml/public/jobs/jobs_list/directive.js +++ b/x-pack/plugins/ml/public/jobs/jobs_list/directive.js @@ -34,6 +34,7 @@ uiRoutes }); import { JobsPage } from './jobs'; +import { I18nProvider } from '@kbn/i18n/react'; module.directive('jobsPage', function () { return { @@ -41,7 +42,7 @@ module.directive('jobsPage', function () { restrict: 'E', link: (scope, element) => { ReactDOM.render( - React.createElement(JobsPage), + {React.createElement(JobsPage)}, element[0] ); } From a1a1b52b1ba374fa996a67ad8385c08f59c8e990 Mon Sep 17 00:00:00 2001 From: szydan Date: Fri, 7 Dec 2018 12:36:53 +0000 Subject: [PATCH 12/85] Corrected wrong calls from .on to .off (#24575) Closing memory leak --- .../metrics/public/visualizations/components/flot_chart.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/legacy/core_plugins/metrics/public/visualizations/components/flot_chart.js b/src/legacy/core_plugins/metrics/public/visualizations/components/flot_chart.js index 8e1ea8c9ae2a4..a50720dd1769a 100644 --- a/src/legacy/core_plugins/metrics/public/visualizations/components/flot_chart.js +++ b/src/legacy/core_plugins/metrics/public/visualizations/components/flot_chart.js @@ -65,9 +65,9 @@ class FlotChart extends Component { shutdownChart() { if (!this.plot) return; - $(this.target).unbind('plothover', this.props.plothover); - if (this.props.onMouseOver) $(this.target).on('plothover', this.handleMouseOver); - if (this.props.onMouseLeave) $(this.target).on('mouseleave', this.handleMouseLeave); + $(this.target).off('plothover', this.props.plothover); + if (this.props.onMouseOver) $(this.target).off('plothover', this.handleMouseOver); + if (this.props.onMouseLeave) $(this.target).off('mouseleave', this.handleMouseLeave); if (this.props.onBrush) $(this.target).off('plotselected', this.brushChart); this.plot.shutdown(); if (this.props.crosshair) { From 5ecf974e828f3d71d9a04e05e38d2bf1bb1c934f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20C=C3=B4t=C3=A9?= Date: Fri, 7 Dec 2018 09:01:17 -0500 Subject: [PATCH 13/85] Fix saved objects client _processBatchQueue function to handle errors (#26763) * Fix saved objects client _processBatchQueue function to handle errors * Fix error thrown in try/catch --- .../__tests__/saved_objects_client.test.js | 15 +++++++++++++++ .../public/saved_objects/saved_objects_client.js | 4 ++++ 2 files changed, 19 insertions(+) diff --git a/src/ui/public/saved_objects/__tests__/saved_objects_client.test.js b/src/ui/public/saved_objects/__tests__/saved_objects_client.test.js index feec586c5cb1d..4a8de1d12b5e9 100644 --- a/src/ui/public/saved_objects/__tests__/saved_objects_client.test.js +++ b/src/ui/public/saved_objects/__tests__/saved_objects_client.test.js @@ -128,6 +128,21 @@ describe('SavedObjectsClient', () => { await savedObjectsClient.get(doc.type, doc.id); sinon.assert.calledOnce(kfetchStub); }); + + test('handles HTTP call when it fails', async () => { + kfetchStub.withArgs({ + method: 'POST', + pathname: `/api/saved_objects/_bulk_get`, + query: undefined, + body: sinon.match.any + }).rejects(new Error('Request failed')); + try { + await savedObjectsClient.get(doc.type, doc.id); + throw new Error('should have error'); + } catch (e) { + expect(e.message).to.be('Request failed'); + } + }); }); describe('#delete', () => { diff --git a/src/ui/public/saved_objects/saved_objects_client.js b/src/ui/public/saved_objects/saved_objects_client.js index ac74db7060312..c18a7276ab804 100644 --- a/src/ui/public/saved_objects/saved_objects_client.js +++ b/src/ui/public/saved_objects/saved_objects_client.js @@ -215,6 +215,10 @@ export class SavedObjectsClient { queueItem.resolve(foundObject); }); + }).catch((err) => { + queue.forEach((queueItem) => { + queueItem.reject(err); + }); }); }, BATCH_INTERVAL, { leading: false }); From ce6305ec8cd73e6154bd7894e68a01f7429a06c5 Mon Sep 17 00:00:00 2001 From: Ahmad Bamieh Date: Fri, 7 Dec 2018 16:11:11 +0200 Subject: [PATCH 14/85] chore(.gitignore): ignore sublime workspace files (#26516) --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 157d51cea5f28..167d677100df5 100644 --- a/.gitignore +++ b/.gitignore @@ -41,6 +41,7 @@ selenium package-lock.json .yo-rc.json .vscode +*.sublime-* npm-debug.log* .tern-project **/public/index.css From d9a30e1597ee8fda1673bb2911ad859852638bb9 Mon Sep 17 00:00:00 2001 From: Nathan Reese Date: Fri, 7 Dec 2018 08:16:47 -0700 Subject: [PATCH 15/85] Map inspector requests by id so single requests can be reset at a time (#26770) --- .../adapters/request/request_adapter.ts | 21 +++++++++++++++---- .../inspector/adapters/request/types.ts | 2 ++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/ui/public/inspector/adapters/request/request_adapter.ts b/src/ui/public/inspector/adapters/request/request_adapter.ts index 9ae429901ea63..a1a1463b8f2f6 100644 --- a/src/ui/public/inspector/adapters/request/request_adapter.ts +++ b/src/ui/public/inspector/adapters/request/request_adapter.ts @@ -18,6 +18,8 @@ */ import { EventEmitter } from 'events'; +import _ from 'lodash'; +import uuid from 'uuid/v4'; import { RequestResponder } from './request_responder'; import { Request, RequestParams, RequestStatus } from './types'; @@ -29,7 +31,12 @@ import { Request, RequestParams, RequestStatus } from './types'; * @extends EventEmitter */ class RequestAdapter extends EventEmitter { - private requests: Request[] = []; + private requests: Map; + + constructor() { + super(); + this.requests = new Map(); + } /** * Start logging a new request into this request adapter. The new request will @@ -47,19 +54,25 @@ class RequestAdapter extends EventEmitter { name, startTime: Date.now(), status: RequestStatus.PENDING, + id: _.get(params, 'id', uuid()), }; - this.requests.push(req); + this.requests.set(req.id, req); this._onChange(); return new RequestResponder(req, () => this._onChange()); } public reset(): void { - this.requests = []; + this.requests = new Map(); + this._onChange(); + } + + public resetRequest(id: string): void { + this.requests.delete(id); this._onChange(); } public getRequests(): Request[] { - return this.requests; + return Array.from(this.requests.values()); } private _onChange(): void { diff --git a/src/ui/public/inspector/adapters/request/types.ts b/src/ui/public/inspector/adapters/request/types.ts index 8e0b6276ae69d..16c9f8d0ab1ab 100644 --- a/src/ui/public/inspector/adapters/request/types.ts +++ b/src/ui/public/inspector/adapters/request/types.ts @@ -36,6 +36,7 @@ export enum RequestStatus { } export interface Request extends RequestParams { + id: string; name: string; json?: object; response?: Response; @@ -46,6 +47,7 @@ export interface Request extends RequestParams { } export interface RequestParams { + id?: string; description?: string; } From 9240b8de6e676a599c3af8e3e7ca51268400b7b0 Mon Sep 17 00:00:00 2001 From: Pete Harverson Date: Fri, 7 Dec 2018 16:12:38 +0000 Subject: [PATCH 16/85] [ML] Implement k7 breadcrumbs for ML routes (#26774) * [ML] Implement k7 breadcrumbs for ML routes * [ML] Remove duplicate nouns from jobs and settings breadcrumbs --- x-pack/plugins/ml/public/breadcrumbs.js | 11 +++ .../ml/public/components/nav_menu/nav_menu.js | 84 +++++++++--------- .../ml/public/datavisualizer/breadcrumbs.js | 18 ++++ .../datavisualizer_controller.js | 2 + .../datavisualizer/selector/directive.js | 2 + .../plugins/ml/public/explorer/breadcrumbs.js | 18 ++++ .../ml/public/explorer/explorer_controller.js | 2 + .../public/file_datavisualizer/breadcrumbs.js | 18 ++++ .../file_datavisualizer_directive.js | 2 + x-pack/plugins/ml/public/jobs/breadcrumbs.js | 87 +++++++++++++++++++ .../ml/public/jobs/jobs_list/directive.js | 2 + .../new_job/advanced/new_job_controller.js | 3 + .../create_job/create_job_controller.js | 2 + .../create_job/create_job_controller.js | 2 + .../create_job/create_job_controller.js | 2 + .../create_job/create_job_controller.js | 2 + .../index_or_search_controller.js | 3 + .../steps/job_type/job_type_controller.js | 2 + .../plugins/ml/public/settings/breadcrumbs.js | 77 ++++++++++++++++ .../settings/filter_lists/edit/directive.js | 3 + .../settings/filter_lists/list/directive.js | 2 + .../calendars_list_controller.js | 2 + .../create_calendar_controller.js | 3 + .../ml/public/settings/settings_controller.js | 2 + .../public/timeseriesexplorer/breadcrumbs.js | 18 ++++ .../timeseriesexplorer_controller.js | 2 + 26 files changed, 331 insertions(+), 40 deletions(-) create mode 100644 x-pack/plugins/ml/public/breadcrumbs.js create mode 100644 x-pack/plugins/ml/public/datavisualizer/breadcrumbs.js create mode 100644 x-pack/plugins/ml/public/explorer/breadcrumbs.js create mode 100644 x-pack/plugins/ml/public/file_datavisualizer/breadcrumbs.js create mode 100644 x-pack/plugins/ml/public/jobs/breadcrumbs.js create mode 100644 x-pack/plugins/ml/public/settings/breadcrumbs.js create mode 100644 x-pack/plugins/ml/public/timeseriesexplorer/breadcrumbs.js diff --git a/x-pack/plugins/ml/public/breadcrumbs.js b/x-pack/plugins/ml/public/breadcrumbs.js new file mode 100644 index 0000000000000..f5deeff4cf253 --- /dev/null +++ b/x-pack/plugins/ml/public/breadcrumbs.js @@ -0,0 +1,11 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + + +export const ML_BREADCRUMB = Object.freeze({ + text: 'Machine Learning', + href: '#/' +}); diff --git a/x-pack/plugins/ml/public/components/nav_menu/nav_menu.js b/x-pack/plugins/ml/public/components/nav_menu/nav_menu.js index 12425b7fa6c54..da2915450449f 100644 --- a/x-pack/plugins/ml/public/components/nav_menu/nav_menu.js +++ b/x-pack/plugins/ml/public/components/nav_menu/nav_menu.js @@ -5,8 +5,6 @@ */ - -import _ from 'lodash'; import $ from 'jquery'; import template from './nav_menu.html'; import uiRouter from 'ui/routes'; @@ -23,8 +21,6 @@ module.directive('mlNavMenu', function (config) { template, link: function (scope, el, attrs) { - - // Tabs scope.name = attrs.name; @@ -43,46 +39,54 @@ module.directive('mlNavMenu', function (config) { scope.disableLinks = (isFullLicense() === false); - // Breadcrumbs - const crumbNames = { - jobs: { label: 'Job Management', url: '#/jobs' }, - new_job: { label: 'Create New Job', url: '#/jobs/new_job' }, - single_metric: { label: 'Single Metric Job', url: '' }, - multi_metric: { label: 'Multi Metric job', url: '' }, - population: { label: 'Population job', url: '' }, - advanced: { label: 'Advanced Job Configuration', url: '' }, - datavisualizer: { label: 'Data Visualizer', url: '' }, - filedatavisualizer: { label: 'File Data Visualizer (Experimental)', url: '' }, - explorer: { label: 'Anomaly Explorer', url: '#/explorer' }, - timeseriesexplorer: { label: 'Single Metric Viewer', url: '#/timeseriesexplorer' }, - settings: { label: 'Settings', url: '#/settings' }, - calendars_list: { label: 'Calendar Management', url: '#/settings/calendars_list' }, - new_calendar: { label: 'New Calendar', url: '#/settings/calendars_list/new_calendar' }, - edit_calendar: { label: 'Edit Calendar', url: '#/settings/calendars_list/edit_calendar' }, - filter_lists: { label: 'Filter Lists', url: '#/settings/filter_lists' }, - new_filter_list: { label: 'New Filter List', url: '#/settings/filter_lists/new' }, - edit_filter_list: { label: 'Edit Filter List', url: '#/settings/filter_lists/edit' }, - }; + // TODO - once the k7design flag is disabled, this should all be removed. + const isK7Design = chrome.getUiSettingsClient().get('k7design', false); + if (isK7Design === false) { + // Breadcrumbs + const crumbNames = { + jobs: { label: 'Job Management', url: '#/jobs' }, + new_job: { label: 'Create New Job', url: '#/jobs/new_job' }, + single_metric: { label: 'Single Metric Job', url: '' }, + multi_metric: { label: 'Multi Metric job', url: '' }, + population: { label: 'Population job', url: '' }, + advanced: { label: 'Advanced Job Configuration', url: '' }, + datavisualizer: { label: 'Data Visualizer', url: '' }, + filedatavisualizer: { label: 'File Data Visualizer (Experimental)', url: '' }, + explorer: { label: 'Anomaly Explorer', url: '#/explorer' }, + timeseriesexplorer: { label: 'Single Metric Viewer', url: '#/timeseriesexplorer' }, + settings: { label: 'Settings', url: '#/settings' }, + calendars_list: { label: 'Calendar Management', url: '#/settings/calendars_list' }, + new_calendar: { label: 'New Calendar', url: '#/settings/calendars_list/new_calendar' }, + edit_calendar: { label: 'Edit Calendar', url: '#/settings/calendars_list/edit_calendar' }, + filter_lists: { label: 'Filter Lists', url: '#/settings/filter_lists' }, + new_filter_list: { label: 'New Filter List', url: '#/settings/filter_lists/new' }, + edit_filter_list: { label: 'Edit Filter List', url: '#/settings/filter_lists/edit' }, + }; - const breadcrumbs = [{ label: 'Machine Learning', url: '#/' }]; + const breadcrumbs = [{ label: 'Machine Learning', url: '#/' }]; - // get crumbs from url - const crumbs = uiRouter.getBreadcrumbs(); - _.each(crumbs, (crumb) => { - breadcrumbs.push(crumbNames[crumb.id]); - }); - scope.breadcrumbs = breadcrumbs.filter(Boolean); + // get crumbs from url + const crumbs = uiRouter.getBreadcrumbs(); + if (crumbs.length > 1) { + crumbs.forEach((crumb) => { + breadcrumbs.push(crumbNames[crumb.id]); + }); + } - config.watch('k7design', (val) => scope.showPluginBreadcrumbs = !val); - chrome.breadcrumbs.set(scope.breadcrumbs.map(b => ({ text: b.label, href: b.url }))); + scope.breadcrumbs = breadcrumbs.filter(Boolean); + + config.watch('k7design', (val) => scope.showPluginBreadcrumbs = !val); + chrome.breadcrumbs.set(scope.breadcrumbs.map(b => ({ text: b.label, href: b.url }))); + + // when the page loads, focus on the first breadcrumb + el.ready(() => { + const $crumbs = $('.kuiLocalBreadcrumbs a'); + if ($crumbs.length) { + $crumbs[0].focus(); + } + }); + } - // when the page loads, focus on the first breadcrumb - el.ready(() => { - const $crumbs = $('.kuiLocalBreadcrumbs a'); - if ($crumbs.length) { - $crumbs[0].focus(); - } - }); } }; }); diff --git a/x-pack/plugins/ml/public/datavisualizer/breadcrumbs.js b/x-pack/plugins/ml/public/datavisualizer/breadcrumbs.js new file mode 100644 index 0000000000000..d7278ee83c90f --- /dev/null +++ b/x-pack/plugins/ml/public/datavisualizer/breadcrumbs.js @@ -0,0 +1,18 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + + +import { ML_BREADCRUMB } from '../breadcrumbs'; + + +export function getDataVisualizerBreadcrumbs() { + // Whilst top level nav menu with tabs remains, + // use root ML breadcrumb. + return [ + ML_BREADCRUMB + ]; +} + diff --git a/x-pack/plugins/ml/public/datavisualizer/datavisualizer_controller.js b/x-pack/plugins/ml/public/datavisualizer/datavisualizer_controller.js index 48ea057218cac..f26118647cad1 100644 --- a/x-pack/plugins/ml/public/datavisualizer/datavisualizer_controller.js +++ b/x-pack/plugins/ml/public/datavisualizer/datavisualizer_controller.js @@ -22,6 +22,7 @@ import { decorateQuery, luceneStringToDsl } from '@kbn/es-query'; import { notify, toastNotifications } from 'ui/notify'; import { ML_JOB_FIELD_TYPES, KBN_FIELD_TYPES } from 'plugins/ml/../common/constants/field_types'; +import { getDataVisualizerBreadcrumbs } from './breadcrumbs'; import { kbnTypeToMLJobType } from 'plugins/ml/util/field_types_utils'; import { IntervalHelperProvider } from 'plugins/ml/util/ml_time_buckets'; import { checkBasicLicense, isFullLicense } from 'plugins/ml/license/check_license'; @@ -36,6 +37,7 @@ import template from './datavisualizer.html'; uiRoutes .when('/jobs/new_job/datavisualizer', { template, + k7Breadcrumbs: getDataVisualizerBreadcrumbs, resolve: { CheckLicense: checkBasicLicense, privileges: checkGetJobsPrivilege, diff --git a/x-pack/plugins/ml/public/datavisualizer/selector/directive.js b/x-pack/plugins/ml/public/datavisualizer/selector/directive.js index 206ebcd96ed86..7fd91f5c1333c 100644 --- a/x-pack/plugins/ml/public/datavisualizer/selector/directive.js +++ b/x-pack/plugins/ml/public/datavisualizer/selector/directive.js @@ -9,6 +9,7 @@ import 'ngreact'; import { uiModules } from 'ui/modules'; const module = uiModules.get('apps/ml', ['react']); +import { getDataVisualizerBreadcrumbs } from '../breadcrumbs'; import { checkBasicLicense } from 'plugins/ml/license/check_license'; import { checkFindFileStructurePrivilege } from 'plugins/ml/privilege/check_privilege'; import { initPromise } from 'plugins/ml/util/promise'; @@ -20,6 +21,7 @@ const template = ``; uiRoutes .when('/jobs/?', { template, + k7Breadcrumbs: getJobManagementBreadcrumbs, resolve: { CheckLicense: checkFullLicense, privileges: checkGetJobsPrivilege, diff --git a/x-pack/plugins/ml/public/jobs/new_job/advanced/new_job_controller.js b/x-pack/plugins/ml/public/jobs/new_job/advanced/new_job_controller.js index db1a1426c4714..ac366227bb075 100644 --- a/x-pack/plugins/ml/public/jobs/new_job/advanced/new_job_controller.js +++ b/x-pack/plugins/ml/public/jobs/new_job/advanced/new_job_controller.js @@ -18,6 +18,7 @@ import { checkFullLicense } from 'plugins/ml/license/check_license'; import { checkCreateJobsPrivilege } from 'plugins/ml/privilege/check_privilege'; import template from './new_job.html'; import saveStatusTemplate from 'plugins/ml/jobs/new_job/advanced/save_status_modal/save_status_modal.html'; +import { getAdvancedJobConfigurationBreadcrumbs } from 'plugins/ml/jobs/breadcrumbs'; import { SearchItemsProvider, createJobForSaving, @@ -42,6 +43,7 @@ import { initPromise } from 'plugins/ml/util/promise'; uiRoutes .when('/jobs/new_job/advanced', { template, + k7Breadcrumbs: getAdvancedJobConfigurationBreadcrumbs, resolve: { CheckLicense: checkFullLicense, privileges: checkCreateJobsPrivilege, @@ -55,6 +57,7 @@ uiRoutes }) .when('/jobs/new_job/advanced/:jobId', { template, + k7Breadcrumbs: getAdvancedJobConfigurationBreadcrumbs, resolve: { CheckLicense: checkFullLicense, privileges: checkCreateJobsPrivilege, diff --git a/x-pack/plugins/ml/public/jobs/new_job/simple/multi_metric/create_job/create_job_controller.js b/x-pack/plugins/ml/public/jobs/new_job/simple/multi_metric/create_job/create_job_controller.js index b40b0947b11eb..d46e228a050cd 100644 --- a/x-pack/plugins/ml/public/jobs/new_job/simple/multi_metric/create_job/create_job_controller.js +++ b/x-pack/plugins/ml/public/jobs/new_job/simple/multi_metric/create_job/create_job_controller.js @@ -19,6 +19,7 @@ import uiRoutes from 'ui/routes'; import { checkLicenseExpired } from 'plugins/ml/license/check_license'; import { checkCreateJobsPrivilege } from 'plugins/ml/privilege/check_privilege'; import { IntervalHelperProvider } from 'plugins/ml/util/ml_time_buckets'; +import { getCreateMultiMetricJobBreadcrumbs } from 'plugins/ml/jobs/breadcrumbs'; import { filterAggTypes } from 'plugins/ml/jobs/new_job/simple/components/utils/filter_agg_types'; import { validateJob } from 'plugins/ml/jobs/new_job/simple/components/utils/validate_job'; import { adjustIntervalDisplayed } from 'plugins/ml/jobs/new_job/simple/components/utils/adjust_interval'; @@ -47,6 +48,7 @@ import { timefilter } from 'ui/timefilter'; uiRoutes .when('/jobs/new_job/simple/multi_metric', { template, + k7Breadcrumbs: getCreateMultiMetricJobBreadcrumbs, resolve: { CheckLicense: checkLicenseExpired, privileges: checkCreateJobsPrivilege, diff --git a/x-pack/plugins/ml/public/jobs/new_job/simple/population/create_job/create_job_controller.js b/x-pack/plugins/ml/public/jobs/new_job/simple/population/create_job/create_job_controller.js index 8bef479ed0b65..47fc87cb00ecc 100644 --- a/x-pack/plugins/ml/public/jobs/new_job/simple/population/create_job/create_job_controller.js +++ b/x-pack/plugins/ml/public/jobs/new_job/simple/population/create_job/create_job_controller.js @@ -19,6 +19,7 @@ import uiRoutes from 'ui/routes'; import { checkLicenseExpired } from 'plugins/ml/license/check_license'; import { checkCreateJobsPrivilege } from 'plugins/ml/privilege/check_privilege'; import { IntervalHelperProvider } from 'plugins/ml/util/ml_time_buckets'; +import { getCreatePopulationJobBreadcrumbs } from 'plugins/ml/jobs/breadcrumbs'; import { filterAggTypes } from 'plugins/ml/jobs/new_job/simple/components/utils/filter_agg_types'; import { validateJob } from 'plugins/ml/jobs/new_job/simple/components/utils/validate_job'; import { adjustIntervalDisplayed } from 'plugins/ml/jobs/new_job/simple/components/utils/adjust_interval'; @@ -46,6 +47,7 @@ import { timefilter } from 'ui/timefilter'; uiRoutes .when('/jobs/new_job/simple/population', { template, + k7Breadcrumbs: getCreatePopulationJobBreadcrumbs, resolve: { CheckLicense: checkLicenseExpired, privileges: checkCreateJobsPrivilege, diff --git a/x-pack/plugins/ml/public/jobs/new_job/simple/recognize/create_job/create_job_controller.js b/x-pack/plugins/ml/public/jobs/new_job/simple/recognize/create_job/create_job_controller.js index 21580cd85cf6d..47265c841394c 100644 --- a/x-pack/plugins/ml/public/jobs/new_job/simple/recognize/create_job/create_job_controller.js +++ b/x-pack/plugins/ml/public/jobs/new_job/simple/recognize/create_job/create_job_controller.js @@ -10,6 +10,7 @@ import _ from 'lodash'; import angular from 'angular'; import dateMath from '@elastic/datemath'; import { isJobIdValid, prefixDatafeedId } from 'plugins/ml/../common/util/job_utils'; +import { getCreateRecognizerJobBreadcrumbs } from 'plugins/ml/jobs/breadcrumbs'; import { SearchItemsProvider, addNewJobToRecentlyAccessed } from 'plugins/ml/jobs/new_job/utils/new_job_utils'; @@ -29,6 +30,7 @@ import { timefilter } from 'ui/timefilter'; uiRoutes .when('/jobs/new_job/simple/recognize', { template, + k7Breadcrumbs: getCreateRecognizerJobBreadcrumbs, resolve: { CheckLicense: checkLicenseExpired, privileges: checkCreateJobsPrivilege, diff --git a/x-pack/plugins/ml/public/jobs/new_job/simple/single_metric/create_job/create_job_controller.js b/x-pack/plugins/ml/public/jobs/new_job/simple/single_metric/create_job/create_job_controller.js index f979ee6023c65..a5a0cfce6a6bc 100644 --- a/x-pack/plugins/ml/public/jobs/new_job/simple/single_metric/create_job/create_job_controller.js +++ b/x-pack/plugins/ml/public/jobs/new_job/simple/single_metric/create_job/create_job_controller.js @@ -20,6 +20,7 @@ import { getSafeAggregationName } from 'plugins/ml/../common/util/job_utils'; import { checkLicenseExpired } from 'plugins/ml/license/check_license'; import { checkCreateJobsPrivilege } from 'plugins/ml/privilege/check_privilege'; import { IntervalHelperProvider } from 'plugins/ml/util/ml_time_buckets'; +import { getCreateSingleMetricJobBreadcrumbs } from 'plugins/ml/jobs/breadcrumbs'; import { filterAggTypes } from 'plugins/ml/jobs/new_job/simple/components/utils/filter_agg_types'; import { validateJob } from 'plugins/ml/jobs/new_job/simple/components/utils/validate_job'; import { adjustIntervalDisplayed } from 'plugins/ml/jobs/new_job/simple/components/utils/adjust_interval'; @@ -48,6 +49,7 @@ import { timefilter } from 'ui/timefilter'; uiRoutes .when('/jobs/new_job/simple/single_metric', { template, + k7Breadcrumbs: getCreateSingleMetricJobBreadcrumbs, resolve: { CheckLicense: checkLicenseExpired, privileges: checkCreateJobsPrivilege, diff --git a/x-pack/plugins/ml/public/jobs/new_job/wizard/steps/index_or_search/index_or_search_controller.js b/x-pack/plugins/ml/public/jobs/new_job/wizard/steps/index_or_search/index_or_search_controller.js index a3c3583e7d3d4..50004a351c8d2 100644 --- a/x-pack/plugins/ml/public/jobs/new_job/wizard/steps/index_or_search/index_or_search_controller.js +++ b/x-pack/plugins/ml/public/jobs/new_job/wizard/steps/index_or_search/index_or_search_controller.js @@ -13,6 +13,7 @@ import uiRoutes from 'ui/routes'; import { checkLicenseExpired, checkBasicLicense } from 'plugins/ml/license/check_license'; +import { getCreateJobBreadcrumbs, getDataVisualizerIndexOrSearchBreadcrumbs } from 'plugins/ml/jobs/breadcrumbs'; import { preConfiguredJobRedirect } from 'plugins/ml/jobs/new_job/wizard/preconfigured_job_redirect'; import { checkCreateJobsPrivilege, checkFindFileStructurePrivilege } from 'plugins/ml/privilege/check_privilege'; import { loadIndexPatterns, getIndexPatterns } from 'plugins/ml/util/index_utils'; @@ -29,6 +30,7 @@ uiRoutes uiRoutes .when('/jobs/new_job/step/index_or_search', { template, + k7Breadcrumbs: getCreateJobBreadcrumbs, resolve: { CheckLicense: checkLicenseExpired, privileges: checkCreateJobsPrivilege, @@ -43,6 +45,7 @@ uiRoutes uiRoutes .when('/datavisualizer_index_select', { template, + k7Breadcrumbs: getDataVisualizerIndexOrSearchBreadcrumbs, resolve: { CheckLicense: checkBasicLicense, privileges: checkFindFileStructurePrivilege, diff --git a/x-pack/plugins/ml/public/jobs/new_job/wizard/steps/job_type/job_type_controller.js b/x-pack/plugins/ml/public/jobs/new_job/wizard/steps/job_type/job_type_controller.js index 87b0f266af4ab..df62094fe5c9e 100644 --- a/x-pack/plugins/ml/public/jobs/new_job/wizard/steps/job_type/job_type_controller.js +++ b/x-pack/plugins/ml/public/jobs/new_job/wizard/steps/job_type/job_type_controller.js @@ -14,6 +14,7 @@ import uiRoutes from 'ui/routes'; import { checkLicenseExpired } from 'plugins/ml/license/check_license'; import { checkCreateJobsPrivilege } from 'plugins/ml/privilege/check_privilege'; +import { getCreateJobBreadcrumbs } from 'plugins/ml/jobs/breadcrumbs'; import { SearchItemsProvider } from 'plugins/ml/jobs/new_job/utils/new_job_utils'; import { loadCurrentIndexPattern, loadCurrentSavedSearch, timeBasedIndexCheck } from 'plugins/ml/util/index_utils'; import { addItemToRecentlyAccessed } from 'plugins/ml/util/recently_accessed'; @@ -25,6 +26,7 @@ import { timefilter } from 'ui/timefilter'; uiRoutes .when('/jobs/new_job/step/job_type', { template, + k7Breadcrumbs: getCreateJobBreadcrumbs, resolve: { CheckLicense: checkLicenseExpired, privileges: checkCreateJobsPrivilege, diff --git a/x-pack/plugins/ml/public/settings/breadcrumbs.js b/x-pack/plugins/ml/public/settings/breadcrumbs.js new file mode 100644 index 0000000000000..2fa1a6e782f03 --- /dev/null +++ b/x-pack/plugins/ml/public/settings/breadcrumbs.js @@ -0,0 +1,77 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + + +import { ML_BREADCRUMB } from '../breadcrumbs'; + + +export function getSettingsBreadcrumbs() { + // Whilst top level nav menu with tabs remains, + // use root ML breadcrumb. + return [ + ML_BREADCRUMB + ]; +} + +export function getCalendarManagementBreadcrumbs() { + return [ + ...getSettingsBreadcrumbs(), + { + text: 'Calendar management', + href: '#/settings/calendars_list' + } + ]; +} + +export function getCreateCalendarBreadcrumbs() { + return [ + ...getCalendarManagementBreadcrumbs(), + { + text: 'Create', + href: '#/settings/calendars_list/new_calendar' + } + ]; +} + +export function getEditCalendarBreadcrumbs() { + return [ + ...getCalendarManagementBreadcrumbs(), + { + text: 'Edit', + href: '#/settings/calendars_list/edit_calendar' + } + ]; +} + +export function getFilterListsBreadcrumbs() { + return [ + ...getSettingsBreadcrumbs(), + { + text: 'Filter lists', + href: '#/settings/filter_lists' + } + ]; +} + +export function getCreateFilterListBreadcrumbs() { + return [ + ...getFilterListsBreadcrumbs(), + { + text: 'Create', + href: '#/settings/filter_lists/new' + } + ]; +} + +export function getEditFilterListBreadcrumbs() { + return [ + ...getFilterListsBreadcrumbs(), + { + text: 'Edit', + href: '#/settings/filter_lists/edit' + } + ]; +} diff --git a/x-pack/plugins/ml/public/settings/filter_lists/edit/directive.js b/x-pack/plugins/ml/public/settings/filter_lists/edit/directive.js index a72eae02c0ab1..a8bc48010e846 100644 --- a/x-pack/plugins/ml/public/settings/filter_lists/edit/directive.js +++ b/x-pack/plugins/ml/public/settings/filter_lists/edit/directive.js @@ -12,6 +12,7 @@ import ReactDOM from 'react-dom'; import { uiModules } from 'ui/modules'; const module = uiModules.get('apps/ml', ['react']); +import { getCreateFilterListBreadcrumbs, getEditFilterListBreadcrumbs } from '../../breadcrumbs'; import { checkFullLicense } from 'plugins/ml/license/check_license'; import { checkGetJobsPrivilege } from 'plugins/ml/privilege/check_privilege'; import { getMlNodeCount } from 'plugins/ml/ml_nodes_check/check_ml_nodes'; @@ -29,6 +30,7 @@ const template = ` uiRoutes .when('/settings/filter_lists/new_filter_list', { template, + k7Breadcrumbs: getCreateFilterListBreadcrumbs, resolve: { CheckLicense: checkFullLicense, privileges: checkGetJobsPrivilege, @@ -38,6 +40,7 @@ uiRoutes }) .when('/settings/filter_lists/edit_filter_list/:filterId', { template, + k7Breadcrumbs: getEditFilterListBreadcrumbs, resolve: { CheckLicense: checkFullLicense, privileges: checkGetJobsPrivilege, diff --git a/x-pack/plugins/ml/public/settings/filter_lists/list/directive.js b/x-pack/plugins/ml/public/settings/filter_lists/list/directive.js index df54a65a5ccc5..60de17ce8f7a7 100644 --- a/x-pack/plugins/ml/public/settings/filter_lists/list/directive.js +++ b/x-pack/plugins/ml/public/settings/filter_lists/list/directive.js @@ -12,6 +12,7 @@ import ReactDOM from 'react-dom'; import { uiModules } from 'ui/modules'; const module = uiModules.get('apps/ml', ['react']); +import { getFilterListsBreadcrumbs } from '../../breadcrumbs'; import { checkFullLicense } from 'plugins/ml/license/check_license'; import { checkGetJobsPrivilege } from 'plugins/ml/privilege/check_privilege'; import { getMlNodeCount } from 'plugins/ml/ml_nodes_check/check_ml_nodes'; @@ -29,6 +30,7 @@ const template = ` uiRoutes .when('/settings/filter_lists', { template, + k7Breadcrumbs: getFilterListsBreadcrumbs, resolve: { CheckLicense: checkFullLicense, privileges: checkGetJobsPrivilege, diff --git a/x-pack/plugins/ml/public/settings/scheduled_events/calendars_list/calendars_list_controller.js b/x-pack/plugins/ml/public/settings/scheduled_events/calendars_list/calendars_list_controller.js index 03cb20d6255f8..eff4f9843ab51 100644 --- a/x-pack/plugins/ml/public/settings/scheduled_events/calendars_list/calendars_list_controller.js +++ b/x-pack/plugins/ml/public/settings/scheduled_events/calendars_list/calendars_list_controller.js @@ -13,6 +13,7 @@ import 'ui/pager'; import 'ui/sortable_column'; import uiRoutes from 'ui/routes'; +import { getCalendarManagementBreadcrumbs } from '../../breadcrumbs'; import { checkFullLicense } from 'plugins/ml/license/check_license'; import { checkGetJobsPrivilege, checkPermission } from 'plugins/ml/privilege/check_privilege'; import { getMlNodeCount, mlNodesAvailable } from 'plugins/ml/ml_nodes_check/check_ml_nodes'; @@ -27,6 +28,7 @@ import { timefilter } from 'ui/timefilter'; uiRoutes .when('/settings/calendars_list', { template, + k7Breadcrumbs: getCalendarManagementBreadcrumbs, resolve: { CheckLicense: checkFullLicense, privileges: checkGetJobsPrivilege, diff --git a/x-pack/plugins/ml/public/settings/scheduled_events/new_calendar/create_calendar_controller.js b/x-pack/plugins/ml/public/settings/scheduled_events/new_calendar/create_calendar_controller.js index 55f4e813c7bbc..7a6e363aa1909 100644 --- a/x-pack/plugins/ml/public/settings/scheduled_events/new_calendar/create_calendar_controller.js +++ b/x-pack/plugins/ml/public/settings/scheduled_events/new_calendar/create_calendar_controller.js @@ -15,6 +15,7 @@ import 'plugins/ml/settings/scheduled_events/components/events_list'; import { validateCalendarId } from 'plugins/ml/settings/scheduled_events/components/utils/validate_calendar'; import uiRoutes from 'ui/routes'; +import { getCreateCalendarBreadcrumbs, getEditCalendarBreadcrumbs } from '../../breadcrumbs'; import { checkFullLicense } from 'plugins/ml/license/check_license'; import { checkGetJobsPrivilege } from 'plugins/ml/privilege/check_privilege'; import { checkMlNodesAvailable } from 'plugins/ml/ml_nodes_check/check_ml_nodes'; @@ -29,6 +30,7 @@ import template from './create_calendar.html'; uiRoutes .when('/settings/calendars_list/new_calendar', { template, + k7Breadcrumbs: getCreateCalendarBreadcrumbs, resolve: { CheckLicense: checkFullLicense, privileges: checkGetJobsPrivilege, @@ -38,6 +40,7 @@ uiRoutes }) .when('/settings/calendars_list/edit_calendar/:calendarId', { template, + k7Breadcrumbs: getEditCalendarBreadcrumbs, resolve: { CheckLicense: checkFullLicense, privileges: checkGetJobsPrivilege, diff --git a/x-pack/plugins/ml/public/settings/settings_controller.js b/x-pack/plugins/ml/public/settings/settings_controller.js index b4c0e123ef1e5..174efc934e921 100644 --- a/x-pack/plugins/ml/public/settings/settings_controller.js +++ b/x-pack/plugins/ml/public/settings/settings_controller.js @@ -7,6 +7,7 @@ import uiRoutes from 'ui/routes'; +import { getSettingsBreadcrumbs } from './breadcrumbs'; import { checkFullLicense } from 'plugins/ml/license/check_license'; import { checkGetJobsPrivilege, checkPermission } from 'plugins/ml/privilege/check_privilege'; import { getMlNodeCount } from 'plugins/ml/ml_nodes_check/check_ml_nodes'; @@ -19,6 +20,7 @@ import { timefilter } from 'ui/timefilter'; uiRoutes .when('/settings', { template, + k7Breadcrumbs: getSettingsBreadcrumbs, resolve: { CheckLicense: checkFullLicense, privileges: checkGetJobsPrivilege, diff --git a/x-pack/plugins/ml/public/timeseriesexplorer/breadcrumbs.js b/x-pack/plugins/ml/public/timeseriesexplorer/breadcrumbs.js new file mode 100644 index 0000000000000..e0e5e5d1431a5 --- /dev/null +++ b/x-pack/plugins/ml/public/timeseriesexplorer/breadcrumbs.js @@ -0,0 +1,18 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + + +import { ML_BREADCRUMB } from '../breadcrumbs'; + + +export function getSingleMetricViewerBreadcrumbs() { + // Whilst top level nav menu with tabs remains, + // use root ML breadcrumb. + return [ + ML_BREADCRUMB + ]; +} + diff --git a/x-pack/plugins/ml/public/timeseriesexplorer/timeseriesexplorer_controller.js b/x-pack/plugins/ml/public/timeseriesexplorer/timeseriesexplorer_controller.js index 44b7d59fe504b..c47a931d87a08 100644 --- a/x-pack/plugins/ml/public/timeseriesexplorer/timeseriesexplorer_controller.js +++ b/x-pack/plugins/ml/public/timeseriesexplorer/timeseriesexplorer_controller.js @@ -30,6 +30,7 @@ import { isModelPlotEnabled, mlFunctionToESAggregation } from 'plugins/ml/../common/util/job_utils'; import { loadIndexPatterns, getIndexPatterns } from 'plugins/ml/util/index_utils'; +import { getSingleMetricViewerBreadcrumbs } from './breadcrumbs'; import { createTimeSeriesJobData, processForecastResults, @@ -53,6 +54,7 @@ import { initPromise } from 'plugins/ml/util/promise'; uiRoutes .when('/timeseriesexplorer/?', { template, + k7Breadcrumbs: getSingleMetricViewerBreadcrumbs, resolve: { CheckLicense: checkFullLicense, privileges: checkGetJobsPrivilege, From e32c203ae0be6d7d4544b24912509d32edd58b4c Mon Sep 17 00:00:00 2001 From: Tim Sullivan Date: Fri, 7 Dec 2018 09:27:19 -0700 Subject: [PATCH 17/85] [Reporting] Re-enabled Chromium API tests (#26789) * [Reporting] Test logging * chromium api tests fixed * whitespace --- x-pack/plugins/reporting/server/routes/jobs.js | 10 ++++++++++ x-pack/scripts/functional_tests.js | 2 +- x-pack/test/reporting/configs/api.js | 1 + x-pack/test/reporting/configs/chromium_api.js | 1 - x-pack/test/reporting/configs/functional.js | 10 ++++++++-- x-pack/test/reporting/configs/phantom_functional.js | 1 - 6 files changed, 20 insertions(+), 5 deletions(-) diff --git a/x-pack/plugins/reporting/server/routes/jobs.js b/x-pack/plugins/reporting/server/routes/jobs.js index 2639fc103bbde..afbdb9cc7e213 100644 --- a/x-pack/plugins/reporting/server/routes/jobs.js +++ b/x-pack/plugins/reporting/server/routes/jobs.js @@ -124,6 +124,16 @@ export function jobs(server) { const { docId } = request.params; let response = await jobResponseHandler(request.pre.management.jobTypes, request.pre.user, h, { docId }); + const { statusCode } = response; + + if (statusCode !== 200) { + const logLevel = statusCode === 500 ? 'error' : 'debug'; + server.log( + [logLevel, "reporting", "download"], + `Report ${docId} has non-OK status: [${statusCode}] Reason: [${JSON.stringify(response.source)}]` + ); + } + if (!response.isBoom) { response = response.header('accept-ranges', 'none'); } diff --git a/x-pack/scripts/functional_tests.js b/x-pack/scripts/functional_tests.js index a9192077791f4..fe070c3445a68 100644 --- a/x-pack/scripts/functional_tests.js +++ b/x-pack/scripts/functional_tests.js @@ -6,7 +6,7 @@ require('@kbn/plugin-helpers').babelRegister(); require('@kbn/test').runTestsCli([ - // require.resolve('../test/reporting/configs/chromium_api.js'), + require.resolve('../test/reporting/configs/chromium_api.js'), // require.resolve('../test/reporting/configs/chromium_functional.js'), // require.resolve('../test/reporting/configs/phantom_api.js'), // require.resolve('../test/reporting/configs/phantom_functional.js'), diff --git a/x-pack/test/reporting/configs/api.js b/x-pack/test/reporting/configs/api.js index 3723390c971b0..7c30f299f3f46 100644 --- a/x-pack/test/reporting/configs/api.js +++ b/x-pack/test/reporting/configs/api.js @@ -30,6 +30,7 @@ export async function getReportingApiConfig({ readConfigFile }) { serverArgs: [ ...apiConfig.get('kbnTestServer.serverArgs'), `--optimize.enabled=true`, + '--logging.events.log', JSON.stringify(['info', 'warning', 'error', 'fatal', 'optimize', 'reporting']) ], }, }; diff --git a/x-pack/test/reporting/configs/chromium_api.js b/x-pack/test/reporting/configs/chromium_api.js index 1d643c4d359df..461c6c0df5271 100644 --- a/x-pack/test/reporting/configs/chromium_api.js +++ b/x-pack/test/reporting/configs/chromium_api.js @@ -22,7 +22,6 @@ export default async function ({ readConfigFile }) { ...reportingApiConfig.kbnTestServer.serverArgs, `--xpack.reporting.capture.browser.type=chromium`, `--xpack.spaces.enabled=false`, - `--logging.verbose=true`, ], }, }; diff --git a/x-pack/test/reporting/configs/functional.js b/x-pack/test/reporting/configs/functional.js index 82d38ccde3119..4eafa10369e93 100644 --- a/x-pack/test/reporting/configs/functional.js +++ b/x-pack/test/reporting/configs/functional.js @@ -21,9 +21,15 @@ export async function getFunctionalConfig({ readConfigFile }) { junit: { reportName: 'X-Pack Reporting Functional Tests', }, - kbnTestServer: xPackFunctionalTestsConfig.get('kbnTestServer'), + kbnTestServer: { + ...xPackFunctionalTestsConfig.get('kbnTestServer'), + serverArgs: [ + ...xPackFunctionalTestsConfig.get('kbnTestServer.serverArgs'), + '--logging.events.log', JSON.stringify(['info', 'warning', 'error', 'fatal', 'optimize', 'reporting']) + ], + }, testFiles: [require.resolve('../functional')], }; } -export default getFunctionalConfig; \ No newline at end of file +export default getFunctionalConfig; diff --git a/x-pack/test/reporting/configs/phantom_functional.js b/x-pack/test/reporting/configs/phantom_functional.js index e9a61ee813cf2..b0e7ba6f29ce7 100644 --- a/x-pack/test/reporting/configs/phantom_functional.js +++ b/x-pack/test/reporting/configs/phantom_functional.js @@ -21,7 +21,6 @@ export default async function ({ readConfigFile }) { serverArgs: [ ...functionalConfig.kbnTestServer.serverArgs, `--xpack.reporting.capture.browser.type=phantom`, - `--logging.verbose=true`, ], }, }; From 669fa64dd3fea52dadb2806e63e777cafbec6bac Mon Sep 17 00:00:00 2001 From: Chris Koehnke Date: Fri, 7 Dec 2018 12:45:32 -0500 Subject: [PATCH 18/85] Fix Elasticsearch typo on connection error screen (#26815) `Elastiscearch` -> `Elasticsearch`. --- .../login_page/__snapshots__/login_page.test.tsx.snap | 2 +- .../public/views/login/components/login_page/login_page.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/x-pack/plugins/security/public/views/login/components/login_page/__snapshots__/login_page.test.tsx.snap b/x-pack/plugins/security/public/views/login/components/login_page/__snapshots__/login_page.test.tsx.snap index 0f91dfef7b0bd..52ce28fd9dec2 100644 --- a/x-pack/plugins/security/public/views/login/components/login_page/__snapshots__/login_page.test.tsx.snap +++ b/x-pack/plugins/security/public/views/login/components/login_page/__snapshots__/login_page.test.tsx.snap @@ -80,7 +80,7 @@ exports[`LoginPage disabled form states renders as expected when a connection to } title={ diff --git a/x-pack/plugins/security/public/views/login/components/login_page/login_page.tsx b/x-pack/plugins/security/public/views/login/components/login_page/login_page.tsx index 29ca0b3d978b6..d00dacbafc113 100644 --- a/x-pack/plugins/security/public/views/login/components/login_page/login_page.tsx +++ b/x-pack/plugins/security/public/views/login/components/login_page/login_page.tsx @@ -122,7 +122,7 @@ export class LoginPage extends Component { title={ } message={ From 3e53313342d656edf20d35a3a51167b352bb2eb5 Mon Sep 17 00:00:00 2001 From: Joel Griffith Date: Fri, 7 Dec 2018 09:49:46 -0800 Subject: [PATCH 19/85] Reporting/reveal document bytes (#26667) * Adding a `size` property to all job-reporting meta-data and showing in reporting details pane --- .../export_types/csv/server/execute_job.js | 5 +++-- .../lib/__tests__/max_size_string_builder.js | 14 ++++++++++++++ .../export_types/csv/server/lib/generate_csv.js | 6 ++++-- .../csv/server/lib/max_size_string_builder.js | 4 ++++ .../export_types/png/server/execute_job/index.js | 3 ++- .../printable_pdf/server/execute_job/index.js | 3 ++- .../public/components/report_info_button.tsx | 4 ++++ .../reporting/public/lib/job_queue_client.ts | 5 ++++- .../server/lib/esqueue/helpers/create_index.js | 1 + .../plugins/reporting/server/lib/esqueue/worker.js | 1 + 10 files changed, 39 insertions(+), 7 deletions(-) diff --git a/x-pack/plugins/reporting/export_types/csv/server/execute_job.js b/x-pack/plugins/reporting/export_types/csv/server/execute_job.js index 89ac80016fa55..4ef1658d88f8e 100644 --- a/x-pack/plugins/reporting/export_types/csv/server/execute_job.js +++ b/x-pack/plugins/reporting/export_types/csv/server/execute_job.js @@ -65,7 +65,7 @@ function executeJobFn(server) { const maxSizeBytes = config.get('xpack.reporting.csv.maxSizeBytes'); const scroll = config.get('xpack.reporting.csv.scroll'); - const { content, maxSizeReached } = await generateCsv({ + const { content, maxSizeReached, size } = await generateCsv({ searchRequest, fields, formatsMap, @@ -84,7 +84,8 @@ function executeJobFn(server) { return { content_type: 'text/csv', content, - max_size_reached: maxSizeReached + max_size_reached: maxSizeReached, + size, }; }; } diff --git a/x-pack/plugins/reporting/export_types/csv/server/lib/__tests__/max_size_string_builder.js b/x-pack/plugins/reporting/export_types/csv/server/lib/__tests__/max_size_string_builder.js index d550399636845..15a10934b5db5 100644 --- a/x-pack/plugins/reporting/export_types/csv/server/lib/__tests__/max_size_string_builder.js +++ b/x-pack/plugins/reporting/export_types/csv/server/lib/__tests__/max_size_string_builder.js @@ -63,4 +63,18 @@ describe('MaxSizeStringBuilder', function () { expect(builder.getString()).to.be('a'); }); }); + + describe('getSizeInBytes', function () { + it(`should return 0 when no strings have been appended`, function () { + const builder = new MaxSizeStringBuilder(100); + expect(builder.getSizeInBytes()).to.be(0); + }); + + it(`should the size in bytes`, function () { + const builder = new MaxSizeStringBuilder(100); + const stringValue = 'foobar'; + builder.tryAppend(stringValue); + expect(builder.getSizeInBytes()).to.be(stringValue.length); + }); + }); }); diff --git a/x-pack/plugins/reporting/export_types/csv/server/lib/generate_csv.js b/x-pack/plugins/reporting/export_types/csv/server/lib/generate_csv.js index 016081198d033..2d0133238bf82 100644 --- a/x-pack/plugins/reporting/export_types/csv/server/lib/generate_csv.js +++ b/x-pack/plugins/reporting/export_types/csv/server/lib/generate_csv.js @@ -58,11 +58,13 @@ export function createGenerateCsv(logger) { } finally { await iterator.return(); } + const size = builder.getSizeInBytes(); + logger(`finished generating, total size in bytes: ${size}`); - logger('finished generating'); return { content: builder.getString(), - maxSizeReached + maxSizeReached, + size, }; }; } diff --git a/x-pack/plugins/reporting/export_types/csv/server/lib/max_size_string_builder.js b/x-pack/plugins/reporting/export_types/csv/server/lib/max_size_string_builder.js index d1d86fd2bb250..b4bdfcc13b3f6 100644 --- a/x-pack/plugins/reporting/export_types/csv/server/lib/max_size_string_builder.js +++ b/x-pack/plugins/reporting/export_types/csv/server/lib/max_size_string_builder.js @@ -22,6 +22,10 @@ export class MaxSizeStringBuilder { return false; } + getSizeInBytes() { + return this._size; + } + getString() { return this._buffer.slice(0, this._size).toString(); } diff --git a/x-pack/plugins/reporting/export_types/png/server/execute_job/index.js b/x-pack/plugins/reporting/export_types/png/server/execute_job/index.js index d9edbd7e0c6de..fda79fb92da2a 100644 --- a/x-pack/plugins/reporting/export_types/png/server/execute_job/index.js +++ b/x-pack/plugins/reporting/export_types/png/server/execute_job/index.js @@ -26,7 +26,8 @@ function executeJobFn(server) { }), map(buffer => ({ content_type: 'image/png', - content: buffer.toString('base64') + content: buffer.toString('base64'), + size: buffer.byteLength, })) ); diff --git a/x-pack/plugins/reporting/export_types/printable_pdf/server/execute_job/index.js b/x-pack/plugins/reporting/export_types/printable_pdf/server/execute_job/index.js index 4f5e6ca830625..618a26b99cc1d 100644 --- a/x-pack/plugins/reporting/export_types/printable_pdf/server/execute_job/index.js +++ b/x-pack/plugins/reporting/export_types/printable_pdf/server/execute_job/index.js @@ -34,7 +34,8 @@ function executeJobFn(server) { }), map(buffer => ({ content_type: 'application/pdf', - content: buffer.toString('base64') + content: buffer.toString('base64'), + size: buffer.byteLength, })) ); diff --git a/x-pack/plugins/reporting/public/components/report_info_button.tsx b/x-pack/plugins/reporting/public/components/report_info_button.tsx index 6168a2e2a8f6b..56ad3f927498c 100644 --- a/x-pack/plugins/reporting/public/components/report_info_button.tsx +++ b/x-pack/plugins/reporting/public/components/report_info_button.tsx @@ -126,6 +126,10 @@ export class ReportInfoButton extends Component { title: 'Content Type', description: get(info, 'output.content_type') || NA, }, + { + title: 'Size in Bytes', + description: get(info, 'output.size') || NA, + }, ], status: [ { diff --git a/x-pack/plugins/reporting/public/lib/job_queue_client.ts b/x-pack/plugins/reporting/public/lib/job_queue_client.ts index d5cdde62acfbd..ca5d21dccfb1f 100644 --- a/x-pack/plugins/reporting/public/lib/job_queue_client.ts +++ b/x-pack/plugins/reporting/public/lib/job_queue_client.ts @@ -27,7 +27,10 @@ export interface JobInfo { jobtype: string; created_by: string; timeout: number; - output: { content_type: string }; + output: { + content_type: string; + size: number; + }; process_expiration: string; completed_at: string; payload: { diff --git a/x-pack/plugins/reporting/server/lib/esqueue/helpers/create_index.js b/x-pack/plugins/reporting/server/lib/esqueue/helpers/create_index.js index bf022ba7f98f4..45be7529e6887 100644 --- a/x-pack/plugins/reporting/server/lib/esqueue/helpers/create_index.js +++ b/x-pack/plugins/reporting/server/lib/esqueue/helpers/create_index.js @@ -58,6 +58,7 @@ const schema = { type: 'object', properties: { content_type: { type: 'keyword' }, + size: { type: 'keyword' }, content: { type: 'object', enabled: false } } } diff --git a/x-pack/plugins/reporting/server/lib/esqueue/worker.js b/x-pack/plugins/reporting/server/lib/esqueue/worker.js index 02f9c054c2e3b..97439b5713579 100644 --- a/x-pack/plugins/reporting/server/lib/esqueue/worker.js +++ b/x-pack/plugins/reporting/server/lib/esqueue/worker.js @@ -184,6 +184,7 @@ export class Worker extends events.EventEmitter { docOutput.content = output.content; docOutput.content_type = output.content_type || unknownMime; docOutput.max_size_reached = output.max_size_reached; + docOutput.size = output.size; } else { docOutput.content = output || defaultOutput; docOutput.content_type = unknownMime; From 34a91e66d8494528c583adacb338d9f90c14bd23 Mon Sep 17 00:00:00 2001 From: Andrew Cholakian Date: Fri, 7 Dec 2018 11:51:54 -0600 Subject: [PATCH 20/85] Enable heartbeat telemetry (#25886) This commit allows heartbeat telemetry data to be sent through kibana. The change to beats was introduced in https://github.com/elastic/beats/pull/8621 --- .../fixtures/beats_stats_results.json | 73 +++++++++++++++++++ .../monitoring/__tests__/get_beats_stats.js | 16 ++++ .../telemetry/monitoring/get_beats_stats.js | 29 ++++++++ 3 files changed, 118 insertions(+) diff --git a/x-pack/plugins/xpack_main/server/lib/telemetry/monitoring/__tests__/fixtures/beats_stats_results.json b/x-pack/plugins/xpack_main/server/lib/telemetry/monitoring/__tests__/fixtures/beats_stats_results.json index be6e4352514fe..c7fadc5057d31 100644 --- a/x-pack/plugins/xpack_main/server/lib/telemetry/monitoring/__tests__/fixtures/beats_stats_results.json +++ b/x-pack/plugins/xpack_main/server/lib/telemetry/monitoring/__tests__/fixtures/beats_stats_results.json @@ -2,6 +2,58 @@ { "hits": { "hits": [ + { + "_source" : { + "cluster_uuid": "W7hppdX7R229Oy3KQbZrTw", + "type": "beats_state", + "beats_state" : { + "state" : { + "heartbeat" : { + "endpoints" : 2, + "http" : { + "endpoints" : 1, + "monitors" : 1 + }, + "icmp" : { + "monitors" : 0, + "endpoints" : 0 + }, + "tcp" : { + "monitors" : 1, + "endpoints" : 1 + }, + "monitors" : 2 + } + } + } + } + }, + { + "_source" : { + "cluster_uuid": "W7hppdX7R229Oy3KQbZrTw", + "type": "beats_state", + "beats_state" : { + "state" : { + "heartbeat" : { + "endpoints" : 2, + "http" : { + "endpoints" : 0, + "monitors" : 0 + }, + "icmp" : { + "monitors" : 0, + "endpoints" : 0 + }, + "tcp" : { + "monitors" : 1, + "endpoints" : 2 + }, + "monitors" : 1 + } + } + } + } + }, { "_source": { "type": "beats_state", @@ -74,6 +126,26 @@ "published": 1038 } } + }, + "heartbeat" : { + "http" : { + "endpoint_starts" : 1, + "endpoint_stops" : 0, + "monitor_starts" : 1, + "monitor_stops" : 0 + }, + "icmp" : { + "endpoint_starts" : 0, + "endpoint_stops" : 0, + "monitor_starts" : 0, + "monitor_stops" : 0 + }, + "tcp" : { + "endpoint_starts" : 1, + "endpoint_stops" : 0, + "monitor_starts" : 1, + "monitor_stops" : 0 + } } } } @@ -11531,5 +11603,6 @@ ] } }, + {} ] diff --git a/x-pack/plugins/xpack_main/server/lib/telemetry/monitoring/__tests__/get_beats_stats.js b/x-pack/plugins/xpack_main/server/lib/telemetry/monitoring/__tests__/get_beats_stats.js index 3cde267a1536b..42642b16de4c4 100644 --- a/x-pack/plugins/xpack_main/server/lib/telemetry/monitoring/__tests__/get_beats_stats.js +++ b/x-pack/plugins/xpack_main/server/lib/telemetry/monitoring/__tests__/get_beats_stats.js @@ -154,6 +154,22 @@ describe('Get Beats Stats', () => { name: 'darwin' } ] + }, + heartbeat: { + endpoints: 4, + http: { + endpoints: 1, + monitors: 1 + }, + icmp: { + monitors: 0, + endpoints: 0 + }, + tcp: { + monitors: 2, + endpoints: 3 + }, + monitors: 3 } }, FlV4ckTxQ0a78hmBkzzc9A: { diff --git a/x-pack/plugins/xpack_main/server/lib/telemetry/monitoring/get_beats_stats.js b/x-pack/plugins/xpack_main/server/lib/telemetry/monitoring/get_beats_stats.js index ff0ddadac40f1..321e2ebdad642 100644 --- a/x-pack/plugins/xpack_main/server/lib/telemetry/monitoring/get_beats_stats.js +++ b/x-pack/plugins/xpack_main/server/lib/telemetry/monitoring/get_beats_stats.js @@ -103,6 +103,34 @@ export function processResults(results = [], { clusters, clusterHostSets, cluste clusters[clusterUuid].module.count += stateModule.count; } + const heartbeatState = get(hit, '_source.beats_state.state.heartbeat'); + if (heartbeatState !== undefined) { + if (!clusters[clusterUuid].hasOwnProperty('heartbeat')) { + clusters[clusterUuid].heartbeat = { + monitors: 0, + endpoints: 0 + }; + } + const clusterHb = clusters[clusterUuid].heartbeat; + + clusterHb.monitors += heartbeatState.monitors; + clusterHb.endpoints += heartbeatState.endpoints; + for (const proto in heartbeatState) { + if (!heartbeatState.hasOwnProperty(proto)) continue; + const val = heartbeatState[proto]; + if (typeof val !== "object") continue; + + if (!clusterHb.hasOwnProperty(proto)) { + clusterHb[proto] = { + monitors: 0, + endpoints: 0 + }; + } + clusterHb[proto].monitors += val.monitors; + clusterHb[proto].endpoints += val.endpoints; + } + } + const stateHost = get(hit, '_source.beats_state.state.host'); if (stateHost !== undefined) { const hostMap = clusterArchitectureMaps[clusterUuid]; @@ -161,6 +189,7 @@ async function fetchBeatsByType(server, callCluster, clusterUuids, start, end, { 'hits.hits._source.beats_state.state.input', 'hits.hits._source.beats_state.state.module', 'hits.hits._source.beats_state.state.host', + 'hits.hits._source.beats_state.state.heartbeat', ], body: { query: createQuery({ From 52719b735649ab1424595db93e376719f8769fb5 Mon Sep 17 00:00:00 2001 From: Justin Kambic Date: Fri, 7 Dec 2018 14:27:20 -0500 Subject: [PATCH 21/85] Change 'Disenroll' text to be consistent with menu option 'Unenroll'. (#26816) --- .../public/components/table/table_type_configs.tsx | 2 +- .../beats_management/public/pages/main/beats.tsx | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/x-pack/plugins/beats_management/public/components/table/table_type_configs.tsx b/x-pack/plugins/beats_management/public/components/table/table_type_configs.tsx index 8e57de438e258..1ee969e03ae87 100644 --- a/x-pack/plugins/beats_management/public/components/table/table_type_configs.tsx +++ b/x-pack/plugins/beats_management/public/components/table/table_type_configs.tsx @@ -178,7 +178,7 @@ export const BeatsTableType: TableType = { actions: [ { name: i18n.translate('xpack.beatsManagement.beatsTable.disenrollSelectedLabel', { - defaultMessage: 'Disenroll Selected', + defaultMessage: 'Unenroll Selected', }), action: 'delete', danger: true, diff --git a/x-pack/plugins/beats_management/public/pages/main/beats.tsx b/x-pack/plugins/beats_management/public/pages/main/beats.tsx index e5772765707cf..c6c24542b6e4c 100644 --- a/x-pack/plugins/beats_management/public/pages/main/beats.tsx +++ b/x-pack/plugins/beats_management/public/pages/main/beats.tsx @@ -190,7 +190,7 @@ class BeatsPageUi extends React.PureComponent { await this.props.libs.beats.update(beat.id, { active: false }); } - this.notifyBeatDisenrolled(selected); + this.notifyBeatUnenrolled(selected); // because the compile code above has a very minor race condition, we wait, // the max race condition time is really 10ms but doing 100 to be safe @@ -229,7 +229,7 @@ class BeatsPageUi extends React.PureComponent { } }; - private notifyBeatDisenrolled = async (beats: CMPopulatedBeat[]) => { + private notifyBeatUnenrolled = async (beats: CMPopulatedBeat[]) => { const { intl } = this.props; let title; let text; @@ -237,7 +237,7 @@ class BeatsPageUi extends React.PureComponent { title = intl.formatMessage( { id: 'xpack.beatsManagement.beats.beatDisenrolledNotificationTitle', - defaultMessage: '{firstBeatNameOrId} disenrolled', + defaultMessage: '{firstBeatNameOrId} unenrolled', }, { firstBeatNameOrId: `"${beats[0].name || beats[0].id}"`, @@ -246,7 +246,7 @@ class BeatsPageUi extends React.PureComponent { text = intl.formatMessage( { id: 'xpack.beatsManagement.beats.beatDisenrolledNotificationDescription', - defaultMessage: 'Beat with ID {firstBeatId} was disenrolled.', + defaultMessage: 'Beat with ID {firstBeatId} was unenrolled.', }, { firstBeatId: `"${beats[0].id}"`, @@ -256,7 +256,7 @@ class BeatsPageUi extends React.PureComponent { title = intl.formatMessage( { id: 'xpack.beatsManagement.beats.disenrolledBeatsNotificationTitle', - defaultMessage: '{beatsLength} beats disenrolled', + defaultMessage: '{beatsLength} beats unenrolled', }, { beatsLength: beats.length, @@ -267,7 +267,7 @@ class BeatsPageUi extends React.PureComponent { this.setState({ notifications: this.state.notifications.concat({ color: 'warning', - id: `disenroll_${new Date()}`, + id: `unenroll_${new Date()}`, title, text, }), From f719089683bda899e227070b1752577905ce6deb Mon Sep 17 00:00:00 2001 From: Brandon Kobel Date: Fri, 7 Dec 2018 12:46:11 -0800 Subject: [PATCH 22/85] Upgrading sshpk (#26834) sshpk is an implicit dependency of request@2.88.0 --- yarn.lock | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/yarn.lock b/yarn.lock index baab1eae32471..0bb48abad29a7 100644 --- a/yarn.lock +++ b/yarn.lock @@ -18278,7 +18278,7 @@ safefs@^4.0.0: editions "^1.1.1" graceful-fs "^4.1.4" -"safer-buffer@>= 2.1.2 < 3": +"safer-buffer@>= 2.1.2 < 3", safer-buffer@^2.0.2: version "2.1.2" resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a" integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg== @@ -19188,18 +19188,18 @@ squel@^5.12.2: integrity sha512-pIM8SjlUJlN2G6xz3we+lCp2aNQgxauGqKXJDi8y2n0hqJlSot0IUEdHh7/zGFFuRYnypbDiOhSWLZzT1BXnlQ== sshpk@^1.7.0: - version "1.13.1" - resolved "https://registry.yarnpkg.com/sshpk/-/sshpk-1.13.1.tgz#512df6da6287144316dc4c18fe1cf1d940739be3" - integrity sha1-US322mKHFEMW3EwY/hzx2UBzm+M= + version "1.15.2" + resolved "https://registry.yarnpkg.com/sshpk/-/sshpk-1.15.2.tgz#c946d6bd9b1a39d0e8635763f5242d6ed6dcb629" + integrity sha512-Ra/OXQtuh0/enyl4ETZAfTaeksa6BXks5ZcjpSUNrjBr0DvrJKX+1fsKDPpT9TBXgHAFsa4510aNVgI8g/+SzA== dependencies: asn1 "~0.2.3" assert-plus "^1.0.0" - dashdash "^1.12.0" - getpass "^0.1.1" - optionalDependencies: bcrypt-pbkdf "^1.0.0" + dashdash "^1.12.0" ecc-jsbn "~0.1.1" + getpass "^0.1.1" jsbn "~0.1.0" + safer-buffer "^2.0.2" tweetnacl "~0.14.0" ssri@^5.2.4: From 975c5ae608d4aea593129b942a9aaa55d38402ec Mon Sep 17 00:00:00 2001 From: Joel Griffith Date: Fri, 7 Dec 2018 13:27:22 -0800 Subject: [PATCH 23/85] Re-enable the chromium functional tests (#26822) --- x-pack/scripts/functional_tests.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x-pack/scripts/functional_tests.js b/x-pack/scripts/functional_tests.js index fe070c3445a68..efc95e38001bc 100644 --- a/x-pack/scripts/functional_tests.js +++ b/x-pack/scripts/functional_tests.js @@ -7,7 +7,7 @@ require('@kbn/plugin-helpers').babelRegister(); require('@kbn/test').runTestsCli([ require.resolve('../test/reporting/configs/chromium_api.js'), - // require.resolve('../test/reporting/configs/chromium_functional.js'), + require.resolve('../test/reporting/configs/chromium_functional.js'), // require.resolve('../test/reporting/configs/phantom_api.js'), // require.resolve('../test/reporting/configs/phantom_functional.js'), require.resolve('../test/functional/config.js'), From da114df4b7f5d15ca175a6cf6be510246644a9ff Mon Sep 17 00:00:00 2001 From: Joel Griffith Date: Fri, 7 Dec 2018 14:50:28 -0800 Subject: [PATCH 24/85] Logging when max-bytes is larger than what's set in ES (#26482) * Simple check if ES body-size is smaller than KBN report size --- x-pack/plugins/apm/typings/numeral.d.ts | 1 + x-pack/plugins/reporting/index.js | 6 +- .../__tests__/validate_max_content_length.js | 71 +++++++++++++++++++ .../server/lib/validate_max_content_length.ts | 31 ++++++++ 4 files changed, 108 insertions(+), 1 deletion(-) create mode 100644 x-pack/plugins/reporting/server/lib/__tests__/validate_max_content_length.js create mode 100644 x-pack/plugins/reporting/server/lib/validate_max_content_length.ts diff --git a/x-pack/plugins/apm/typings/numeral.d.ts b/x-pack/plugins/apm/typings/numeral.d.ts index f08f99f5ef11a..da2d84662a09f 100644 --- a/x-pack/plugins/apm/typings/numeral.d.ts +++ b/x-pack/plugins/apm/typings/numeral.d.ts @@ -7,6 +7,7 @@ interface Numeral { (value?: unknown): Numeral; format: (pattern: string) => string; + unformat: (pattern: string) => number; } declare var numeral: Numeral; diff --git a/x-pack/plugins/reporting/index.js b/x-pack/plugins/reporting/index.js index 1ef8edbc5f921..014a38bc2066b 100644 --- a/x-pack/plugins/reporting/index.js +++ b/x-pack/plugins/reporting/index.js @@ -15,6 +15,7 @@ import { createQueueFactory } from './server/lib/create_queue'; import { config as appConfig } from './server/config/config'; import { checkLicenseFactory } from './server/lib/check_license'; import { validateConfig } from './server/lib/validate_config'; +import { validateMaxContentLength } from './server/lib/validate_max_content_length'; import { exportTypesRegistryFactory } from './server/lib/export_types_registry'; import { PHANTOM, createBrowserDriverFactory, getDefaultBrowser, getDefaultChromiumSandboxDisabled } from './server/browsers'; import { logConfiguration } from './log_configuration'; @@ -148,7 +149,10 @@ export const reporting = (kibana) => { server.expose('exportTypesRegistry', exportTypesRegistry); const config = server.config(); - validateConfig(config, message => server.log(['reporting', 'warning'], message)); + const logWarning = message => server.log(['reporting', 'warning'], message); + + validateConfig(config, logWarning); + validateMaxContentLength(server, logWarning); logConfiguration(config, message => server.log(['reporting', 'debug'], message)); const { xpack_main: xpackMainPlugin } = server.plugins; diff --git a/x-pack/plugins/reporting/server/lib/__tests__/validate_max_content_length.js b/x-pack/plugins/reporting/server/lib/__tests__/validate_max_content_length.js new file mode 100644 index 0000000000000..28ac7bade95c1 --- /dev/null +++ b/x-pack/plugins/reporting/server/lib/__tests__/validate_max_content_length.js @@ -0,0 +1,71 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import expect from 'expect.js'; +import sinon from 'sinon'; +import { validateMaxContentLength } from '../validate_max_content_length'; + +const FIVE_HUNDRED_MEGABYTES = 524288000; +const ONE_HUNDRED_MEGABYTES = 104857600; + +describe('Reporting: Validate Max Content Length', () => { + const log = sinon.spy(); + + beforeEach(() => { + log.resetHistory(); + }); + + it('should log warning messages when reporting has a higher max-size than elasticsearch', async () => { + const server = { + config: () => ({ + get: sinon.stub().returns(FIVE_HUNDRED_MEGABYTES), + }), + plugins: { + elasticsearch: { + getCluster: () => ({ + callWithInternalUser: () => ({ + defaults: { + http: { + max_content_length: '100mb', + }, + }, + }), + }), + }, + }, + }; + + await validateMaxContentLength(server, log); + + sinon.assert.calledWithMatch(log, `xpack.reporting.csv.maxSizeBytes (524288000) is higher`); + sinon.assert.calledWithMatch(log, `than ElasticSearch's http.max_content_length (104857600)`); + sinon.assert.calledWithMatch(log, 'Please set http.max_content_length in ElasticSearch to match'); + sinon.assert.calledWithMatch(log, 'or lower your xpack.reporting.csv.maxSizeBytes in Kibana'); + }); + + it('should do nothing when reporting has the same max-size as elasticsearch', async () => { + const server = { + config: () => ({ + get: sinon.stub().returns(ONE_HUNDRED_MEGABYTES), + }), + plugins: { + elasticsearch: { + getCluster: () => ({ + callWithInternalUser: () => ({ + defaults: { + http: { + max_content_length: '100mb', + }, + }, + }), + }), + }, + }, + }; + + expect(async () => validateMaxContentLength(server, log)).not.to.throwError(); + sinon.assert.notCalled(log); + }); +}); diff --git a/x-pack/plugins/reporting/server/lib/validate_max_content_length.ts b/x-pack/plugins/reporting/server/lib/validate_max_content_length.ts new file mode 100644 index 0000000000000..0142b482bc0aa --- /dev/null +++ b/x-pack/plugins/reporting/server/lib/validate_max_content_length.ts @@ -0,0 +1,31 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import numeral from '@elastic/numeral'; +import { defaults, get } from 'lodash'; +const KIBANA_MAX_SIZE_BYTES_PATH = 'xpack.reporting.csv.maxSizeBytes'; +const ES_MAX_SIZE_BYTES_PATH = 'http.max_content_length'; + +export async function validateMaxContentLength(server: any, log: (message: string) => any) { + const config = server.config(); + const { callWithInternalUser } = server.plugins.elasticsearch.getCluster('data'); + + const elasticClusterSettingsResponse = await callWithInternalUser('cluster.getSettings', { + includeDefaults: true, + }); + const { persistent, transient, defaults: defaultSettings } = elasticClusterSettingsResponse; + const elasticClusterSettings = defaults({}, persistent, transient, defaultSettings); + + const elasticSearchMaxContent = get(elasticClusterSettings, 'http.max_content_length', '100mb'); + const elasticSearchMaxContentBytes = numeral().unformat(elasticSearchMaxContent.toUpperCase()); + const kibanaMaxContentBytes = config.get(KIBANA_MAX_SIZE_BYTES_PATH); + + if (kibanaMaxContentBytes > elasticSearchMaxContentBytes) { + log( + `${KIBANA_MAX_SIZE_BYTES_PATH} (${kibanaMaxContentBytes}) is higher than ElasticSearch's ${ES_MAX_SIZE_BYTES_PATH} (${elasticSearchMaxContentBytes}). ` + + `Please set ${ES_MAX_SIZE_BYTES_PATH} in ElasticSearch to match, or lower your ${KIBANA_MAX_SIZE_BYTES_PATH} in Kibana to avoid this warning.` + ); + } +} From cee968ef11060db59ba327f1ea2bfffd88a135c7 Mon Sep 17 00:00:00 2001 From: Matt Apperson Date: Fri, 7 Dec 2018 19:07:33 -0500 Subject: [PATCH 25/85] [BeatsCM] Cleanup and refactor (#26636) * Refactor BeatsCM * update deps * update more deps * update for new EUI definitions * update import * Revert "update deps" This reverts commit 759a14561dbeb52fba70515384ee35873e43a409. * use _source_includes * remove _source_includes * work-around due to watcher UI tests * Keep all xpack checks safe because we cant trust its there in tests for some reason * VALIDATION. This commit is to ensure the errors in CI are coming from beats * remove validation that this is a beats CM issue * More try/catch to try and find where this error is * testing another call * revert back to dangerouslyGetActiveInjector * ensure expire always is a number * fix swallowed error * Update x-pack/plugins/beats_management/public/lib/compose/kibana.ts Co-Authored-By: mattapperson * Update x-pack/plugins/beats_management/public/utils/page_loader.test.ts Co-Authored-By: mattapperson * Update x-pack/plugins/beats_management/public/utils/page_loader.ts Co-Authored-By: mattapperson * fix for new webpack import * Fix translation map * fix URL path * fix other link * removing tag from beats via tag details screen now uses container * remove debug text * added comment/readme about routing on the client side * enrolled beat UI now works on overview screen * newly enrolled beat now reloads the beats table * fix TS errors --- x-pack/package.json | 4 +- .../common/constants/index.ts | 3 +- .../common/constants/plugin.ts | 1 + .../common/constants/security.ts | 10 + x-pack/plugins/beats_management/index.ts | 9 +- .../enroll_beats.tsx} | 131 ++------ .../layouts/background.tsx} | 13 +- .../public/components/layouts/header.tsx | 36 --- .../public/components/layouts/no_data.tsx | 18 +- .../public/components/layouts/primary.tsx | 112 ++++--- .../public/components/layouts/walkthrough.tsx | 1 - .../public/components/loading.tsx | 16 + .../navigation/breadcrumb/breadcrumb.tsx | 62 ++++ .../breadcrumb}/consumer.tsx | 0 .../breadcrumb}/context.tsx | 0 .../breadcrumb}/index.ts | 2 +- .../breadcrumb}/provider.tsx | 0 .../breadcrumb}/types.d.ts | 0 .../components/navigation/child_routes.tsx | 38 +++ .../{ => navigation}/connected_link.tsx | 3 +- .../route_with_breadcrumb.tsx | 88 ----- .../public/components/table/controls.tsx | 2 +- .../controls}/action_control.tsx | 0 .../controls}/index.ts | 0 .../controls}/option_control.tsx | 2 +- .../controls}/tag_assignment.tsx | 4 +- .../controls}/tag_badge_list.tsx | 2 +- .../components/table/table_type_configs.tsx | 5 +- .../tag/config_view/config_form.tsx | 2 +- .../components/tag/config_view/index.tsx | 2 - .../public/components/tag/tag_edit.tsx | 38 +-- .../beats_management/public/config_schemas.ts | 2 +- .../public/config_schemas_translations_map.ts | 7 +- .../public/containers/beats.ts | 98 ++++++ .../public/containers/tags.ts | 45 +++ .../containers/with_kuery_autocompletion.tsx | 2 +- .../public/containers/with_url_state.tsx | 6 +- .../public/frontend_types.d.ts | 34 ++ .../plugins/beats_management/public/index.tsx | 68 ++-- .../lib/adapters/beats/rest_beats_adapter.ts | 2 +- .../public/lib/adapters/elasticsearch/rest.ts | 1 - .../lib/adapters/framework/adapter_types.ts | 81 +++++ .../framework/kibana_framework_adapter.ts | 290 ++++++++++------- .../lib/adapters/rest_api/adapter_types.ts | 2 +- .../rest_api/axios_rest_api_adapter.ts | 2 +- .../public/lib/adapters/tags/adapter_types.ts | 2 +- .../lib/adapters/tags/memory_tags_adapter.ts | 2 +- .../lib/adapters/tags/rest_tags_adapter.ts | 4 +- .../beats_management/public/lib/beats.ts | 46 ++- .../public/lib/compose/kibana.ts | 44 ++- .../public/lib/compose/memory.ts | 34 +- .../beats_management/public/lib/framework.ts | 40 +++ .../beats_management/public/lib/tags.ts | 6 +- .../public/lib/{lib.ts => types.ts} | 31 +- .../public/pages/{404.tsx => __404.tsx} | 0 .../public/pages/beat/action_section.tsx | 76 ----- .../public/pages/beat/activity.tsx | 22 -- .../pages/beat/{detail.tsx => details.tsx} | 25 +- .../public/pages/beat/index.tsx | 207 ++++++------ .../public/pages/beat/tags.tsx | 34 +- .../pages/{ => error}/enforce_security.tsx | 2 +- .../pages/{ => error}/invalid_license.tsx | 2 +- .../public/pages/{ => error}/no_access.tsx | 2 +- .../public/pages/main/activity.tsx | 21 -- .../public/pages/main/index.tsx | 304 ------------------ .../public/pages/main/tags.tsx | 126 -------- .../pages/overview/configuration_tags.tsx | 126 ++++++++ .../beats.tsx => overview/enrolled_beats.tsx} | 276 +++++++--------- .../public/pages/overview/index.tsx | 91 ++++++ .../public/pages/{tag/index.tsx => tag.tsx} | 62 ++-- .../public/pages/walkthrough/initial/beat.tsx | 63 ++++ .../initial/finish.tsx} | 46 ++- .../pages/walkthrough/initial/index.tsx | 86 +++++ .../initial/tag.tsx} | 56 +--- .../beats_management/public/router.tsx | 222 +++++++------ .../__snapshots__/page_loader.test.ts.snap | 143 ++++++++ .../utils/page_loader/page_loader.test.ts | 138 ++++++++ .../public/utils/page_loader/page_loader.ts | 170 ++++++++++ .../public/utils/page_loader/readme.md | 21 ++ .../beats/elasticsearch_beats_adapter.ts | 2 - .../lib/adapters/database/adapter_types.ts | 17 +- .../database/kibana_database_adapter.ts | 2 +- .../adapters/framework/__tests__/kibana.ts | 8 +- .../lib/adapters/framework/adapter_types.ts | 148 +++++++-- .../framework/hapi_framework_adapter.ts | 86 ++++- .../framework/kibana_framework_adapter.ts | 269 ++++++++-------- .../tags/elasticsearch_tags_adapter.ts | 2 + .../lib/adapters/tokens/adapter_types.ts | 4 +- .../tokens/elasticsearch_tokens_adapter.ts | 21 +- .../adapters/tokens/memory_tokens_adapter.ts | 9 +- .../server/lib/{domains => }/beats.ts | 35 +- .../server/lib/compose/kibana.ts | 33 +- .../server/lib/compose/testing.ts | 19 +- .../__tests__/beats/assign_tags.test.ts | 237 -------------- .../domains/__tests__/beats/enroll.test.ts | 137 -------- .../__tests__/beats/remove_tags.test.ts | 112 ------- .../domains/__tests__/beats/update.test.ts | 118 ------- .../lib/domains/__tests__/tokens.test.ts | 76 ----- .../beats_management/server/lib/framework.ts | 104 ++++++ .../server/lib/{domains => }/tags.ts | 10 +- .../server/lib/{domains => }/tokens.ts | 25 +- .../server/lib/{lib.ts => types.ts} | 18 +- .../server/management_server.ts | 2 +- .../__tests__/beats_assignments.test.ts | 26 +- .../server/rest_api/__tests__/test_harnes.ts | 2 +- .../server/rest_api/beats/configuration.ts | 2 +- .../server/rest_api/beats/enroll.ts | 10 +- .../server/rest_api/beats/get.ts | 2 +- .../server/rest_api/beats/list.ts | 8 +- .../server/rest_api/beats/tag_assignment.ts | 7 +- .../server/rest_api/beats/tag_removal.ts | 7 +- .../server/rest_api/beats/update.ts | 7 +- .../server/rest_api/tags/delete.ts | 5 +- .../server/rest_api/tags/get.ts | 8 +- .../server/rest_api/tags/list.ts | 5 +- .../server/rest_api/tags/set.ts | 6 +- .../server/rest_api/tokens/create.ts | 5 +- .../server/utils/wrap_request.ts | 7 +- x-pack/plugins/beats_management/wallaby.js | 8 +- x-pack/test/functional/config.js | 37 +-- yarn.lock | 24 ++ 121 files changed, 2809 insertions(+), 2635 deletions(-) create mode 100644 x-pack/plugins/beats_management/common/constants/security.ts rename x-pack/plugins/beats_management/public/{pages/main/enroll_fragment.tsx => components/enroll_beats.tsx} (69%) rename x-pack/plugins/beats_management/public/{app.d.ts => components/layouts/background.tsx} (56%) delete mode 100644 x-pack/plugins/beats_management/public/components/layouts/header.tsx create mode 100644 x-pack/plugins/beats_management/public/components/loading.tsx create mode 100644 x-pack/plugins/beats_management/public/components/navigation/breadcrumb/breadcrumb.tsx rename x-pack/plugins/beats_management/public/components/{route_with_breadcrumb => navigation/breadcrumb}/consumer.tsx (100%) rename x-pack/plugins/beats_management/public/components/{route_with_breadcrumb => navigation/breadcrumb}/context.tsx (100%) rename x-pack/plugins/beats_management/public/components/{route_with_breadcrumb => navigation/breadcrumb}/index.ts (84%) rename x-pack/plugins/beats_management/public/components/{route_with_breadcrumb => navigation/breadcrumb}/provider.tsx (100%) rename x-pack/plugins/beats_management/public/components/{route_with_breadcrumb => navigation/breadcrumb}/types.d.ts (100%) create mode 100644 x-pack/plugins/beats_management/public/components/navigation/child_routes.tsx rename x-pack/plugins/beats_management/public/components/{ => navigation}/connected_link.tsx (96%) delete mode 100644 x-pack/plugins/beats_management/public/components/route_with_breadcrumb/route_with_breadcrumb.tsx rename x-pack/plugins/beats_management/public/components/{table_controls => table/controls}/action_control.tsx (100%) rename x-pack/plugins/beats_management/public/components/{table_controls => table/controls}/index.ts (100%) rename x-pack/plugins/beats_management/public/components/{table_controls => table/controls}/option_control.tsx (99%) rename x-pack/plugins/beats_management/public/components/{table_controls => table/controls}/tag_assignment.tsx (92%) rename x-pack/plugins/beats_management/public/components/{table_controls => table/controls}/tag_badge_list.tsx (94%) create mode 100644 x-pack/plugins/beats_management/public/containers/beats.ts create mode 100644 x-pack/plugins/beats_management/public/containers/tags.ts create mode 100644 x-pack/plugins/beats_management/public/frontend_types.d.ts create mode 100644 x-pack/plugins/beats_management/public/lib/adapters/framework/adapter_types.ts create mode 100644 x-pack/plugins/beats_management/public/lib/framework.ts rename x-pack/plugins/beats_management/public/lib/{lib.ts => types.ts} (73%) rename x-pack/plugins/beats_management/public/pages/{404.tsx => __404.tsx} (100%) delete mode 100644 x-pack/plugins/beats_management/public/pages/beat/action_section.tsx delete mode 100644 x-pack/plugins/beats_management/public/pages/beat/activity.tsx rename x-pack/plugins/beats_management/public/pages/beat/{detail.tsx => details.tsx} (88%) rename x-pack/plugins/beats_management/public/pages/{ => error}/enforce_security.tsx (92%) rename x-pack/plugins/beats_management/public/pages/{ => error}/invalid_license.tsx (93%) rename x-pack/plugins/beats_management/public/pages/{ => error}/no_access.tsx (93%) delete mode 100644 x-pack/plugins/beats_management/public/pages/main/activity.tsx delete mode 100644 x-pack/plugins/beats_management/public/pages/main/index.tsx delete mode 100644 x-pack/plugins/beats_management/public/pages/main/tags.tsx create mode 100644 x-pack/plugins/beats_management/public/pages/overview/configuration_tags.tsx rename x-pack/plugins/beats_management/public/pages/{main/beats.tsx => overview/enrolled_beats.tsx} (57%) create mode 100644 x-pack/plugins/beats_management/public/pages/overview/index.tsx rename x-pack/plugins/beats_management/public/pages/{tag/index.tsx => tag.tsx} (78%) create mode 100644 x-pack/plugins/beats_management/public/pages/walkthrough/initial/beat.tsx rename x-pack/plugins/beats_management/public/pages/{main/finish_walkthrough.tsx => walkthrough/initial/finish.tsx} (74%) create mode 100644 x-pack/plugins/beats_management/public/pages/walkthrough/initial/index.tsx rename x-pack/plugins/beats_management/public/pages/{main/create_tag_fragment.tsx => walkthrough/initial/tag.tsx} (55%) create mode 100644 x-pack/plugins/beats_management/public/utils/page_loader/__snapshots__/page_loader.test.ts.snap create mode 100644 x-pack/plugins/beats_management/public/utils/page_loader/page_loader.test.ts create mode 100644 x-pack/plugins/beats_management/public/utils/page_loader/page_loader.ts create mode 100644 x-pack/plugins/beats_management/public/utils/page_loader/readme.md rename x-pack/plugins/beats_management/server/lib/{domains => }/beats.ts (88%) delete mode 100644 x-pack/plugins/beats_management/server/lib/domains/__tests__/beats/assign_tags.test.ts delete mode 100644 x-pack/plugins/beats_management/server/lib/domains/__tests__/beats/enroll.test.ts delete mode 100644 x-pack/plugins/beats_management/server/lib/domains/__tests__/beats/remove_tags.test.ts delete mode 100644 x-pack/plugins/beats_management/server/lib/domains/__tests__/beats/update.test.ts delete mode 100644 x-pack/plugins/beats_management/server/lib/domains/__tests__/tokens.test.ts create mode 100644 x-pack/plugins/beats_management/server/lib/framework.ts rename x-pack/plugins/beats_management/server/lib/{domains => }/tags.ts (89%) rename x-pack/plugins/beats_management/server/lib/{domains => }/tokens.ts (81%) rename x-pack/plugins/beats_management/server/lib/{lib.ts => types.ts} (63%) diff --git a/x-pack/package.json b/x-pack/package.json index b7bf5b055e822..8a456d06245d0 100644 --- a/x-pack/package.json +++ b/x-pack/package.json @@ -124,8 +124,8 @@ "@kbn/babel-preset": "1.0.0", "@kbn/es-query": "1.0.0", "@kbn/i18n": "1.0.0", - "@kbn/ui-framework": "1.0.0", "@kbn/interpreter": "1.0.0", + "@kbn/ui-framework": "1.0.0", "@samverschueren/stream-to-observable": "^0.3.0", "@scant/router": "^0.1.0", "@slack/client": "^4.2.2", @@ -181,6 +181,7 @@ "icalendar": "0.7.1", "inline-style": "^2.0.0", "intl": "^1.2.5", + "io-ts": "^1.4.2", "isomorphic-fetch": "2.2.1", "joi": "^13.5.2", "jquery": "^3.3.1", @@ -258,6 +259,7 @@ "typescript-fsa-reducers": "^0.4.5", "ui-select": "0.19.4", "unbzip2-stream": "1.0.9", + "unstated": "^2.1.1", "uuid": "3.0.1", "venn.js": "0.2.9", "xregexp": "3.2.0" diff --git a/x-pack/plugins/beats_management/common/constants/index.ts b/x-pack/plugins/beats_management/common/constants/index.ts index 50851dcef947e..e111d32d41802 100644 --- a/x-pack/plugins/beats_management/common/constants/index.ts +++ b/x-pack/plugins/beats_management/common/constants/index.ts @@ -7,5 +7,6 @@ export { PLUGIN } from './plugin'; export { INDEX_NAMES } from './index_names'; export { UNIQUENESS_ENFORCING_TYPES, ConfigurationBlockTypes } from './configuration_blocks'; -export const BASE_PATH = '/management/beats_management/'; +export const BASE_PATH = '/management/beats_management'; export { TABLE_CONFIG } from './table'; +export { REQUIRED_ROLES, LICENSES, REQUIRED_LICENSES } from './security'; diff --git a/x-pack/plugins/beats_management/common/constants/plugin.ts b/x-pack/plugins/beats_management/common/constants/plugin.ts index dc7cd85300341..e30109bf269c7 100644 --- a/x-pack/plugins/beats_management/common/constants/plugin.ts +++ b/x-pack/plugins/beats_management/common/constants/plugin.ts @@ -7,3 +7,4 @@ export const PLUGIN = { ID: 'beats_management', }; +export const CONFIG_PREFIX = 'xpack.beats'; diff --git a/x-pack/plugins/beats_management/common/constants/security.ts b/x-pack/plugins/beats_management/common/constants/security.ts new file mode 100644 index 0000000000000..4d72e3c9f2ac7 --- /dev/null +++ b/x-pack/plugins/beats_management/common/constants/security.ts @@ -0,0 +1,10 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export const REQUIRED_ROLES = ['beats_admin']; +export const REQUIRED_LICENSES = ['standard', 'gold', 'trial', 'platinum']; +export const LICENSES = ['oss', 'standard', 'gold', 'trial', 'platinum']; +export type LicenseType = 'oss' | 'trial' | 'standard' | 'basic' | 'gold' | 'platinum'; diff --git a/x-pack/plugins/beats_management/index.ts b/x-pack/plugins/beats_management/index.ts index a415395de5262..3355bc9881811 100644 --- a/x-pack/plugins/beats_management/index.ts +++ b/x-pack/plugins/beats_management/index.ts @@ -6,23 +6,24 @@ import Joi from 'joi'; import { resolve } from 'path'; import { PLUGIN } from './common/constants'; +import { CONFIG_PREFIX } from './common/constants/plugin'; import { initServerWithKibana } from './server/kibana.index'; +import { KibanaLegacyServer } from './server/lib/adapters/framework/adapter_types'; const DEFAULT_ENROLLMENT_TOKENS_TTL_S = 10 * 60; // 10 minutes export const config = Joi.object({ enabled: Joi.boolean().default(true), - encryptionKey: Joi.string(), defaultUserRoles: Joi.array() .items(Joi.string()) .default(['superuser']), + encryptionKey: Joi.string().default('xpack_beats_default_encryptionKey'), enrollmentTokensTtlInSeconds: Joi.number() .integer() .min(1) .max(10 * 60 * 14) // No more then 2 weeks for security reasons .default(DEFAULT_ENROLLMENT_TOKENS_TTL_S), }).default(); -export const configPrefix = 'xpack.beats'; export function beats(kibana: any) { return new kibana.Plugin({ @@ -33,8 +34,8 @@ export function beats(kibana: any) { managementSections: ['plugins/beats_management'], }, config: () => config, - configPrefix, - init(server: any) { + configPrefix: CONFIG_PREFIX, + init(server: KibanaLegacyServer) { initServerWithKibana(server); }, }); diff --git a/x-pack/plugins/beats_management/public/pages/main/enroll_fragment.tsx b/x-pack/plugins/beats_management/public/components/enroll_beats.tsx similarity index 69% rename from x-pack/plugins/beats_management/public/pages/main/enroll_fragment.tsx rename to x-pack/plugins/beats_management/public/components/enroll_beats.tsx index c417a8860a29d..dba4e243e16d3 100644 --- a/x-pack/plugins/beats_management/public/pages/main/enroll_fragment.tsx +++ b/x-pack/plugins/beats_management/public/components/enroll_beats.tsx @@ -4,9 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ import { - // @ts-ignore typings for EuiBasicTable not present in current version EuiBasicTable, - EuiButton, EuiFlexGroup, EuiFlexItem, EuiLoadingSpinner, @@ -15,37 +13,43 @@ import { EuiSelect, EuiTitle, } from '@elastic/eui'; -import { FormattedMessage, InjectedIntl, injectI18n } from '@kbn/i18n/react'; +import { FormattedMessage } from '@kbn/i18n/react'; import { capitalize } from 'lodash'; import React from 'react'; -import { RouteComponentProps } from 'react-router'; -import { CMBeat } from '../../../common/domain_types'; -import { AppURLState } from '../../app'; -import { URLStateProps, withUrlState } from '../../containers/with_url_state'; -import { FrontendLibs } from '../../lib/lib'; +import { CMBeat } from '../../common/domain_types'; -interface BeatsProps extends URLStateProps, RouteComponentProps { - match: any; - libs: FrontendLibs; - intl: InjectedIntl; +interface ComponentProps { + /** Such as kibanas basePath, for use to generate command */ + frameworkBasePath?: string; + enrollmentToken?: string; + getBeatWithToken(token: string): Promise; + createEnrollmentToken(): Promise; + onBeatEnrolled(enrolledBeat: CMBeat): void; } -export class EnrollBeat extends React.Component { + +interface ComponentState { + enrolledBeat: CMBeat | null; + hasPolledForBeat: boolean; + command: string; + beatType: string; +} + +export class EnrollBeat extends React.Component { private pinging = false; - constructor(props: BeatsProps) { + constructor(props: ComponentProps) { super(props); this.state = { enrolledBeat: null, + hasPolledForBeat: false, command: 'sudo filebeat', beatType: 'filebeat', }; } - public pingForBeatWithToken = async ( - libs: FrontendLibs, - token: string - ): Promise => { + public pingForBeatWithToken = async (token: string): Promise => { try { - const beats = await libs.beats.getBeatWithToken(token); + const beats = await this.props.getBeatWithToken(token); + if (!beats) { throw new Error('no beats'); } @@ -54,69 +58,34 @@ export class EnrollBeat extends React.Component { if (this.pinging) { const timeout = (ms: number) => new Promise(res => setTimeout(res, ms)); await timeout(5000); - return await this.pingForBeatWithToken(libs, token); + return await this.pingForBeatWithToken(token); } } }; public async componentDidMount() { - if (!this.props.urlState.enrollmentToken) { - const enrollmentToken = await this.props.libs.tokens.createEnrollmentToken(); - this.props.setUrlState({ - enrollmentToken, - }); + if (!this.props.enrollmentToken) { + await this.props.createEnrollmentToken(); } } - public waitForToken = async (token: string) => { - if (this.pinging) { + public waitForTokenToEnrollBeat = async () => { + if (this.pinging || !this.props.enrollmentToken) { return; } this.pinging = true; - const enrolledBeat = (await this.pingForBeatWithToken(this.props.libs, token)) as CMBeat; + const enrolledBeat = (await this.pingForBeatWithToken(this.props.enrollmentToken)) as CMBeat; this.setState({ enrolledBeat, }); + this.props.onBeatEnrolled(enrolledBeat); this.pinging = false; }; public render() { - if (!this.props.urlState.enrollmentToken) { + if (!this.props.enrollmentToken && !this.state.enrolledBeat) { return null; } - if (this.props.urlState.enrollmentToken && !this.state.enrolledBeat) { - this.waitForToken(this.props.urlState.enrollmentToken); - } - const { goTo, intl } = this.props; - - const actions = []; - - switch (this.props.location.pathname) { - case '/overview/initial/beats': - actions.push({ - goTo: '/overview/initial/tag', - name: intl.formatMessage({ - id: 'xpack.beatsManagement.enrollBeat.continueButtonLabel', - defaultMessage: 'Continue', - }), - }); - break; - case '/overview/beats/enroll': - actions.push({ - goTo: '/overview/beats/enroll', - name: intl.formatMessage({ - id: 'xpack.beatsManagement.enrollBeat.enrollAnotherBeatButtonLabel', - defaultMessage: 'Enroll another Beat', - }), - newToken: true, - }); - actions.push({ - goTo: '/overview/beats', - name: intl.formatMessage({ - id: 'xpack.beatsManagement.enrollBeat.doneButtonLabel', - defaultMessage: 'Done', - }), - clearToken: true, - }); - break; + if (this.props.enrollmentToken && !this.state.enrolledBeat) { + this.waitForTokenToEnrollBeat(); } return ( @@ -229,10 +198,7 @@ export class EnrollBeat extends React.Component { /> {`//`} {window.location.host} - {this.props.libs.framework.baseURLPath - ? this.props.libs.framework.baseURLPath - : ''}{' '} - {this.props.urlState.enrollmentToken} + {this.props.frameworkBasePath} {this.props.enrollmentToken}

@@ -309,38 +275,9 @@ export class EnrollBeat extends React.Component { />

- {actions.map(action => ( - { - if (action.clearToken) { - this.props.setUrlState({ enrollmentToken: '' }); - } - - if (action.newToken) { - const enrollmentToken = await this.props.libs.tokens.createEnrollmentToken(); - - this.props.setUrlState({ enrollmentToken }); - return this.setState({ - enrolledBeat: null, - }); - } - goTo(action.goTo); - }} - > - {action.name} - - ))} )} ); } } - -export const EnrollBeatPageUi = withUrlState(EnrollBeat); - -export const EnrollBeatPage = injectI18n(EnrollBeatPageUi); diff --git a/x-pack/plugins/beats_management/public/app.d.ts b/x-pack/plugins/beats_management/public/components/layouts/background.tsx similarity index 56% rename from x-pack/plugins/beats_management/public/app.d.ts rename to x-pack/plugins/beats_management/public/components/layouts/background.tsx index 4e806e12d3843..3368b0e05598e 100644 --- a/x-pack/plugins/beats_management/public/app.d.ts +++ b/x-pack/plugins/beats_management/public/components/layouts/background.tsx @@ -4,11 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ -export type FlatObject = { [Key in keyof T]: string }; +import styled from 'styled-components'; -export interface AppURLState { - beatsKBar?: string; - tagsKBar?: string; - enrollmentToken?: string; - createdTag?: string; -} +export const Background = styled.div` + flex-grow: 1; + height: 100vh; + background: #f5f5f5; +`; diff --git a/x-pack/plugins/beats_management/public/components/layouts/header.tsx b/x-pack/plugins/beats_management/public/components/layouts/header.tsx deleted file mode 100644 index 4ad567b73fc77..0000000000000 --- a/x-pack/plugins/beats_management/public/components/layouts/header.tsx +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { - EuiBreadcrumbDefinition, - EuiHeader, - EuiHeaderBreadcrumbs, - EuiHeaderSection, -} from '@elastic/eui'; -import React from 'react'; -import styled from 'styled-components'; - -interface HeaderProps { - breadcrumbs?: EuiBreadcrumbDefinition[]; -} - -export class Header extends React.PureComponent { - public render() { - const { breadcrumbs = [] } = this.props; - - return ( - - - - - - ); - } -} - -const HeaderWrapper = styled(EuiHeader)` - height: 29px; -`; diff --git a/x-pack/plugins/beats_management/public/components/layouts/no_data.tsx b/x-pack/plugins/beats_management/public/components/layouts/no_data.tsx index 8f31b90ff507e..8f30803724cc4 100644 --- a/x-pack/plugins/beats_management/public/components/layouts/no_data.tsx +++ b/x-pack/plugins/beats_management/public/components/layouts/no_data.tsx @@ -11,8 +11,6 @@ import { EuiEmptyPrompt, EuiFlexGroup, EuiFlexItem, - EuiModal, - EuiOverlayMask, EuiPage, EuiPageBody, EuiPageContent, @@ -21,13 +19,11 @@ import { interface LayoutProps { title: string; actionSection?: React.ReactNode; - modalRender?: () => React.ReactNode; modalClosePath?: string; } export const NoDataLayout: React.SFC = withRouter( - ({ actionSection, title, modalRender, modalClosePath, children, history }) => { - const modalContent = modalRender && modalRender(); + ({ actionSection, title, modalClosePath, children, history }) => { return ( @@ -44,18 +40,6 @@ export const NoDataLayout: React.SFC = withRouter( - {modalContent && ( - - { - history.push(modalClosePath); - }} - style={{ width: '640px' }} - > - {modalContent} - - - )} ); } diff --git a/x-pack/plugins/beats_management/public/components/layouts/primary.tsx b/x-pack/plugins/beats_management/public/components/layouts/primary.tsx index 516ad648eac8b..bf192b3f1cc0c 100644 --- a/x-pack/plugins/beats_management/public/components/layouts/primary.tsx +++ b/x-pack/plugins/beats_management/public/components/layouts/primary.tsx @@ -4,12 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ -import React from 'react'; -import { withRouter } from 'react-router-dom'; - import { - EuiModal, - EuiOverlayMask, + EuiHeader, + EuiHeaderBreadcrumbs, + EuiHeaderSection, EuiPage, EuiPageBody, EuiPageContent, @@ -18,45 +16,85 @@ import { EuiPageHeaderSection, EuiTitle, } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +import React, { Component, ReactNode } from 'react'; +import styled from 'styled-components'; +import { BreadcrumbConsumer } from '../navigation/breadcrumb'; +type RenderCallback = ((component: () => JSX.Element) => void); interface PrimaryLayoutProps { title: string; actionSection?: React.ReactNode; - modalRender?: () => React.ReactNode; - modalClosePath?: string; + hideBreadcrumbs?: boolean; } +export class PrimaryLayout extends Component { + private actionSection: (() => JSX.Element) | null = null; + constructor(props: PrimaryLayoutProps) { + super(props); + } -export const PrimaryLayout: React.SFC = withRouter( - ({ actionSection, title, modalRender, modalClosePath, children, history }) => { - const modalContent = modalRender && modalRender(); + public render() { + const children: (callback: RenderCallback) => void | ReactNode = this.props.children as any; return ( - - - - - -

{title}

-
-
- {actionSection} -
- - {children} - -
- {modalContent && ( - - { - history.push(modalClosePath); - }} - style={{ width: '640px' }} - > - {modalContent} - - + + {!this.props.hideBreadcrumbs && ( + + {({ breadcrumbs }) => ( + + + + + + )} + )} -
+ + + + + +

{this.props.title}

+
+
+ + {(this.actionSection && this.actionSection()) || this.props.actionSection} + +
+ + + {(children && typeof children === 'function' + ? children(this.renderAction) + : children) || } + + +
+
+ ); } -) as any; + + private renderAction = (component: () => JSX.Element) => { + this.actionSection = component; + this.forceUpdate(); + }; +} + +const HeaderWrapper = styled(EuiHeader)` + height: 29px; +`; diff --git a/x-pack/plugins/beats_management/public/components/layouts/walkthrough.tsx b/x-pack/plugins/beats_management/public/components/layouts/walkthrough.tsx index 32cfd4cb43316..f4fd804996927 100644 --- a/x-pack/plugins/beats_management/public/components/layouts/walkthrough.tsx +++ b/x-pack/plugins/beats_management/public/components/layouts/walkthrough.tsx @@ -22,7 +22,6 @@ interface LayoutProps { walkthroughSteps: Array<{ id: string; name: string; - disabled: boolean; }>; activePath: string; } diff --git a/x-pack/plugins/beats_management/public/components/loading.tsx b/x-pack/plugins/beats_management/public/components/loading.tsx new file mode 100644 index 0000000000000..f1c2455ec85b9 --- /dev/null +++ b/x-pack/plugins/beats_management/public/components/loading.tsx @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { EuiFlexGroup, EuiFlexItem, EuiLoadingSpinner } from '@elastic/eui'; +import * as React from 'react'; + +export const Loading: React.SFC<{}> = () => ( + + + + + +); diff --git a/x-pack/plugins/beats_management/public/components/navigation/breadcrumb/breadcrumb.tsx b/x-pack/plugins/beats_management/public/components/navigation/breadcrumb/breadcrumb.tsx new file mode 100644 index 0000000000000..3e704ed8f246e --- /dev/null +++ b/x-pack/plugins/beats_management/public/components/navigation/breadcrumb/breadcrumb.tsx @@ -0,0 +1,62 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import React, { Component } from 'react'; +import { RouteProps } from 'react-router'; +import { BASE_PATH } from 'x-pack/plugins/beats_management/common/constants'; +import { BreadcrumbConsumer } from './consumer'; +import { Breadcrumb as BreadcrumbData, BreadcrumbContext } from './types'; + +interface BreadcrumbManagerProps extends RouteProps { + text: string; + href: string; + parents?: BreadcrumbData[]; + context: BreadcrumbContext; +} + +class BreadcrumbManager extends Component { + public componentWillUnmount() { + const { text, href, context } = this.props; + + context.removeCrumb({ + text, + href, + }); + } + + public componentDidMount() { + const { text, href, parents, context } = this.props; + context.addCrumb( + { + text, + href, + }, + parents + ); + } + + public render() { + return ; + } +} + +interface BreadcrumbProps extends RouteProps { + title: string; + path: string; + parentBreadcrumbs?: BreadcrumbData[]; +} + +export const Breadcrumb: React.SFC = ({ title, path, parentBreadcrumbs }) => ( + + {context => ( + + )} + +); diff --git a/x-pack/plugins/beats_management/public/components/route_with_breadcrumb/consumer.tsx b/x-pack/plugins/beats_management/public/components/navigation/breadcrumb/consumer.tsx similarity index 100% rename from x-pack/plugins/beats_management/public/components/route_with_breadcrumb/consumer.tsx rename to x-pack/plugins/beats_management/public/components/navigation/breadcrumb/consumer.tsx diff --git a/x-pack/plugins/beats_management/public/components/route_with_breadcrumb/context.tsx b/x-pack/plugins/beats_management/public/components/navigation/breadcrumb/context.tsx similarity index 100% rename from x-pack/plugins/beats_management/public/components/route_with_breadcrumb/context.tsx rename to x-pack/plugins/beats_management/public/components/navigation/breadcrumb/context.tsx diff --git a/x-pack/plugins/beats_management/public/components/route_with_breadcrumb/index.ts b/x-pack/plugins/beats_management/public/components/navigation/breadcrumb/index.ts similarity index 84% rename from x-pack/plugins/beats_management/public/components/route_with_breadcrumb/index.ts rename to x-pack/plugins/beats_management/public/components/navigation/breadcrumb/index.ts index 56192af8bdc0d..bfab26d8ecf59 100644 --- a/x-pack/plugins/beats_management/public/components/route_with_breadcrumb/index.ts +++ b/x-pack/plugins/beats_management/public/components/navigation/breadcrumb/index.ts @@ -6,4 +6,4 @@ export { BreadcrumbProvider } from './provider'; export { BreadcrumbConsumer } from './consumer'; -export { RouteWithBreadcrumb } from './route_with_breadcrumb'; +export { Breadcrumb } from './breadcrumb'; diff --git a/x-pack/plugins/beats_management/public/components/route_with_breadcrumb/provider.tsx b/x-pack/plugins/beats_management/public/components/navigation/breadcrumb/provider.tsx similarity index 100% rename from x-pack/plugins/beats_management/public/components/route_with_breadcrumb/provider.tsx rename to x-pack/plugins/beats_management/public/components/navigation/breadcrumb/provider.tsx diff --git a/x-pack/plugins/beats_management/public/components/route_with_breadcrumb/types.d.ts b/x-pack/plugins/beats_management/public/components/navigation/breadcrumb/types.d.ts similarity index 100% rename from x-pack/plugins/beats_management/public/components/route_with_breadcrumb/types.d.ts rename to x-pack/plugins/beats_management/public/components/navigation/breadcrumb/types.d.ts diff --git a/x-pack/plugins/beats_management/public/components/navigation/child_routes.tsx b/x-pack/plugins/beats_management/public/components/navigation/child_routes.tsx new file mode 100644 index 0000000000000..189d7b1d2a3bd --- /dev/null +++ b/x-pack/plugins/beats_management/public/components/navigation/child_routes.tsx @@ -0,0 +1,38 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import React, { SFC } from 'react'; +import { Route, Switch } from 'react-router-dom'; + +interface RouteConfig { + path: string; + component: React.ComponentType; + routes?: RouteConfig[]; +} + +export const ChildRoutes: SFC<{ + routes?: RouteConfig[]; + useSwitch?: boolean; + [other: string]: any; +}> = ({ routes, useSwitch = true, ...rest }) => { + if (!routes) { + return null; + } + const Parent = useSwitch ? Switch : React.Fragment; + return ( + + {routes.map(route => ( + { + const Component = route.component; + return ; + }} + /> + ))} + + ); +}; diff --git a/x-pack/plugins/beats_management/public/components/connected_link.tsx b/x-pack/plugins/beats_management/public/components/navigation/connected_link.tsx similarity index 96% rename from x-pack/plugins/beats_management/public/components/connected_link.tsx rename to x-pack/plugins/beats_management/public/components/navigation/connected_link.tsx index b2c0e8ad607af..30d12c9ce10de 100644 --- a/x-pack/plugins/beats_management/public/components/connected_link.tsx +++ b/x-pack/plugins/beats_management/public/components/navigation/connected_link.tsx @@ -13,6 +13,7 @@ export function ConnectedLinkComponent({ path, query, disabled, + children, ...props }: { location: any; @@ -30,7 +31,7 @@ export function ConnectedLinkComponent({ return ( diff --git a/x-pack/plugins/beats_management/public/components/route_with_breadcrumb/route_with_breadcrumb.tsx b/x-pack/plugins/beats_management/public/components/route_with_breadcrumb/route_with_breadcrumb.tsx deleted file mode 100644 index f0b5e93838b08..0000000000000 --- a/x-pack/plugins/beats_management/public/components/route_with_breadcrumb/route_with_breadcrumb.tsx +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import React, { Component } from 'react'; - -import { RouteProps } from 'react-router'; -import { Route } from 'react-router-dom'; -import { BreadcrumbConsumer } from './consumer'; -import { Breadcrumb, BreadcrumbContext } from './types'; - -interface WrappedRouteWithBreadcrumbProps extends RouteProps { - text: string; - href: string; - parents?: Breadcrumb[]; - context: BreadcrumbContext; -} - -class WrappedRouteWithBreadcrumb extends Component< - WrappedRouteWithBreadcrumbProps, - {}, - BreadcrumbContext -> { - public componentWillUnmount() { - const { text, href, context } = this.props; - - context.removeCrumb({ - text, - href, - }); - } - - public componentDidMount() { - const { text, href, parents, context } = this.props; - context.addCrumb( - { - text, - href, - }, - parents - ); - } - - public render() { - return this.props.children; - } -} - -type titleCallback = ( - urlParams: { - [key: string]: string; - } -) => string; -interface RouteWithBreadcrumbProps extends RouteProps { - title: string | titleCallback; - path: string; - parentBreadcrumbs?: Breadcrumb[]; -} - -export const RouteWithBreadcrumb: React.SFC = ({ - title, - render, - component: RouteComponent, - parentBreadcrumbs, - ...props -}) => ( - { - return ( - - {context => ( - - {render && render(renderProps)} - {RouteComponent && } - - )} - - ); - }} - /> -); diff --git a/x-pack/plugins/beats_management/public/components/table/controls.tsx b/x-pack/plugins/beats_management/public/components/table/controls.tsx index 20211ab3ced04..f484da2fa013b 100644 --- a/x-pack/plugins/beats_management/public/components/table/controls.tsx +++ b/x-pack/plugins/beats_management/public/components/table/controls.tsx @@ -8,7 +8,7 @@ import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import { InjectedIntl, injectI18n } from '@kbn/i18n/react'; import React from 'react'; import { AutocompleteField } from '../autocomplete_field/index'; -import { OptionControl } from '../table_controls'; +import { OptionControl } from './controls/index'; import { AssignmentOptions as AssignmentOptionsType, KueryBarProps } from './table'; interface ControlBarProps { diff --git a/x-pack/plugins/beats_management/public/components/table_controls/action_control.tsx b/x-pack/plugins/beats_management/public/components/table/controls/action_control.tsx similarity index 100% rename from x-pack/plugins/beats_management/public/components/table_controls/action_control.tsx rename to x-pack/plugins/beats_management/public/components/table/controls/action_control.tsx diff --git a/x-pack/plugins/beats_management/public/components/table_controls/index.ts b/x-pack/plugins/beats_management/public/components/table/controls/index.ts similarity index 100% rename from x-pack/plugins/beats_management/public/components/table_controls/index.ts rename to x-pack/plugins/beats_management/public/components/table/controls/index.ts diff --git a/x-pack/plugins/beats_management/public/components/table_controls/option_control.tsx b/x-pack/plugins/beats_management/public/components/table/controls/option_control.tsx similarity index 99% rename from x-pack/plugins/beats_management/public/components/table_controls/option_control.tsx rename to x-pack/plugins/beats_management/public/components/table/controls/option_control.tsx index df18dcb3ebfaa..3ce727df6bfa1 100644 --- a/x-pack/plugins/beats_management/public/components/table_controls/option_control.tsx +++ b/x-pack/plugins/beats_management/public/components/table/controls/option_control.tsx @@ -19,7 +19,7 @@ import { EuiIcon } from '@elastic/eui'; import { FormattedMessage, InjectedIntl, injectI18n } from '@kbn/i18n/react'; import { isArray } from 'lodash'; import React from 'react'; -import { AssignmentControlSchema } from '../table'; +import { AssignmentControlSchema } from '../index'; import { AssignmentActionType } from '../table'; import { ActionControl } from './action_control'; import { TagBadgeList } from './tag_badge_list'; diff --git a/x-pack/plugins/beats_management/public/components/table_controls/tag_assignment.tsx b/x-pack/plugins/beats_management/public/components/table/controls/tag_assignment.tsx similarity index 92% rename from x-pack/plugins/beats_management/public/components/table_controls/tag_assignment.tsx rename to x-pack/plugins/beats_management/public/components/table/controls/tag_assignment.tsx index 952636d9b9804..82f7427103cfe 100644 --- a/x-pack/plugins/beats_management/public/components/table_controls/tag_assignment.tsx +++ b/x-pack/plugins/beats_management/public/components/table/controls/tag_assignment.tsx @@ -6,8 +6,8 @@ import { EuiFlexGroup, EuiFlexItem, EuiLoadingSpinner } from '@elastic/eui'; import React from 'react'; -import { TABLE_CONFIG } from '../../../common/constants'; -import { TagBadge } from '../tag/tag_badge'; +import { TABLE_CONFIG } from '../../../../common/constants'; +import { TagBadge } from '../../tag/tag_badge'; interface TagAssignmentProps { tag: any; diff --git a/x-pack/plugins/beats_management/public/components/table_controls/tag_badge_list.tsx b/x-pack/plugins/beats_management/public/components/table/controls/tag_badge_list.tsx similarity index 94% rename from x-pack/plugins/beats_management/public/components/table_controls/tag_badge_list.tsx rename to x-pack/plugins/beats_management/public/components/table/controls/tag_badge_list.tsx index f419c086a43fe..97255801c9028 100644 --- a/x-pack/plugins/beats_management/public/components/table_controls/tag_badge_list.tsx +++ b/x-pack/plugins/beats_management/public/components/table/controls/tag_badge_list.tsx @@ -6,7 +6,7 @@ import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import React from 'react'; -import { AssignmentActionType } from '../table/table'; +import { AssignmentActionType } from '../index'; import { TagAssignment } from './tag_assignment'; interface TagBadgeListProps { diff --git a/x-pack/plugins/beats_management/public/components/table/table_type_configs.tsx b/x-pack/plugins/beats_management/public/components/table/table_type_configs.tsx index 1ee969e03ae87..95b169d1254f8 100644 --- a/x-pack/plugins/beats_management/public/components/table/table_type_configs.tsx +++ b/x-pack/plugins/beats_management/public/components/table/table_type_configs.tsx @@ -10,7 +10,7 @@ import { first, sortBy, sortByOrder, uniq } from 'lodash'; import moment from 'moment'; import React from 'react'; import { BeatTag, CMPopulatedBeat, ConfigurationBlock } from '../../../common/domain_types'; -import { ConnectedLink } from '../connected_link'; +import { ConnectedLink } from '../navigation/connected_link'; import { TagBadge } from '../tag'; export interface ColumnDefinition { @@ -61,7 +61,7 @@ export const BeatsTableType: TableType = { defaultMessage: 'Beat name', }), render: (name: string, beat: CMPopulatedBeat) => ( - {name} + {name} ), sortable: true, }, @@ -91,7 +91,6 @@ export const BeatsTableType: TableType = { sortable: false, }, { - // TODO: update to use actual metadata field field: 'config_status', name: i18n.translate('xpack.beatsManagement.beatsTable.configStatusTitle', { defaultMessage: 'Config Status', diff --git a/x-pack/plugins/beats_management/public/components/tag/config_view/config_form.tsx b/x-pack/plugins/beats_management/public/components/tag/config_view/config_form.tsx index 0c421619ab07c..c1f557c82243c 100644 --- a/x-pack/plugins/beats_management/public/components/tag/config_view/config_form.tsx +++ b/x-pack/plugins/beats_management/public/components/tag/config_view/config_form.tsx @@ -10,7 +10,7 @@ import yaml from 'js-yaml'; import { get } from 'lodash'; import React from 'react'; import { ConfigurationBlock } from '../../../../common/domain_types'; -import { YamlConfigSchema } from '../../../lib/lib'; +import { YamlConfigSchema } from '../../../lib/types'; import { FormsyEuiCodeEditor, FormsyEuiFieldText, diff --git a/x-pack/plugins/beats_management/public/components/tag/config_view/index.tsx b/x-pack/plugins/beats_management/public/components/tag/config_view/index.tsx index 2f7e983bcdbe6..98fb2df4cdf62 100644 --- a/x-pack/plugins/beats_management/public/components/tag/config_view/index.tsx +++ b/x-pack/plugins/beats_management/public/components/tag/config_view/index.tsx @@ -17,11 +17,9 @@ import { EuiFlyoutFooter, EuiFlyoutHeader, EuiFormRow, - // @ts-ignore EuiHorizontalRule, // @ts-ignore EuiSearchBar, - // @ts-ignore EuiSelect, // @ts-ignore EuiTabbedContent, diff --git a/x-pack/plugins/beats_management/public/components/tag/tag_edit.tsx b/x-pack/plugins/beats_management/public/components/tag/tag_edit.tsx index d2be9c57abf4a..fad7d346869ed 100644 --- a/x-pack/plugins/beats_management/public/components/tag/tag_edit.tsx +++ b/x-pack/plugins/beats_management/public/components/tag/tag_edit.tsx @@ -19,26 +19,23 @@ import { EuiText, EuiTitle, } from '@elastic/eui'; -import { FormattedMessage, InjectedIntl, injectI18n } from '@kbn/i18n/react'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; import 'brace/mode/yaml'; import 'brace/theme/github'; import { isEqual } from 'lodash'; import React from 'react'; import { BeatTag, CMBeat, ConfigurationBlock } from '../../../common/domain_types'; import { ConfigList } from '../config_list'; -import { AssignmentActionType, Table } from '../table'; -import { BeatsTableType } from '../table'; -import { tagConfigAssignmentOptions } from '../table'; +import { AssignmentActionType, BeatsTableType, Table, tagConfigAssignmentOptions } from '../table'; import { ConfigView } from './config_view'; import { TagBadge } from './tag_badge'; interface TagEditProps { - mode: 'edit' | 'create'; tag: Pick>; - onDetachBeat: (beatIds: string[]) => void; + onDetachBeat?: (beatIds: string[]) => void; onTagChange: (field: keyof BeatTag, value: string) => any; - attachedBeats: CMBeat[] | null; - intl: InjectedIntl; + attachedBeats?: CMBeat[]; } interface TagEditState { @@ -47,7 +44,7 @@ interface TagEditState { selectedConfigIndex?: number; } -class TagEditUi extends React.PureComponent { +export class TagEdit extends React.PureComponent { constructor(props: TagEditProps) { super(props); @@ -58,7 +55,7 @@ class TagEditUi extends React.PureComponent { } public render() { - const { tag, attachedBeats, intl } = this.props; + const { tag, attachedBeats } = this.props; return (
@@ -99,18 +96,16 @@ class TagEditUi extends React.PureComponent { name="name" isInvalid={!!this.getNameError(tag.id)} onChange={this.updateTag('id')} - disabled={this.props.mode === 'edit'} + disabled={!!this.props.onDetachBeat} value={tag.id} - placeholder={intl.formatMessage({ - id: 'xpack.beatsManagement.tag.tagNamePlaceholder', + placeholder={i18n.translate('xpack.beatsManagement.tag.tagNamePlaceholder', { defaultMessage: 'Tag name (required)', })} /> - {this.props.mode === 'create' && ( + {!this.props.onDetachBeat && ( @@ -236,10 +231,8 @@ class TagEditUi extends React.PureComponent { } private getNameError = (name: string) => { - const { intl } = this.props; if (name && name !== '' && name.search(/^[a-zA-Z0-9-]+$/) === -1) { - return intl.formatMessage({ - id: 'xpack.beatsManagement.tag.tagName.validationErrorMessage', + return i18n.translate('xpack.beatsManagement.tag.tagName.validationErrorMessage', { defaultMessage: 'Tag name must consist of letters, numbers, and dashes only', }); } else { @@ -251,15 +244,14 @@ class TagEditUi extends React.PureComponent { switch (action) { case AssignmentActionType.Delete: const { selection } = this.state.tableRef.current.state; - this.props.onDetachBeat(selection.map((beat: any) => beat.id)); + if (this.props.onDetachBeat) { + this.props.onDetachBeat(selection.map((beat: any) => beat.id)); + } } }; - // TODO this should disable save button on bad validations private updateTag = (key: keyof BeatTag, value?: any) => value !== undefined ? this.props.onTagChange(key, value) : (e: any) => this.props.onTagChange(key, e.target ? e.target.value : e); } - -export const TagEdit = injectI18n(TagEditUi); diff --git a/x-pack/plugins/beats_management/public/config_schemas.ts b/x-pack/plugins/beats_management/public/config_schemas.ts index 379e98c89be06..ef6c83265273c 100644 --- a/x-pack/plugins/beats_management/public/config_schemas.ts +++ b/x-pack/plugins/beats_management/public/config_schemas.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { YamlConfigSchema } from './lib/lib'; +import { YamlConfigSchema } from './lib/types'; const filebeatInputConfig: YamlConfigSchema[] = [ { diff --git a/x-pack/plugins/beats_management/public/config_schemas_translations_map.ts b/x-pack/plugins/beats_management/public/config_schemas_translations_map.ts index fa2fcdacb61b6..faec5a32d86d4 100644 --- a/x-pack/plugins/beats_management/public/config_schemas_translations_map.ts +++ b/x-pack/plugins/beats_management/public/config_schemas_translations_map.ts @@ -7,7 +7,7 @@ import { i18n } from '@kbn/i18n'; import { cloneDeep } from 'lodash'; import { supportedConfigs } from './config_schemas'; -import { YamlConfigSchema } from './lib/lib'; +import { YamlConfigSchema } from './lib/types'; interface ConfigSchema { text: string; @@ -226,10 +226,9 @@ export const getSupportedConfig = () => { } translatedConfigs = cloneDeep(supportedConfigs); - - translatedConfigs.forEach(({ text, config }) => { + translatedConfigs.forEach(({ text, config }, index) => { if (text) { - text = supportedConfigLabelsMap.get(text) || ''; + translatedConfigs[index].text = supportedConfigLabelsMap.get(text) || ''; } config.forEach(yanlConfig => { diff --git a/x-pack/plugins/beats_management/public/containers/beats.ts b/x-pack/plugins/beats_management/public/containers/beats.ts new file mode 100644 index 0000000000000..cd29a65191c75 --- /dev/null +++ b/x-pack/plugins/beats_management/public/containers/beats.ts @@ -0,0 +1,98 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { Container } from 'unstated'; +import { CMPopulatedBeat } from './../../common/domain_types'; +import { BeatsTagAssignment } from './../../server/lib/adapters/beats/adapter_types'; +import { FrontendLibs } from './../lib/types'; + +interface ContainerState { + list: CMPopulatedBeat[]; +} + +export class BeatsContainer extends Container { + private query?: string; + constructor(private readonly libs: FrontendLibs) { + super(); + this.state = { + list: [], + }; + } + + public getBeatWithToken = async (token: string) => { + const beat = await this.libs.beats.getBeatWithToken(token); + + if (beat) { + this.setState({ + list: [beat as CMPopulatedBeat, ...this.state.list], + }); + return beat as CMPopulatedBeat; + } + return null; + }; + + public reload = async (kuery?: string) => { + if (kuery) { + this.query = await this.libs.elasticsearch.convertKueryToEsQuery(kuery); + } else { + this.query = undefined; + } + const beats = await this.libs.beats.getAll(this.query); + + this.setState({ + list: beats, + }); + }; + + public deactivate = async (beats: CMPopulatedBeat[]) => { + for (const beat of beats) { + await this.libs.beats.update(beat.id, { active: false }); + } + + // because the compile code above has a very minor race condition, we wait, + // the max race condition time is really 10ms but doing 100 to be safe + setTimeout(async () => { + await this.reload(this.query); + }, 100); + }; + + public toggleTagAssignment = async (tagId: string, beats: CMPopulatedBeat[]) => { + if (beats.some(beat => beat.full_tags.some(({ id }) => id === tagId))) { + await this.removeTagsFromBeats(beats, tagId); + return 'removed'; + } + await this.assignTagsToBeats(beats, tagId); + return 'added'; + }; + + public removeTagsFromBeats = async (beats: CMPopulatedBeat[] | string[], tagId: string) => { + if (!beats.length) { + return false; + } + const assignments = createBeatTagAssignments(beats, tagId); + await this.libs.beats.removeTagsFromBeats(assignments); + await this.reload(this.query); + }; + + public assignTagsToBeats = async (beats: CMPopulatedBeat[] | string[], tagId: string) => { + if (!beats.length) { + return false; + } + const assignments = createBeatTagAssignments(beats, tagId); + await this.libs.beats.assignTagsToBeats(assignments); + await this.reload(this.query); + }; +} + +function createBeatTagAssignments( + beats: CMPopulatedBeat[] | string[], + tagId: string +): BeatsTagAssignment[] { + if (typeof beats[0] === 'string') { + return (beats as string[]).map(id => ({ beatId: id, tag: tagId })); + } else { + return (beats as CMPopulatedBeat[]).map(({ id }) => ({ beatId: id, tag: tagId })); + } +} diff --git a/x-pack/plugins/beats_management/public/containers/tags.ts b/x-pack/plugins/beats_management/public/containers/tags.ts new file mode 100644 index 0000000000000..4210ddc9c0831 --- /dev/null +++ b/x-pack/plugins/beats_management/public/containers/tags.ts @@ -0,0 +1,45 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { Container } from 'unstated'; +import { BeatTag } from '../../common/domain_types'; +import { FrontendLibs } from '../lib/types'; + +interface ContainerState { + list: BeatTag[]; +} + +export class TagsContainer extends Container { + private query?: string; + constructor(private readonly libs: FrontendLibs) { + super(); + this.state = { + list: [], + }; + } + public reload = async (kuery?: string) => { + if (kuery) { + this.query = await this.libs.elasticsearch.convertKueryToEsQuery(kuery); + } else { + this.query = undefined; + } + + const tags = await this.libs.tags.getAll(this.query); + + this.setState({ + list: tags, + }); + }; + + public delete = async (tags: BeatTag[]) => { + const tagIds = tags.map((tag: BeatTag) => tag.id); + const success = await this.libs.tags.delete(tagIds); + if (success) { + this.reload(this.query); + } + return success; + }; +} diff --git a/x-pack/plugins/beats_management/public/containers/with_kuery_autocompletion.tsx b/x-pack/plugins/beats_management/public/containers/with_kuery_autocompletion.tsx index a0a2afb7e63f2..5f60464cb0a0e 100644 --- a/x-pack/plugins/beats_management/public/containers/with_kuery_autocompletion.tsx +++ b/x-pack/plugins/beats_management/public/containers/with_kuery_autocompletion.tsx @@ -8,7 +8,7 @@ import React from 'react'; import { AutocompleteSuggestion } from 'ui/autocomplete_providers'; -import { FrontendLibs } from '../lib/lib'; +import { FrontendLibs } from '../lib/types'; import { RendererFunction } from '../utils/typed_react'; interface WithKueryAutocompletionLifecycleProps { diff --git a/x-pack/plugins/beats_management/public/containers/with_url_state.tsx b/x-pack/plugins/beats_management/public/containers/with_url_state.tsx index 1630c2c20cda8..0802b4d8ea7e8 100644 --- a/x-pack/plugins/beats_management/public/containers/with_url_state.tsx +++ b/x-pack/plugins/beats_management/public/containers/with_url_state.tsx @@ -7,7 +7,7 @@ import { parse, stringify } from 'querystring'; import React from 'react'; import { withRouter } from 'react-router-dom'; -import { FlatObject } from '../app'; +import { FlatObject } from '../frontend_types'; import { RendererFunction } from '../utils/typed_react'; type StateCallback = (previousState: T) => T; @@ -88,7 +88,9 @@ export class WithURLStateComponent extends React.Compon } export const WithURLState = withRouter(WithURLStateComponent); -export function withUrlState(UnwrappedComponent: React.ComponentType): React.SFC { +export function withUrlState( + UnwrappedComponent: React.ComponentType +): React.SFC { return (origProps: OP) => { return ( diff --git a/x-pack/plugins/beats_management/public/frontend_types.d.ts b/x-pack/plugins/beats_management/public/frontend_types.d.ts new file mode 100644 index 0000000000000..bcaac2b3781aa --- /dev/null +++ b/x-pack/plugins/beats_management/public/frontend_types.d.ts @@ -0,0 +1,34 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { RouteComponentProps } from 'react-router'; +import { BeatsContainer } from './containers/beats'; +import { TagsContainer } from './containers/tags'; +import { URLStateProps } from './containers/with_url_state'; +import { FrontendLibs } from './lib/types'; + +export type FlatObject = { [Key in keyof T]: string }; + +export interface AppURLState { + beatsKBar?: string; + tagsKBar?: string; + enrollmentToken?: string; + createdTag?: string; +} + +export interface RouteConfig { + path: string; + component: React.ComponentType; + routes?: RouteConfig[]; +} + +export interface AppPageProps extends URLStateProps, RouteComponentProps { + libs: FrontendLibs; + containers: { + beats: BeatsContainer; + tags: TagsContainer; + }; + routes?: RouteConfig[]; +} diff --git a/x-pack/plugins/beats_management/public/index.tsx b/x-pack/plugins/beats_management/public/index.tsx index 1c2fb15fdc5fd..f8273e7b0ab10 100644 --- a/x-pack/plugins/beats_management/public/index.tsx +++ b/x-pack/plugins/beats_management/public/index.tsx @@ -8,30 +8,60 @@ import * as euiVars from '@elastic/eui/dist/eui_theme_k6_light.json'; import { i18n } from '@kbn/i18n'; import { I18nProvider } from '@kbn/i18n/react'; import React from 'react'; +import { HashRouter } from 'react-router-dom'; import { ThemeProvider } from 'styled-components'; +import { Provider as UnstatedProvider, Subscribe } from 'unstated'; import { BASE_PATH } from '../common/constants'; -import { BreadcrumbProvider } from './components/route_with_breadcrumb'; +import { Background } from './components/layouts/background'; +import { BreadcrumbProvider } from './components/navigation/breadcrumb'; +import { BeatsContainer } from './containers/beats'; +import { TagsContainer } from './containers/tags'; import { compose } from './lib/compose/kibana'; -import { FrontendLibs } from './lib/lib'; -import { PageRouter } from './router'; +import { FrontendLibs } from './lib/types'; +import { AppRouter } from './router'; -function startApp(libs: FrontendLibs) { - libs.framework.registerManagementSection( - 'beats', - i18n.translate('xpack.beatsManagement.managementMainPage.centralManagementLinkLabel', { - defaultMessage: 'Central Management (Beta)', - }), - BASE_PATH - ); - libs.framework.render( - - - - - - - +async function startApp(libs: FrontendLibs) { + libs.framework.renderUIAtPath( + BASE_PATH, + + + + + + + {(beats: BeatsContainer, tags: TagsContainer) => ( + + + + )} + + + + + + , + libs.framework.getUISetting('k7design') ? 'management' : 'self' ); + + await libs.framework.waitUntilFrameworkReady(); + + if (libs.framework.licenseIsAtLeast('standard')) { + libs.framework.registerManagementSection({ + id: 'beats', + name: i18n.translate('xpack.beatsManagement.centralManagementSectionLabel', { + defaultMessage: 'Beats', + }), + iconName: 'logoBeats', + }); + + libs.framework.registerManagementUI({ + sectionId: 'beats', + name: i18n.translate('xpack.beatsManagement.centralManagementLinkLabel', { + defaultMessage: 'Central Management (Beta)', + }), + basePath: BASE_PATH, + }); + } } startApp(compose()); diff --git a/x-pack/plugins/beats_management/public/lib/adapters/beats/rest_beats_adapter.ts b/x-pack/plugins/beats_management/public/lib/adapters/beats/rest_beats_adapter.ts index 8649bf9c37e0e..f2a020618e2e8 100644 --- a/x-pack/plugins/beats_management/public/lib/adapters/beats/rest_beats_adapter.ts +++ b/x-pack/plugins/beats_management/public/lib/adapters/beats/rest_beats_adapter.ts @@ -24,7 +24,7 @@ export class RestBeatsAdapter implements CMBeatsAdapter { return beat; } - public async getAll(ESQuery?: any): Promise { + public async getAll(ESQuery?: string): Promise { return (await this.REST.get<{ beats: CMBeat[] }>('/api/beats/agents/all', { ESQuery })).beats; } diff --git a/x-pack/plugins/beats_management/public/lib/adapters/elasticsearch/rest.ts b/x-pack/plugins/beats_management/public/lib/adapters/elasticsearch/rest.ts index e4b4e73afc18c..8899ddd7976d5 100644 --- a/x-pack/plugins/beats_management/public/lib/adapters/elasticsearch/rest.ts +++ b/x-pack/plugins/beats_management/public/lib/adapters/elasticsearch/rest.ts @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -// @ts-ignore TODO type this import { fromKueryExpression, toElasticsearchQuery } from '@kbn/es-query'; import { isEmpty } from 'lodash'; import { AutocompleteSuggestion, getAutocompleteProvider } from 'ui/autocomplete_providers'; diff --git a/x-pack/plugins/beats_management/public/lib/adapters/framework/adapter_types.ts b/x-pack/plugins/beats_management/public/lib/adapters/framework/adapter_types.ts new file mode 100644 index 0000000000000..ac03e9f13d6c2 --- /dev/null +++ b/x-pack/plugins/beats_management/public/lib/adapters/framework/adapter_types.ts @@ -0,0 +1,81 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import * as t from 'io-ts'; +import { LICENSES } from './../../../../common/constants/security'; + +export interface FrameworkAdapter { + // Instance vars + info: FrameworkInfo; + currentUser: FrameworkUser; + // Methods + waitUntilFrameworkReady(): Promise; + renderUIAtPath(path: string, component: React.ReactElement): void; + registerManagementSection(settings: { + id?: string; + name: string; + iconName: string; + order?: number; + }): void; + registerManagementUI(settings: { + id?: string; + name: string; + basePath: string; + visable?: boolean; + order?: number; + }): void; + setUISettings(key: string, value: any): void; + getUISetting(key: 'k7design'): boolean; +} + +export const RuntimeFrameworkInfo = t.type({ + basePath: t.string, + k7Design: t.boolean, + license: t.type({ + type: t.union(LICENSES.map(s => t.literal(s))), + expired: t.boolean, + expiry_date_in_millis: t.number, + }), + security: t.type({ + enabled: t.boolean, + available: t.boolean, + }), + settings: t.type({ + encryptionKey: t.string, + enrollmentTokensTtlInSeconds: t.number, + defaultUserRoles: t.array(t.string), + }), +}); + +export interface FrameworkInfo extends t.TypeOf {} + +interface ManagementSection { + register( + sectionId: string, + options: { + visible: boolean; + display: string; + order: number; + url: string; + } + ): void; +} +export interface ManagementAPI { + getSection(sectionId: string): ManagementSection; + hasItem(sectionId: string): boolean; + register(sectionId: string, options: { display: string; icon: string; order: number }): void; +} + +export const RuntimeFrameworkUser = t.interface( + { + username: t.string, + roles: t.array(t.string), + full_name: t.union([t.null, t.string]), + email: t.union([t.null, t.string]), + enabled: t.boolean, + }, + 'FrameworkUser' +); +export interface FrameworkUser extends t.TypeOf {} diff --git a/x-pack/plugins/beats_management/public/lib/adapters/framework/kibana_framework_adapter.ts b/x-pack/plugins/beats_management/public/lib/adapters/framework/kibana_framework_adapter.ts index 1db905845e936..33cf335b0cf77 100644 --- a/x-pack/plugins/beats_management/public/lib/adapters/framework/kibana_framework_adapter.ts +++ b/x-pack/plugins/beats_management/public/lib/adapters/framework/kibana_framework_adapter.ts @@ -4,49 +4,64 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IModule, IScope } from 'angular'; +import { IScope } from 'angular'; +import { PathReporter } from 'io-ts/lib/PathReporter'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; - -import { i18n } from '@kbn/i18n'; +import { UIRoutes } from 'ui/routes'; +import { BufferedKibanaServiceCall, KibanaAdapterServiceRefs, KibanaUIConfig } from '../../types'; import { - BufferedKibanaServiceCall, FrameworkAdapter, - KibanaAdapterServiceRefs, - KibanaUIConfig, -} from '../../lib'; + FrameworkInfo, + FrameworkUser, + ManagementAPI, + RuntimeFrameworkInfo, + RuntimeFrameworkUser, +} from './adapter_types'; +interface IInjector { + get(injectable: string): any; +} export class KibanaFrameworkAdapter implements FrameworkAdapter { - public appState: object; + public get info() { + if (this.xpackInfo) { + return this.xpackInfo; + } else { + throw new Error('framework adapter must have init called before anything else'); + } + } - private management: any; + public get currentUser() { + return this.shieldUser!; + } + private xpackInfo: FrameworkInfo | null = null; private adapterService: KibanaAdapterServiceProvider; - private rootComponent: React.ReactElement | null = null; - private uiModule: IModule; - private routes: any; - private XPackInfoProvider: any; - private xpackInfo: null | any; - private chrome: any; - private shieldUser: any; - + private shieldUser: FrameworkUser | null = null; + private settingSubscription: any; constructor( - uiModule: IModule, - management: any, - routes: any, - chrome: any, - XPackInfoProvider: any + private readonly PLUGIN_ID: string, + private readonly management: ManagementAPI, + private readonly routes: UIRoutes, + private readonly getBasePath: () => string, + private readonly onKibanaReady: () => Promise, + private readonly XPackInfoProvider: unknown, + private readonly uiSettings: any ) { this.adapterService = new KibanaAdapterServiceProvider(); - this.management = management; - this.uiModule = uiModule; - this.routes = routes; - this.chrome = chrome; - this.XPackInfoProvider = XPackInfoProvider; - this.appState = {}; + + this.settingSubscription = uiSettings.getUpdate$().subscribe({ + next: ({ key, newValue }: { key: string; newValue: boolean }) => { + if (key === 'k7design' && this.xpackInfo) { + this.xpackInfo.k7Design = newValue; + } + }, + }); } - public get baseURLPath(): string { - return this.chrome.getBasePath(); + // We dont really want to have this, but it's needed to conditionaly render for k7 due to + // when that data is needed. + public getUISetting(key: 'k7design'): boolean { + return this.uiSettings.get(key); } public setUISettings = (key: string, value: any) => { @@ -55,71 +70,137 @@ export class KibanaFrameworkAdapter implements FrameworkAdapter { }); }; - public render = (component: React.ReactElement) => { - this.rootComponent = component; - }; + public async waitUntilFrameworkReady(): Promise { + const $injector = await this.onKibanaReady(); + const Private: any = $injector.get('Private'); - public hasValidLicense() { - if (!this.xpackInfo) { - return false; + let xpackInfo: any; + try { + xpackInfo = Private(this.XPackInfoProvider); + } catch (e) { + xpackInfo = false; } - return this.xpackInfo.get('features.beats_management.licenseValid', false); - } - public licenseExpired() { - if (!this.xpackInfo) { - return false; + let xpackInfoUnpacked: FrameworkInfo; + try { + xpackInfoUnpacked = { + basePath: this.getBasePath(), + k7Design: this.uiSettings.get('k7design'), + license: { + type: xpackInfo ? xpackInfo.getLicense().type : 'oss', + expired: xpackInfo ? !xpackInfo.getLicense().isActive : false, + expiry_date_in_millis: xpackInfo ? xpackInfo.getLicense().expiryDateInMillis : 0, + }, + security: { + enabled: xpackInfo + ? xpackInfo.get(`features.${this.PLUGIN_ID}.security.enabled`, false) + : false, + available: xpackInfo + ? xpackInfo.get(`features.${this.PLUGIN_ID}.security.available`, false) + : false, + }, + settings: xpackInfo ? xpackInfo.get(`features.${this.PLUGIN_ID}.settings`) : {}, + }; + } catch (e) { + throw new Error(`Unexpected data structure from XPackInfoProvider, ${JSON.stringify(e)}`); } - return this.xpackInfo.get('features.beats_management.licenseExpired', false); - } - public securityEnabled() { - if (!this.xpackInfo) { - return false; + const assertData = RuntimeFrameworkInfo.decode(xpackInfoUnpacked); + if (assertData.isLeft()) { + throw new Error( + `Error parsing xpack info in ${this.PLUGIN_ID}, ${PathReporter.report(assertData)[0]}` + ); } + this.xpackInfo = xpackInfoUnpacked; - return this.xpackInfo.get('features.beats_management.securityEnabled', false); - } + try { + this.shieldUser = await $injector.get('ShieldUser').getCurrent().$promise; + const assertUser = RuntimeFrameworkUser.decode(this.shieldUser); - public getDefaultUserRoles() { - if (!this.xpackInfo) { - return []; + if (assertUser.isLeft()) { + throw new Error( + `Error parsing user info in ${this.PLUGIN_ID}, ${PathReporter.report(assertUser)[0]}` + ); + } + } catch (e) { + this.shieldUser = null; } + } - return this.xpackInfo.get('features.beats_management.defaultUserRoles'); + public renderUIAtPath( + path: string, + component: React.ReactElement, + toController: 'management' | 'self' = 'self' + ) { + const DOM_ELEMENT_NAME = this.PLUGIN_ID.replace('_', '-'); + const adapter = this; + this.routes.when( + `${path}${[...Array(6)].map((e, n) => `/:arg${n}?`).join('')}`, // Hack because angular 1 does not support wildcards + { + template: + toController === 'self' + ? `<${DOM_ELEMENT_NAME}>
` + : ` +
+ `, + // tslint:disable-next-line: max-classes-per-file + controller: ($scope: any, $route: any) => { + try { + $scope.$$postDigest(() => { + const elem = document.getElementById(`${DOM_ELEMENT_NAME}ReactRoot`); + ReactDOM.render(component, elem); + adapter.manageAngularLifecycle($scope, $route, elem); + }); + $scope.$onInit = () => { + $scope.topNavMenu = []; + }; + } catch (e) { + throw new Error(`Error rendering Beats CM to the dom, ${e.message}`); + } + }, + } + ); } - public getCurrentUser() { - try { - return this.shieldUser; - } catch (e) { - return null; + public registerManagementSection(settings: { + id?: string; + name: string; + iconName: string; + order?: number; + }) { + const sectionId = settings.id || this.PLUGIN_ID; + + if (!this.management.hasItem(sectionId)) { + this.management.register(sectionId, { + display: settings.name, + icon: settings.iconName, + order: settings.order || 30, + }); } } - public registerManagementSection(pluginId: string, displayName: string, basePath: string) { - this.register(this.uiModule); - - this.hookAngular(() => { - if (this.hasValidLicense()) { - const registerSection = () => - this.management.register(pluginId, { - display: i18n.translate('xpack.beatsManagement.beatsDislayName', { - defaultMessage: 'Beats', - }), // TODO these need to be config options not hard coded in the adapter - icon: 'logoBeats', - order: 30, - }); - const getSection = () => this.management.getSection(pluginId); - const section = this.management.hasItem(pluginId) ? getSection() : registerSection(); - - section.register(pluginId, { - visible: true, - display: displayName, - order: 30, - url: `#${basePath}`, - }); - } + public registerManagementUI(settings: { + sectionId?: string; + name: string; + basePath: string; + visable?: boolean; + order?: number; + }) { + const sectionId = settings.sectionId || this.PLUGIN_ID; + + if (!this.management.hasItem(sectionId)) { + throw new Error( + `registerManagementUI was called with a sectionId of ${sectionId}, and that is is not yet regestered as a section` + ); + } + + const section = this.management.getSection(sectionId); + + section.register(sectionId, { + visible: settings.visable || true, + display: settings.name, + order: settings.order || 30, + url: `#${settings.basePath}`, }); } @@ -131,58 +212,27 @@ export class KibanaFrameworkAdapter implements FrameworkAdapter { if (lastRoute.$$route.template === currentRoute.$$route.template) { // this prevents angular from destroying scope $route.current = lastRoute; + } else { + if (elem) { + ReactDOM.unmountComponentAtNode(elem); + elem.remove(); + this.settingSubscription.unsubscribe(); + } } }); $scope.$on('$destroy', () => { if (deregister) { deregister(); } + // manually unmount component when scope is destroyed if (elem) { ReactDOM.unmountComponentAtNode(elem); + elem.remove(); + this.settingSubscription.unsubscribe(); } }); } - - private hookAngular(done: () => any) { - this.chrome.dangerouslyGetActiveInjector().then(async ($injector: any) => { - const Private = $injector.get('Private'); - const xpackInfo = Private(this.XPackInfoProvider); - - this.xpackInfo = xpackInfo; - if (this.securityEnabled()) { - try { - this.shieldUser = await $injector.get('ShieldUser').getCurrent().$promise; - } catch (e) { - // errors when security disabled, even though we check first because angular - } - } - - done(); - }); - } - - private register = (adapterModule: IModule) => { - const adapter = this; - this.routes.when(`/management/beats_management/:view?/:id?/:other?/:other2?`, { - template: - '
', - controllerAs: 'beatsManagement', - // tslint:disable-next-line: max-classes-per-file - controller: class BeatsManagementController { - constructor($scope: any, $route: any) { - $scope.$$postDigest(() => { - const elem = document.getElementById('beatsReactRoot'); - ReactDOM.render(adapter.rootComponent as React.ReactElement, elem); - adapter.manageAngularLifecycle($scope, $route, elem); - }); - $scope.$onInit = () => { - $scope.topNavMenu = []; - }; - } - }, - }); - }; } // tslint:disable-next-line: max-classes-per-file diff --git a/x-pack/plugins/beats_management/public/lib/adapters/rest_api/adapter_types.ts b/x-pack/plugins/beats_management/public/lib/adapters/rest_api/adapter_types.ts index e9d9bf551f739..c13d9fdc2dfe6 100644 --- a/x-pack/plugins/beats_management/public/lib/adapters/rest_api/adapter_types.ts +++ b/x-pack/plugins/beats_management/public/lib/adapters/rest_api/adapter_types.ts @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { FlatObject } from '../../../app'; +import { FlatObject } from '../../../frontend_types'; export interface RestAPIAdapter { get(url: string, query?: FlatObject): Promise; diff --git a/x-pack/plugins/beats_management/public/lib/adapters/rest_api/axios_rest_api_adapter.ts b/x-pack/plugins/beats_management/public/lib/adapters/rest_api/axios_rest_api_adapter.ts index 690843bbb1cf8..dbd9a5a5e66a1 100644 --- a/x-pack/plugins/beats_management/public/lib/adapters/rest_api/axios_rest_api_adapter.ts +++ b/x-pack/plugins/beats_management/public/lib/adapters/rest_api/axios_rest_api_adapter.ts @@ -5,7 +5,7 @@ */ import axios, { AxiosInstance } from 'axios'; -import { FlatObject } from '../../../app'; +import { FlatObject } from '../../../frontend_types'; import { RestAPIAdapter } from './adapter_types'; let globalAPI: AxiosInstance; diff --git a/x-pack/plugins/beats_management/public/lib/adapters/tags/adapter_types.ts b/x-pack/plugins/beats_management/public/lib/adapters/tags/adapter_types.ts index 395c01f259dc3..bcebba0c880a8 100644 --- a/x-pack/plugins/beats_management/public/lib/adapters/tags/adapter_types.ts +++ b/x-pack/plugins/beats_management/public/lib/adapters/tags/adapter_types.ts @@ -8,6 +8,6 @@ import { BeatTag } from '../../../../common/domain_types'; export interface CMTagsAdapter { getTagsWithIds(tagIds: string[]): Promise; delete(tagIds: string[]): Promise; - getAll(): Promise; + getAll(ESQuery?: string): Promise; upsertTag(tag: BeatTag): Promise; } diff --git a/x-pack/plugins/beats_management/public/lib/adapters/tags/memory_tags_adapter.ts b/x-pack/plugins/beats_management/public/lib/adapters/tags/memory_tags_adapter.ts index 86daefb47c653..d44f7e1f34f97 100644 --- a/x-pack/plugins/beats_management/public/lib/adapters/tags/memory_tags_adapter.ts +++ b/x-pack/plugins/beats_management/public/lib/adapters/tags/memory_tags_adapter.ts @@ -23,7 +23,7 @@ export class MemoryTagsAdapter implements CMTagsAdapter { return true; } - public async getAll() { + public async getAll(ESQuery?: string) { return this.tagsDB; } diff --git a/x-pack/plugins/beats_management/public/lib/adapters/tags/rest_tags_adapter.ts b/x-pack/plugins/beats_management/public/lib/adapters/tags/rest_tags_adapter.ts index e49d4a9109984..381b320fffe7f 100644 --- a/x-pack/plugins/beats_management/public/lib/adapters/tags/rest_tags_adapter.ts +++ b/x-pack/plugins/beats_management/public/lib/adapters/tags/rest_tags_adapter.ts @@ -16,8 +16,8 @@ export class RestTagsAdapter implements CMTagsAdapter { return tags; } - public async getAll(): Promise { - return await this.REST.get(`/api/beats/tags`); + public async getAll(ESQuery: string): Promise { + return await this.REST.get(`/api/beats/tags`, { ESQuery }); } public async delete(tagIds: string[]): Promise { diff --git a/x-pack/plugins/beats_management/public/lib/beats.ts b/x-pack/plugins/beats_management/public/lib/beats.ts index f676f4611be63..4ff5f7e959d74 100644 --- a/x-pack/plugins/beats_management/public/lib/beats.ts +++ b/x-pack/plugins/beats_management/public/lib/beats.ts @@ -12,7 +12,7 @@ import { CMAssignmentReturn, CMBeatsAdapter, } from './adapters/beats/adapter_types'; -import { FrontendDomainLibs } from './lib'; +import { FrontendDomainLibs } from './types'; export class BeatsLib { constructor( @@ -20,44 +20,58 @@ export class BeatsLib { private readonly libs: { tags: FrontendDomainLibs['tags'] } ) {} + /** Get a single beat using it's ID for lookup */ public async get(id: string): Promise { const beat = await this.adapter.get(id); return beat ? (await this.mergeInTags([beat]))[0] : null; } - public async getBeatWithToken(enrollmentToken: string): Promise { + /** Get a single beat using the token it was enrolled in for lookup */ + public getBeatWithToken = async (enrollmentToken: string): Promise => { const beat = await this.adapter.getBeatWithToken(enrollmentToken); return beat; - } + }; - public async getBeatsWithTag(tagId: string): Promise { + /** Get an array of beats that have a given tag id assigned to it */ + public getBeatsWithTag = async (tagId: string): Promise => { const beats = await this.adapter.getBeatsWithTag(tagId); return await this.mergeInTags(beats); - } + }; - public async getAll(ESQuery?: any): Promise { + // FIXME: This needs to be paginated https://github.com/elastic/kibana/issues/26022 + /** Get an array of all enrolled beats. */ + public getAll = async (ESQuery?: string): Promise => { const beats = await this.adapter.getAll(ESQuery); return await this.mergeInTags(beats); - } + }; - public async update(id: string, beatData: Partial): Promise { + /** Update a given beat via it's ID */ + public update = async (id: string, beatData: Partial): Promise => { return await this.adapter.update(id, beatData); - } + }; - public async removeTagsFromBeats(removals: BeatsTagAssignment[]): Promise { + /** unassign tags from beats using an array of tags and beats */ + public removeTagsFromBeats = async ( + removals: BeatsTagAssignment[] + ): Promise => { return await this.adapter.removeTagsFromBeats(removals); - } + }; - public async assignTagsToBeats(assignments: BeatsTagAssignment[]): Promise { + /** assign tags from beats using an array of tags and beats */ + public assignTagsToBeats = async ( + assignments: BeatsTagAssignment[] + ): Promise => { return await this.adapter.assignTagsToBeats(assignments); - } + }; - private async mergeInTags(beats: CMBeat[]): Promise { + /** method user to join tags to beats, thus fully populating the beats */ + private mergeInTags = async (beats: CMBeat[]): Promise => { const tagIds = flatten(beats.map(b => b.tags || [])); const tags = await this.libs.tags.getTagsWithIds(tagIds); // TODO the filter should not be needed, if the data gets into a bad state, we should error - // and inform the user they need to delte the tag, or else we should auto delete it + // and inform the user they need to delete the tag, or else we should auto delete it + // https://github.com/elastic/kibana/issues/26021 const mergedBeats: CMPopulatedBeat[] = beats.map( b => ({ @@ -66,5 +80,5 @@ export class BeatsLib { } as CMPopulatedBeat) ); return mergedBeats; - } + }; } diff --git a/x-pack/plugins/beats_management/public/lib/compose/kibana.ts b/x-pack/plugins/beats_management/public/lib/compose/kibana.ts index 9f2b7a3d88b0b..e1a82da8fb493 100644 --- a/x-pack/plugins/beats_management/public/lib/compose/kibana.ts +++ b/x-pack/plugins/beats_management/public/lib/compose/kibana.ts @@ -4,19 +4,13 @@ * you may not use this file except in compliance with the Elastic License. */ -// @ts-ignore +// @ts-ignore not typed yet import { XPackInfoProvider } from 'plugins/xpack_main/services/xpack_info'; -// @ts-ignore import 'ui/autoload/all'; -// @ts-ignore: path dynamic for kibana import chrome from 'ui/chrome'; -// @ts-ignore: path dynamic for kibana +// @ts-ignore not typed yet import { management } from 'ui/management'; -// @ts-ignore: path dynamic for kibana -import { uiModules } from 'ui/modules'; -// @ts-ignore: path dynamic for kibana import routes from 'ui/routes'; - import { INDEX_NAMES } from '../../../common/constants/index_names'; import { getSupportedConfig } from '../../config_schemas_translations_map'; import { RestBeatsAdapter } from '../adapters/beats/rest_beats_adapter'; @@ -27,8 +21,13 @@ import { RestTagsAdapter } from '../adapters/tags/rest_tags_adapter'; import { RestTokensAdapter } from '../adapters/tokens/rest_tokens_adapter'; import { BeatsLib } from '../beats'; import { ElasticsearchLib } from '../elasticsearch'; -import { FrontendDomainLibs, FrontendLibs } from '../lib'; import { TagsLib } from '../tags'; +import { FrontendLibs } from '../types'; +import { PLUGIN } from './../../../common/constants/plugin'; +import { FrameworkLib } from './../framework'; + +// A super early spot in kibana loading that we can use to hook before most other things +const onKibanaReady = chrome.dangerouslyGetActiveInjector; export function compose(): FrontendLibs { const api = new AxiosRestAPIAdapter(chrome.getXsrfToken(), chrome.getBasePath()); @@ -40,25 +39,24 @@ export function compose(): FrontendLibs { tags, }); - const domainLibs: FrontendDomainLibs = { - tags, - tokens, - beats, - }; - const pluginUIModule = uiModules.get('app/beats_management'); - - const framework = new KibanaFrameworkAdapter( - pluginUIModule, - management, - routes, - chrome, - XPackInfoProvider + const framework = new FrameworkLib( + new KibanaFrameworkAdapter( + PLUGIN.ID, + management, + routes, + chrome.getBasePath, + onKibanaReady, + XPackInfoProvider, + chrome.getUiSettingsClient() + ) ); const libs: FrontendLibs = { framework, elasticsearch: new ElasticsearchLib(esAdapter), - ...domainLibs, + tags, + tokens, + beats, }; return libs; } diff --git a/x-pack/plugins/beats_management/public/lib/compose/memory.ts b/x-pack/plugins/beats_management/public/lib/compose/memory.ts index cf1d4a9aa003e..6767c72801cb3 100644 --- a/x-pack/plugins/beats_management/public/lib/compose/memory.ts +++ b/x-pack/plugins/beats_management/public/lib/compose/memory.ts @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ +import { AutocompleteSuggestion } from 'ui/autocomplete_providers'; import 'ui/autoload/all'; // @ts-ignore: path dynamic for kibana import { management } from 'ui/management'; @@ -11,21 +12,21 @@ import { management } from 'ui/management'; import { uiModules } from 'ui/modules'; // @ts-ignore: path dynamic for kibana import routes from 'ui/routes'; +import { getSupportedConfig } from '../../config_schemas_translations_map'; // @ts-ignore: path dynamic for kibana import { MemoryBeatsAdapter } from '../adapters/beats/memory_beats_adapter'; import { KibanaFrameworkAdapter } from '../adapters/framework/kibana_framework_adapter'; import { MemoryTagsAdapter } from '../adapters/tags/memory_tags_adapter'; import { MemoryTokensAdapter } from '../adapters/tokens/memory_tokens_adapter'; - import { BeatsLib } from '../beats'; -import { FrontendDomainLibs, FrontendLibs } from '../lib'; - -import { AutocompleteSuggestion } from 'ui/autocomplete_providers'; -import { getSupportedConfig } from '../../config_schemas_translations_map'; +import { FrameworkLib } from '../framework'; import { TagsLib } from '../tags'; +import { FrontendLibs } from '../types'; import { MemoryElasticsearchAdapter } from './../adapters/elasticsearch/memory'; import { ElasticsearchLib } from './../elasticsearch'; +const onKibanaReady = uiModules.get('kibana').run; + export function compose( mockIsKueryValid: (kuery: string) => boolean, mockKueryToEsQuery: (kuery: string) => string, @@ -40,18 +41,25 @@ export function compose( const tokens = new MemoryTokensAdapter(); const beats = new BeatsLib(new MemoryBeatsAdapter([]), { tags }); - const domainLibs: FrontendDomainLibs = { - tags, - tokens, - beats, - }; const pluginUIModule = uiModules.get('app/beats_management'); - const framework = new KibanaFrameworkAdapter(pluginUIModule, management, routes, null, null); + const framework = new FrameworkLib( + new KibanaFrameworkAdapter( + pluginUIModule, + management, + routes, + () => '', + onKibanaReady, + null, + null + ) + ); const libs: FrontendLibs = { - ...domainLibs, - elasticsearch: new ElasticsearchLib(esAdapter), framework, + elasticsearch: new ElasticsearchLib(esAdapter), + tags, + tokens, + beats, }; return libs; } diff --git a/x-pack/plugins/beats_management/public/lib/framework.ts b/x-pack/plugins/beats_management/public/lib/framework.ts new file mode 100644 index 0000000000000..7050a40aed5ed --- /dev/null +++ b/x-pack/plugins/beats_management/public/lib/framework.ts @@ -0,0 +1,40 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { difference, get } from 'lodash'; +import { LICENSES, LicenseType } from '../../common/constants/security'; +import { FrameworkAdapter } from './adapters/framework/adapter_types'; + +export class FrameworkLib { + public waitUntilFrameworkReady = this.adapter.waitUntilFrameworkReady.bind(this.adapter); + public renderUIAtPath = this.adapter.renderUIAtPath.bind(this.adapter); + public registerManagementSection = this.adapter.registerManagementSection.bind(this.adapter); + public registerManagementUI = this.adapter.registerManagementUI.bind(this.adapter); + public setUISettings = this.adapter.setUISettings.bind(this.adapter); + public getUISetting = this.adapter.getUISetting.bind(this.adapter); + + constructor(private readonly adapter: FrameworkAdapter) {} + + public get currentUser() { + return this.adapter.currentUser; + } + + public get info() { + return this.adapter.info; + } + + public licenseIsAtLeast(type: LicenseType) { + return ( + LICENSES.indexOf(get(this.adapter.info, 'license.type', 'oss')) >= LICENSES.indexOf(type) + ); + } + + public currentUserHasOneOfRoles(roles: string[]) { + // If the user has at least one of the roles requested, the returnd difference will be less + // then the orig array size. difference only compares based on the left side arg + return difference(roles, get(this.currentUser, 'roles', [])).length < roles.length; + } +} diff --git a/x-pack/plugins/beats_management/public/lib/tags.ts b/x-pack/plugins/beats_management/public/lib/tags.ts index 86b21bca24310..82feb2093eda4 100644 --- a/x-pack/plugins/beats_management/public/lib/tags.ts +++ b/x-pack/plugins/beats_management/public/lib/tags.ts @@ -20,8 +20,10 @@ export class TagsLib { public async delete(tagIds: string[]): Promise { return await this.adapter.delete(tagIds); } - public async getAll(): Promise { - return this.jsonConfigToUserYaml(await this.adapter.getAll()); + + // FIXME: This needs to be paginated https://github.com/elastic/kibana/issues/26022 + public async getAll(ESQuery?: string): Promise { + return this.jsonConfigToUserYaml(await this.adapter.getAll(ESQuery)); } public async upsertTag(tag: BeatTag): Promise { tag.id = tag.id.replace(' ', '-'); diff --git a/x-pack/plugins/beats_management/public/lib/lib.ts b/x-pack/plugins/beats_management/public/lib/types.ts similarity index 73% rename from x-pack/plugins/beats_management/public/lib/lib.ts rename to x-pack/plugins/beats_management/public/lib/types.ts index 23e4da5c6336e..c8ced7d26029a 100644 --- a/x-pack/plugins/beats_management/public/lib/lib.ts +++ b/x-pack/plugins/beats_management/public/lib/types.ts @@ -6,10 +6,11 @@ import { IModule, IScope } from 'angular'; import { AxiosRequestConfig } from 'axios'; -import React from 'react'; +import { FrameworkAdapter } from './adapters/framework/adapter_types'; import { CMTokensAdapter } from './adapters/tokens/adapter_types'; import { BeatsLib } from './beats'; import { ElasticsearchLib } from './elasticsearch'; +import { FrameworkLib } from './framework'; import { TagsLib } from './tags'; export interface FrontendDomainLibs { @@ -20,7 +21,7 @@ export interface FrontendDomainLibs { export interface FrontendLibs extends FrontendDomainLibs { elasticsearch: ElasticsearchLib; - framework: FrameworkAdapter; + framework: FrameworkLib; } export interface YamlConfigSchema { @@ -39,35 +40,11 @@ export interface YamlConfigSchema { parseValidResult?: (value: any) => any; } -export interface FrameworkAdapter { - // Instance vars - appState?: object; - kbnVersion?: string; - baseURLPath: string; - registerManagementSection(pluginId: string, displayName: string, basePath: string): void; - getDefaultUserRoles(): string[]; - // Methods - getCurrentUser(): { - email: string | null; - enabled: boolean; - full_name: string | null; - metadata: { _reserved: true }; - roles: string[]; - scope: string[]; - username: string; - }; - licenseExpired(): boolean; - securityEnabled(): boolean; - hasValidLicense(): boolean; - setUISettings(key: string, value: any): void; - render(component: React.ReactElement): void; -} - export interface FramworkAdapterConstructable { new (uiModule: IModule): FrameworkAdapter; } -// TODO: replace AxiosRequestConfig with something more defined +// FIXME: replace AxiosRequestConfig with something more defined export type RequestConfig = AxiosRequestConfig; export interface ApiAdapter { diff --git a/x-pack/plugins/beats_management/public/pages/404.tsx b/x-pack/plugins/beats_management/public/pages/__404.tsx similarity index 100% rename from x-pack/plugins/beats_management/public/pages/404.tsx rename to x-pack/plugins/beats_management/public/pages/__404.tsx diff --git a/x-pack/plugins/beats_management/public/pages/beat/action_section.tsx b/x-pack/plugins/beats_management/public/pages/beat/action_section.tsx deleted file mode 100644 index f1471cd8b76ae..0000000000000 --- a/x-pack/plugins/beats_management/public/pages/beat/action_section.tsx +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { EuiFlexGroup, EuiFlexItem, EuiText } from '@elastic/eui'; -import { FormattedMessage } from '@kbn/i18n/react'; -import { first, sortByOrder } from 'lodash'; -import moment from 'moment'; -import React from 'react'; -import { CMPopulatedBeat } from '../../../common/domain_types'; - -interface BeatDetailsActionSectionProps { - beat: CMPopulatedBeat | undefined; -} - -export const BeatDetailsActionSection = ({ beat }: BeatDetailsActionSectionProps) => ( -
- {beat ? ( - - - - {beat.type} }} - /> - - - - - {beat.version} }} - /> - - - {/* TODO: We need a populated field before we can run this code - - - Uptime: 12min. - - */} - {beat.full_tags && - beat.full_tags.length > 0 && ( - - - - {moment( - first(sortByOrder(beat.full_tags, 'last_updated')).last_updated - ).fromNow()} - - ), - }} - /> - - - )} - - ) : ( -
- -
- )} -
-); diff --git a/x-pack/plugins/beats_management/public/pages/beat/activity.tsx b/x-pack/plugins/beats_management/public/pages/beat/activity.tsx deleted file mode 100644 index 6a031ef195200..0000000000000 --- a/x-pack/plugins/beats_management/public/pages/beat/activity.tsx +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { FormattedMessage } from '@kbn/i18n/react'; -import React from 'react'; -import { FrontendLibs } from '../../lib/lib'; - -interface BeatActivityPageProps { - libs: FrontendLibs; -} - -export const BeatActivityPage = (props: BeatActivityPageProps) => ( -
- -
-); diff --git a/x-pack/plugins/beats_management/public/pages/beat/detail.tsx b/x-pack/plugins/beats_management/public/pages/beat/details.tsx similarity index 88% rename from x-pack/plugins/beats_management/public/pages/beat/detail.tsx rename to x-pack/plugins/beats_management/public/pages/beat/details.tsx index 6eee9ce738703..0a5d17d84e0f2 100644 --- a/x-pack/plugins/beats_management/public/pages/beat/detail.tsx +++ b/x-pack/plugins/beats_management/public/pages/beat/details.tsx @@ -10,21 +10,24 @@ import { // @ts-ignore EuiInMemoryTable typings not yet available EuiInMemoryTable, EuiLink, + EuiSpacer, EuiText, EuiTitle, } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; import { FormattedMessage, InjectedIntl, injectI18n } from '@kbn/i18n/react'; import { flatten, get } from 'lodash'; import React from 'react'; import { TABLE_CONFIG } from '../../../common/constants'; import { BeatTag, CMPopulatedBeat, ConfigurationBlock } from '../../../common/domain_types'; -import { ConnectedLink } from '../../components/connected_link'; +import { Breadcrumb } from '../../components/navigation/breadcrumb'; +import { ConnectedLink } from '../../components/navigation/connected_link'; import { TagBadge } from '../../components/tag'; import { ConfigView } from '../../components/tag/config_view/index'; import { getSupportedConfig } from '../../config_schemas_translations_map'; interface PageProps { - beat: CMPopulatedBeat | undefined; + beat: CMPopulatedBeat; intl: InjectedIntl; } @@ -45,12 +48,10 @@ class BeatDetailPageUi extends React.PureComponent { const { beat, intl } = props; if (!beat) { return ( -
- -
+ ); } const configurationBlocks = flatten( @@ -126,6 +127,14 @@ class BeatDetailPageUi extends React.PureComponent { ]; return ( + + diff --git a/x-pack/plugins/beats_management/public/pages/beat/index.tsx b/x-pack/plugins/beats_management/public/pages/beat/index.tsx index f33d926d68a10..a9d77b3a104c2 100644 --- a/x-pack/plugins/beats_management/public/pages/beat/index.tsx +++ b/x-pack/plugins/beats_management/public/pages/beat/index.tsx @@ -5,53 +5,40 @@ */ import { - EuiSpacer, - // @ts-ignore types for EuiTab not currently available + EuiFlexGroup, + EuiFlexItem, + // @ts-ignore EuiTab, - // @ts-ignore types for EuiTabs not currently available + // @ts-ignore EuiTabs, + EuiText, } from '@elastic/eui'; -import { InjectedIntl, injectI18n } from '@kbn/i18n/react'; +import { FormattedMessage, InjectedIntl, injectI18n } from '@kbn/i18n/react'; +import { first, sortByOrder } from 'lodash'; +import moment from 'moment'; import React from 'react'; -import { Route, Switch } from 'react-router-dom'; +import { Redirect, Route, Switch } from 'react-router-dom'; import { CMPopulatedBeat } from '../../../common/domain_types'; -import { AppURLState } from '../../app'; import { PrimaryLayout } from '../../components/layouts/primary'; -import { URLStateProps, withUrlState } from '../../containers/with_url_state'; -import { FrontendLibs } from '../../lib/lib'; -import { BeatDetailsActionSection } from './action_section'; -import { BeatActivityPage } from './activity'; -import { BeatDetailPage } from './detail'; -import { BeatTagsPage } from './tags'; +import { Breadcrumb } from '../../components/navigation/breadcrumb'; +import { ChildRoutes } from '../../components/navigation/child_routes'; +import { AppPageProps } from '../../frontend_types'; -interface Match { - params: any; -} - -interface BeatDetailsPageProps extends URLStateProps { - location: any; - history: any; - libs: FrontendLibs; - match: Match; +interface PageProps extends AppPageProps { intl: InjectedIntl; } - -interface BeatDetailsPageState { +interface PageState { beat: CMPopulatedBeat | undefined; beatId: string; isLoading: boolean; } -class BeatDetailsPageComponent extends React.PureComponent< - BeatDetailsPageProps, - BeatDetailsPageState -> { - constructor(props: BeatDetailsPageProps) { +class BeatDetailsPageComponent extends React.PureComponent { + constructor(props: PageProps) { super(props); - this.state = { beat: undefined, - beatId: this.props.match.params.beatId, + beatId: props.match.params.beatId, isLoading: true, }; this.loadBeat(); @@ -64,16 +51,67 @@ class BeatDetailsPageComponent extends React.PureComponent< }); }; + public renderActionSection(beat?: CMPopulatedBeat) { + return beat ? ( + + + + {beat.type} }} + /> + + + + + {beat.version} }} + /> + + + {beat.full_tags && + beat.full_tags.length > 0 && ( + + + + {moment( + first(sortByOrder(beat.full_tags, 'last_updated')).last_updated + ).fromNow()} + + ), + }} + /> + + + )} + + ) : ( + + ); + } + public render() { const { intl } = this.props; const { beat } = this.state; - let id; + let id: string | undefined; let name; if (beat) { id = beat.id; name = beat.name; } + const title = this.state.isLoading ? intl.formatMessage({ id: 'xpack.beatsManagement.beat.loadingTitle', @@ -95,77 +133,57 @@ class BeatDetailsPageComponent extends React.PureComponent< } ); - const tabs = [ - { - id: `/beat/${id}`, - name: intl.formatMessage({ - id: 'xpack.beatsManagement.beat.configTabLabel', - defaultMessage: 'Config', - }), - disabled: false, - }, - // { - // id: `/beat/${id}/activity`, - // name: 'Beat Activity', - // disabled: false, - // }, - { - id: `/beat/${id}/tags`, - name: intl.formatMessage({ - id: 'xpack.beatsManagement.beat.configurationTagsTabLabel', - defaultMessage: 'Configuration Tags', - }), - disabled: false, - }, - ]; - return ( - }> - - {tabs.map((tab, index) => ( + + + + { - this.props.history.push({ - pathname: tab.id, - search: this.props.location.search, - }); - }} + isSelected={`/beat/${id}/details` === this.props.history.location.pathname} + onClick={this.onTabClicked(`/beat/${id}/details`)} > - {tab.name} + + + + - ))} - - - - } - /> - ( - this.loadBeat()} - {...props} + + {!this.state.beat &&
Beat not found
} + {this.state.beat && ( + + - )} - /> - ( - - )} - /> - + {id && } />} + + )} +
); } + private onTabClicked = (path: string) => { + return () => { + this.props.goTo(path); + }; + }; + private async loadBeat() { const { intl } = this.props; const { beatId } = this.props.match.params; @@ -186,6 +204,5 @@ class BeatDetailsPageComponent extends React.PureComponent< this.setState({ beat, isLoading: false }); } } -const BeatDetailsPageUi = withUrlState(BeatDetailsPageComponent); -export const BeatDetailsPage = injectI18n(BeatDetailsPageUi); +export const BeatDetailsPage = injectI18n(BeatDetailsPageComponent); diff --git a/x-pack/plugins/beats_management/public/pages/beat/tags.tsx b/x-pack/plugins/beats_management/public/pages/beat/tags.tsx index 9d0a693e8efa7..a6c7c01ee469d 100644 --- a/x-pack/plugins/beats_management/public/pages/beat/tags.tsx +++ b/x-pack/plugins/beats_management/public/pages/beat/tags.tsx @@ -5,19 +5,20 @@ */ import { EuiGlobalToastList } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; import React from 'react'; import { CMPopulatedBeat } from '../../../common/domain_types'; +import { Breadcrumb } from '../../components/navigation/breadcrumb'; import { BeatDetailTagsTable, Table } from '../../components/table'; -import { FrontendLibs } from '../../lib/lib'; +import { FrontendLibs } from '../../lib/types'; interface BeatTagsPageProps { - beatId: string; + beat: CMPopulatedBeat; libs: FrontendLibs; refreshBeat(): void; } interface BeatTagsPageState { - beat: CMPopulatedBeat | null; notifications: any[]; } @@ -27,19 +28,21 @@ export class BeatTagsPage extends React.PureComponent + + this.setState({ notifications: [] })} toastLifeTimeMs={5000} /> - + ); } - - private getBeat = async () => { - try { - const beat = await this.props.libs.beats.get(this.props.beatId); - this.setState({ beat }); - } catch (e) { - throw new Error(e); - } - }; } diff --git a/x-pack/plugins/beats_management/public/pages/enforce_security.tsx b/x-pack/plugins/beats_management/public/pages/error/enforce_security.tsx similarity index 92% rename from x-pack/plugins/beats_management/public/pages/enforce_security.tsx rename to x-pack/plugins/beats_management/public/pages/error/enforce_security.tsx index a79f828a28fb3..aab2a965fd04d 100644 --- a/x-pack/plugins/beats_management/public/pages/enforce_security.tsx +++ b/x-pack/plugins/beats_management/public/pages/error/enforce_security.tsx @@ -6,7 +6,7 @@ import { FormattedMessage, injectI18n } from '@kbn/i18n/react'; import * as React from 'react'; -import { NoDataLayout } from '../components/layouts/no_data'; +import { NoDataLayout } from '../../components/layouts/no_data'; export const EnforceSecurityPage = injectI18n(({ intl }) => ( ( ( - - - ); - } -} diff --git a/x-pack/plugins/beats_management/public/pages/main/index.tsx b/x-pack/plugins/beats_management/public/pages/main/index.tsx deleted file mode 100644 index bc9b9922f6502..0000000000000 --- a/x-pack/plugins/beats_management/public/pages/main/index.tsx +++ /dev/null @@ -1,304 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { - // @ts-ignore - EuiTab, - // @ts-ignore - EuiTabs, -} from '@elastic/eui'; -import { EuiButton } from '@elastic/eui'; -import { FormattedMessage, InjectedIntl, injectI18n } from '@kbn/i18n/react'; -import React from 'react'; -import { Redirect, Route, Switch } from 'react-router-dom'; -import { CMPopulatedBeat } from '../../../common/domain_types'; -import { AppURLState } from '../../app'; -import { ConnectedLink } from '../../components/connected_link'; -import { NoDataLayout } from '../../components/layouts/no_data'; -import { PrimaryLayout } from '../../components/layouts/primary'; -import { WalkthroughLayout } from '../../components/layouts/walkthrough'; -import { RouteWithBreadcrumb } from '../../components/route_with_breadcrumb'; -import { URLStateProps, withUrlState } from '../../containers/with_url_state'; -import { FrontendLibs } from '../../lib/lib'; -import { ActivityPage } from './activity'; -import { BeatsPage } from './beats'; -import { CreateTagPageFragment } from './create_tag_fragment'; -import { EnrollBeatPage } from './enroll_fragment'; -import { FinishWalkthroughPage } from './finish_walkthrough'; -import { TagsPage } from './tags'; - -interface MainPagesProps extends URLStateProps { - libs: FrontendLibs; - location: any; - intl: InjectedIntl; -} - -interface MainPagesState { - enrollBeat?: { - enrollmentToken: string; - } | null; - beats: CMPopulatedBeat[]; - unfilteredBeats: CMPopulatedBeat[]; - loadedBeatsAtLeastOnce: boolean; -} - -class MainPagesComponent extends React.PureComponent { - private mounted: boolean = false; - - constructor(props: MainPagesProps) { - super(props); - this.state = { - loadedBeatsAtLeastOnce: false, - beats: [], - unfilteredBeats: [], - }; - } - public onSelectedTabChanged = (id: string) => { - this.props.goTo(id); - }; - - public componentDidMount() { - this.mounted = true; - this.loadBeats(); - } - - public componentWillUnmount() { - this.mounted = false; - } - - public render() { - const { intl } = this.props; - if ( - this.state.loadedBeatsAtLeastOnce && - this.state.unfilteredBeats.length === 0 && - !this.props.location.pathname.includes('/overview/initial') - ) { - return ; - } - const tabs = [ - { - id: '/overview/beats', - name: ( - - ), - disabled: false, - }, - // { - // id: '/overview/activity', - // name: 'Beats Activity', - // disabled: false, - // }, - { - id: '/overview/tags', - name: ( - - ), - disabled: false, - }, - ]; - - const walkthroughSteps = [ - { - id: '/overview/initial/beats', - name: intl.formatMessage({ - id: 'xpack.beatsManagement.enrollBeat.enrollBeatStepLabel', - defaultMessage: 'Enroll Beat', - }), - disabled: false, - page: EnrollBeatPage, - }, - { - id: '/overview/initial/tag', - name: intl.formatMessage({ - id: 'xpack.beatsManagement.enrollBeat.createTagStepLabel', - defaultMessage: 'Create tag', - }), - disabled: false, - page: CreateTagPageFragment, - }, - { - id: '/overview/initial/finish', - name: intl.formatMessage({ - id: 'xpack.beatsManagement.enrollBeat.finishStepLabel', - defaultMessage: 'Finish', - }), - disabled: false, - page: FinishWalkthroughPage, - }, - ]; - - if (this.props.location.pathname === '/overview/initial/help') { - return ( - - - - - - } - > -

- -

-
- ); - } - - if (this.props.location.pathname.includes('/overview/initial')) { - return ( - - - {walkthroughSteps.map(step => ( - ( - - )} - /> - ))} - - - ); - } - - const renderedTabs = tabs.map((tab, index) => ( - this.onSelectedTabChanged(tab.id)} - isSelected={tab.id === this.props.location.pathname} - disabled={tab.disabled} - key={index} - > - {tab.name} - - )); - - return ( - - ( - - )} - /> - ( - - )} - /> - - } - > - {renderedTabs} - - ( - - )} - /> - ( - - )} - /> - } - /> - - ); - } - - private loadBeats = async () => { - let query; - if (this.props.urlState.beatsKBar) { - query = await this.props.libs.elasticsearch.convertKueryToEsQuery( - this.props.urlState.beatsKBar - ); - } - - let beats: CMPopulatedBeat[]; - let unfilteredBeats: CMPopulatedBeat[]; - try { - [beats, unfilteredBeats] = await Promise.all([ - this.props.libs.beats.getAll(query), - this.props.libs.beats.getAll(), - ]); - } catch (e) { - beats = []; - unfilteredBeats = []; - } - if (this.mounted) { - this.setState({ - loadedBeatsAtLeastOnce: true, - beats, - unfilteredBeats, - }); - } - }; -} - -const MainPagesUi = withUrlState(MainPagesComponent); - -export const MainPages = injectI18n(MainPagesUi); diff --git a/x-pack/plugins/beats_management/public/pages/main/tags.tsx b/x-pack/plugins/beats_management/public/pages/main/tags.tsx deleted file mode 100644 index ec2171c1104b1..0000000000000 --- a/x-pack/plugins/beats_management/public/pages/main/tags.tsx +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { EuiButton } from '@elastic/eui'; -import { FormattedMessage, InjectedIntl, injectI18n } from '@kbn/i18n/react'; -import React from 'react'; -import { BeatTag } from '../../../common/domain_types'; -import { AppURLState } from '../../app'; -import { AssignmentActionType, Table, TagsTableType } from '../../components/table'; -import { tagListAssignmentOptions } from '../../components/table/assignment_schema'; -import { WithKueryAutocompletion } from '../../containers/with_kuery_autocompletion'; -import { URLStateProps } from '../../containers/with_url_state'; -import { FrontendLibs } from '../../lib/lib'; - -interface TagsPageProps extends URLStateProps { - libs: FrontendLibs; - intl: InjectedIntl; -} - -interface TagsPageState { - tags: BeatTag[]; - tableRef: any; -} - -class TagsPageUi extends React.PureComponent { - public static ActionArea = ({ goTo }: TagsPageProps) => ( - { - goTo('/tag/create'); - }} - > - - - ); - - constructor(props: TagsPageProps) { - super(props); - - this.state = { - tags: [], - tableRef: React.createRef(), - }; - - this.loadTags(); - } - - public render() { - return ( - - {autocompleteProps => ( -
this.props.setUrlState({ tagsKBar: value }), - onSubmit: () => null, // todo - value: this.props.urlState.tagsKBar || '', - }} - assignmentOptions={{ - schema: tagListAssignmentOptions, - type: 'primary', - items: [], - actionHandler: this.handleTagsAction, - }} - ref={this.state.tableRef} - items={this.state.tags} - type={TagsTableType} - /> - )} - - ); - } - - private handleTagsAction = async (action: AssignmentActionType, payload: any) => { - const { intl } = this.props; - switch (action) { - case AssignmentActionType.Delete: - const tags = this.getSelectedTags().map((tag: BeatTag) => tag.id); - const success = await this.props.libs.tags.delete(tags); - if (!success) { - alert( - intl.formatMessage({ - id: 'xpack.beatsManagement.tags.someTagsMightBeAssignedToBeatsTitle', - defaultMessage: - 'Some of these tags might be assigned to beats. Please ensure tags being removed are not activly assigned', - }) - ); - } else { - this.loadTags(); - if (this.state.tableRef && this.state.tableRef.current) { - this.state.tableRef.current.resetSelection(); - } - } - break; - } - - this.loadTags(); - }; - - private getSelectedTags = () => { - return this.state.tableRef.current ? this.state.tableRef.current.state.selection : []; - }; - - private async loadTags() { - const tags = await this.props.libs.tags.getAll(); - this.setState({ - tags, - }); - } -} - -const TagsPageWrapped = injectI18n(TagsPageUi); -export const TagsPage = TagsPageWrapped as typeof TagsPageWrapped & { - ActionArea: typeof TagsPageUi['ActionArea']; -}; diff --git a/x-pack/plugins/beats_management/public/pages/overview/configuration_tags.tsx b/x-pack/plugins/beats_management/public/pages/overview/configuration_tags.tsx new file mode 100644 index 0000000000000..ce5328a219ce1 --- /dev/null +++ b/x-pack/plugins/beats_management/public/pages/overview/configuration_tags.tsx @@ -0,0 +1,126 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { EuiButton } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage, InjectedIntl, injectI18n } from '@kbn/i18n/react'; +import React from 'react'; +import { BeatTag } from '../../../common/domain_types'; +import { Breadcrumb } from '../../components/navigation/breadcrumb'; +import { AssignmentActionType, Table, TagsTableType } from '../../components/table'; +import { tagListAssignmentOptions } from '../../components/table/assignment_schema'; +import { WithKueryAutocompletion } from '../../containers/with_kuery_autocompletion'; +import { AppPageProps } from '../../frontend_types'; + +interface PageProps extends AppPageProps { + renderAction: (area: () => JSX.Element) => void; + intl: InjectedIntl; +} + +interface PageState { + tableRef: any; +} + +class TagsPageComponent extends React.PureComponent { + constructor(props: PageProps) { + super(props); + + this.state = { + tableRef: React.createRef(), + }; + + if (props.urlState.tagsKBar) { + props.containers.tags.reload(props.urlState.tagsKBar); + } + + props.renderAction(this.renderActionArea); + } + + public renderActionArea = () => ( + { + this.props.goTo('/tag/create'); + }} + > + + + ); + + public render() { + return ( + + + + {autocompleteProps => ( +
{ + this.props.setUrlState({ tagsKBar: value }); + this.props.containers.tags.reload(this.props.urlState.tagsKBar); + }, + onSubmit: () => null, // todo + value: this.props.urlState.tagsKBar || '', + }} + assignmentOptions={{ + schema: tagListAssignmentOptions, + type: 'primary', + items: [], + actionHandler: this.handleTagsAction, + }} + ref={this.state.tableRef} + items={this.props.containers.tags.state.list} + type={TagsTableType} + /> + )} + + + ); + } + + private handleTagsAction = async (action: AssignmentActionType) => { + const { intl } = this.props; + switch (action) { + case AssignmentActionType.Delete: + const tags = this.getSelectedTags().map((tag: BeatTag) => tag.id); + const success = await this.props.containers.tags.delete(tags); + if (!success) { + alert( + intl.formatMessage({ + id: 'xpack.beatsManagement.tags.someTagsMightBeAssignedToBeatsTitle', + defaultMessage: + 'Some of these tags might be assigned to beats. Please ensure tags being removed are not activly assigned', + }) + ); + } else { + if (this.state.tableRef && this.state.tableRef.current) { + this.state.tableRef.current.resetSelection(); + } + } + break; + } + }; + + private getSelectedTags = () => { + return this.state.tableRef.current ? this.state.tableRef.current.state.selection : []; + }; +} + +export const TagsPage = injectI18n(TagsPageComponent); diff --git a/x-pack/plugins/beats_management/public/pages/main/beats.tsx b/x-pack/plugins/beats_management/public/pages/overview/enrolled_beats.tsx similarity index 57% rename from x-pack/plugins/beats_management/public/pages/main/beats.tsx rename to x-pack/plugins/beats_management/public/pages/overview/enrolled_beats.tsx index c6c24542b6e4c..8d1ce681132d3 100644 --- a/x-pack/plugins/beats_management/public/pages/main/beats.tsx +++ b/x-pack/plugins/beats_management/public/pages/overview/enrolled_beats.tsx @@ -14,43 +14,48 @@ import { EuiModalHeaderTitle, EuiOverlayMask, } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; import { FormattedMessage, InjectedIntl, injectI18n } from '@kbn/i18n/react'; import { flatten, intersection, sortBy } from 'lodash'; import moment from 'moment'; import React from 'react'; -import { RouteComponentProps } from 'react-router'; import { UNIQUENESS_ENFORCING_TYPES } from 'x-pack/plugins/beats_management/common/constants'; import { BeatTag, CMPopulatedBeat, ConfigurationBlock } from '../../../common/domain_types'; -import { BeatsTagAssignment } from '../../../server/lib/adapters/beats/adapter_types'; -import { AppURLState } from '../../app'; +import { EnrollBeat } from '../../components/enroll_beats'; +import { Breadcrumb } from '../../components/navigation/breadcrumb'; import { BeatsTableType, Table } from '../../components/table'; import { beatsListAssignmentOptions } from '../../components/table/assignment_schema'; import { AssignmentActionType } from '../../components/table/table'; import { WithKueryAutocompletion } from '../../containers/with_kuery_autocompletion'; -import { URLStateProps } from '../../containers/with_url_state'; -import { FrontendLibs } from '../../lib/lib'; -import { EnrollBeatPage } from './enroll_fragment'; +import { AppPageProps } from '../../frontend_types'; -interface BeatsPageProps extends URLStateProps { +interface PageProps extends AppPageProps { + renderAction: (area: () => JSX.Element) => void; intl: InjectedIntl; - libs: FrontendLibs; - location: any; - beats: CMPopulatedBeat[]; - loadBeats: () => any; } -interface BeatsPageState { +interface PageState { notifications: any[]; - tableRef: any; - tags: any[] | null; + tags: BeatTag[] | null; } -interface ActionAreaProps extends URLStateProps, RouteComponentProps { - libs: FrontendLibs; -} +class BeatsPageComponent extends React.PureComponent { + private tableRef: React.RefObject = React.createRef(); + constructor(props: PageProps) { + super(props); + + this.state = { + notifications: [], + tags: null, + }; -class BeatsPageUi extends React.PureComponent { - public static ActionArea = (props: ActionAreaProps) => ( + if (props.urlState.beatsKBar) { + props.containers.beats.reload(props.urlState.beatsKBar); + } + props.renderAction(this.renderActionArea); + } + + public renderActionArea = () => ( { @@ -71,7 +76,7 @@ class BeatsPageUi extends React.PureComponent { size="s" color="primary" onClick={async () => { - props.goTo(`/overview/beats/enroll`); + this.props.goTo(`/overview/enrolled_beats/enroll`); }} > { /> - {props.location.pathname === '/overview/beats/enroll' && ( + {this.props.location.pathname === '/overview/enrolled_beats/enroll' && ( { - props.goTo(`/overview/beats`); + this.props.setUrlState({ + enrollmentToken: '', + }); + this.props.goTo(`/overview/enrolled_beats`); }} style={{ width: '640px' }} > @@ -97,31 +105,52 @@ class BeatsPageUi extends React.PureComponent { - + { + const enrollmentToken = await this.props.libs.tokens.createEnrollmentToken(); + this.props.setUrlState({ + enrollmentToken, + }); + }} + onBeatEnrolled={() => { + this.props.setUrlState({ + enrollmentToken: '', + }); + }} + /> + {!this.props.urlState.enrollmentToken && ( + + { + this.props.goTo('/overview/enrolled_beats'); + }} + > + Done + + + )} )} ); - constructor(props: BeatsPageProps) { - super(props); - - this.state = { - notifications: [], - tableRef: React.createRef(), - tags: null, - }; - } - public componentDidUpdate(prevProps: any) { - if (this.props.location !== prevProps.location) { - this.props.loadBeats(); - } - } public render() { return ( -
+ + {autocompleteProps => (
{ isValid: this.props.libs.elasticsearch.isKueryValid( this.props.urlState.beatsKBar || '' ), // todo check if query converts to es query correctly - onChange: (value: any) => this.props.setUrlState({ beatsKBar: value }), // todo + onChange: (value: any) => { + this.props.setUrlState({ beatsKBar: value }); + this.props.containers.beats.reload(this.props.urlState.beatsKBar); + }, // todo onSubmit: () => null, // todo value: this.props.urlState.beatsKBar || '', }} assignmentOptions={{ - items: this.filterSelectedBeatTags(), + items: this.filterTags(this.props.containers.tags.state.list), schema: beatsListAssignmentOptions, type: 'assignment', - actionHandler: this.handleBeatsActions, + actionHandler: async (action: AssignmentActionType, payload: any) => { + switch (action) { + case AssignmentActionType.Assign: + const status = await this.props.containers.beats.toggleTagAssignment( + payload, + this.getSelectedBeats() + ); + this.notifyUpdatedTagAssociation(status, this.getSelectedBeats(), payload); + break; + case AssignmentActionType.Delete: + this.props.containers.beats.deactivate(this.getSelectedBeats()); + this.notifyBeatDisenrolled(this.getSelectedBeats()); + break; + case AssignmentActionType.Reload: + this.props.containers.tags.reload(); + break; + } + }, }} - items={sortBy(this.props.beats, 'id') || []} - ref={this.state.tableRef} + items={sortBy(this.props.containers.beats.state.list, 'id') || []} + ref={this.tableRef} type={BeatsTableType} /> )} @@ -152,84 +201,11 @@ class BeatsPageUi extends React.PureComponent { dismissToast={() => this.setState({ notifications: [] })} toastLifeTimeMs={5000} /> - + ); } - private handleBeatsActions = (action: AssignmentActionType, payload: any) => { - switch (action) { - case AssignmentActionType.Assign: - this.handleBeatTagAssignment(payload); - break; - case AssignmentActionType.Edit: - // TODO: navigate to edit page - break; - case AssignmentActionType.Delete: - this.deleteSelected(); - break; - case AssignmentActionType.Reload: - this.loadTags(); - break; - } - - this.props.loadBeats(); - }; - - private handleBeatTagAssignment = async (tagId: string) => { - const selected = this.getSelectedBeats(); - if (selected.some(beat => beat.full_tags.some(({ id }) => id === tagId))) { - await this.removeTagsFromBeats(selected, tagId); - } else { - await this.assignTagsToBeats(selected, tagId); - } - }; - - private deleteSelected = async () => { - const selected = this.getSelectedBeats(); - for (const beat of selected) { - await this.props.libs.beats.update(beat.id, { active: false }); - } - - this.notifyBeatUnenrolled(selected); - - // because the compile code above has a very minor race condition, we wait, - // the max race condition time is really 10ms but doing 100 to be safe - setTimeout(async () => { - await this.props.loadBeats(); - }, 100); - }; - - private loadTags = async () => { - const tags = await this.props.libs.tags.getAll(); - this.setState({ - tags, - }); - }; - - private createBeatTagAssignments = ( - beats: CMPopulatedBeat[], - tagId: string - ): BeatsTagAssignment[] => beats.map(({ id }) => ({ beatId: id, tag: tagId })); - - private removeTagsFromBeats = async (beats: CMPopulatedBeat[], tagId: string) => { - if (beats.length) { - const assignments = this.createBeatTagAssignments(beats, tagId); - await this.props.libs.beats.removeTagsFromBeats(assignments); - await this.refreshData(); - this.notifyUpdatedTagAssociation('remove', assignments, tagId); - } - }; - - private assignTagsToBeats = async (beats: CMPopulatedBeat[], tagId: string) => { - if (beats.length) { - const assignments = this.createBeatTagAssignments(beats, tagId); - await this.props.libs.beats.assignTagsToBeats(assignments); - await this.refreshData(); - this.notifyUpdatedTagAssociation('add', assignments, tagId); - } - }; - - private notifyBeatUnenrolled = async (beats: CMPopulatedBeat[]) => { + private notifyBeatDisenrolled = async (beats: CMPopulatedBeat[]) => { const { intl } = this.props; let title; let text; @@ -237,7 +213,7 @@ class BeatsPageUi extends React.PureComponent { title = intl.formatMessage( { id: 'xpack.beatsManagement.beats.beatDisenrolledNotificationTitle', - defaultMessage: '{firstBeatNameOrId} unenrolled', + defaultMessage: '{firstBeatNameOrId} disenrolled', }, { firstBeatNameOrId: `"${beats[0].name || beats[0].id}"`, @@ -246,7 +222,7 @@ class BeatsPageUi extends React.PureComponent { text = intl.formatMessage( { id: 'xpack.beatsManagement.beats.beatDisenrolledNotificationDescription', - defaultMessage: 'Beat with ID {firstBeatId} was unenrolled.', + defaultMessage: 'Beat with ID {firstBeatId} was disenrolled.', }, { firstBeatId: `"${beats[0].id}"`, @@ -256,7 +232,7 @@ class BeatsPageUi extends React.PureComponent { title = intl.formatMessage( { id: 'xpack.beatsManagement.beats.disenrolledBeatsNotificationTitle', - defaultMessage: '{beatsLength} beats unenrolled', + defaultMessage: '{beatsLength} beats disenrolled', }, { beatsLength: beats.length, @@ -267,7 +243,7 @@ class BeatsPageUi extends React.PureComponent { this.setState({ notifications: this.state.notifications.concat({ color: 'warning', - id: `unenroll_${new Date()}`, + id: `disenroll_${new Date()}`, title, text, }), @@ -275,13 +251,13 @@ class BeatsPageUi extends React.PureComponent { }; private notifyUpdatedTagAssociation = ( - action: 'add' | 'remove', - assignments: BeatsTagAssignment[], + action: 'added' | 'removed', + beats: CMPopulatedBeat[], tag: string ) => { const { intl } = this.props; const notificationMessage = - action === 'remove' + action === 'removed' ? intl.formatMessage( { id: 'xpack.beatsManagement.beats.removedNotificationDescription', @@ -290,8 +266,8 @@ class BeatsPageUi extends React.PureComponent { }, { tag: `"${tag}"`, - assignmentsLength: assignments.length, - beatName: `"${this.getNameForBeatId(assignments[0].beatId)}"`, + assignmentsLength: beats.length, + beatName: `"${beats[0].name || beats[0].id}"`, } ) : intl.formatMessage( @@ -302,19 +278,19 @@ class BeatsPageUi extends React.PureComponent { }, { tag: `"${tag}"`, - assignmentsLength: assignments.length, - beatName: `"${this.getNameForBeatId(assignments[0].beatId)}"`, + assignmentsLength: beats.length, + beatName: `"${beats[0].name || beats[0].id}"`, } ); const notificationTitle = - action === 'remove' + action === 'removed' ? intl.formatMessage( { id: 'xpack.beatsManagement.beats.removedNotificationTitle', defaultMessage: '{assignmentsLength, plural, one {Tag} other {Tags}} removed', }, { - assignmentsLength: assignments.length, + assignmentsLength: beats.length, } ) : intl.formatMessage( @@ -323,9 +299,10 @@ class BeatsPageUi extends React.PureComponent { defaultMessage: '{assignmentsLength, plural, one {Tag} other {Tags}} added', }, { - assignmentsLength: assignments.length, + assignmentsLength: beats.length, } ); + this.setState({ notifications: this.state.notifications.concat({ color: 'success', @@ -336,25 +313,14 @@ class BeatsPageUi extends React.PureComponent { }); }; - private getNameForBeatId = (beatId: string) => { - const beat = this.props.beats.find(b => b.id === beatId); - if (beat) { - return beat.name; - } - return null; - }; - - private refreshData = async () => { - await this.loadTags(); - await this.props.loadBeats(); - this.state.tableRef.current.setSelection(this.getSelectedBeats()); - }; - private getSelectedBeats = (): CMPopulatedBeat[] => { - const selectedIds = this.state.tableRef.current.state.selection.map((beat: any) => beat.id); + if (!this.tableRef.current) { + return []; + } + const selectedIds = this.tableRef.current.state.selection.map((beat: any) => beat.id); const beats: CMPopulatedBeat[] = []; selectedIds.forEach((id: any) => { - const beat: CMPopulatedBeat | undefined = this.props.beats.find(b => b.id === id); + const beat = this.props.containers.beats.state.list.find(b => b.id === id); if (beat) { beats.push(beat); } @@ -362,13 +328,10 @@ class BeatsPageUi extends React.PureComponent { return beats; }; - private filterSelectedBeatTags = () => { - if (!this.state.tags) { - return []; - } + private filterTags = (tags: BeatTag[]) => { return this.selectedBeatConfigsRequireUniqueness() - ? this.state.tags.map(this.disableTagForUniquenessEnforcement) - : this.state.tags; + ? tags.map(this.disableTagForUniquenessEnforcement) + : tags; }; private configBlocksRequireUniqueness = (configurationBlocks: ConfigurationBlock[]) => @@ -391,7 +354,4 @@ class BeatsPageUi extends React.PureComponent { .reduce((acc, cur) => acc || cur, false); } -const BeatsPageWrapped = injectI18n(BeatsPageUi); -export const BeatsPage = BeatsPageWrapped as typeof BeatsPageWrapped & { - ActionArea: typeof BeatsPageUi['ActionArea']; -}; +export const BeatsPage = injectI18n(BeatsPageComponent); diff --git a/x-pack/plugins/beats_management/public/pages/overview/index.tsx b/x-pack/plugins/beats_management/public/pages/overview/index.tsx new file mode 100644 index 0000000000000..a50c3088bc929 --- /dev/null +++ b/x-pack/plugins/beats_management/public/pages/overview/index.tsx @@ -0,0 +1,91 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { + // @ts-ignore types for EuiTabs not currently available + EuiTab, + // @ts-ignore types for EuiTab not currently available + EuiTabs, +} from '@elastic/eui'; +import { FormattedMessage } from '@kbn/i18n/react'; +import React from 'react'; +import { Subscribe } from 'unstated'; +import { CMPopulatedBeat } from '../../../common/domain_types'; +import { PrimaryLayout } from '../../components/layouts/primary'; +import { ChildRoutes } from '../../components/navigation/child_routes'; +import { BeatsContainer } from '../../containers/beats'; +import { TagsContainer } from '../../containers/tags'; +import { withUrlState } from '../../containers/with_url_state'; +import { AppPageProps } from '../../frontend_types'; + +interface MainPagesState { + enrollBeat?: { + enrollmentToken: string; + } | null; + beats: CMPopulatedBeat[]; + loadedBeatsAtLeastOnce: boolean; +} + +class MainPageComponent extends React.PureComponent { + constructor(props: AppPageProps) { + super(props); + this.state = { + loadedBeatsAtLeastOnce: false, + beats: [], + }; + } + public onTabClicked = (path: string) => { + return () => { + this.props.goTo(path); + }; + }; + + public render() { + return ( + + {(renderAction: any) => ( + + {(beats: BeatsContainer, tags: TagsContainer) => ( + + + + + + + + + + + + )} + + )} + + ); + } +} + +export const MainPage = withUrlState(MainPageComponent); diff --git a/x-pack/plugins/beats_management/public/pages/tag/index.tsx b/x-pack/plugins/beats_management/public/pages/tag.tsx similarity index 78% rename from x-pack/plugins/beats_management/public/pages/tag/index.tsx rename to x-pack/plugins/beats_management/public/pages/tag.tsx index 88f909514763f..29eabe49dea55 100644 --- a/x-pack/plugins/beats_management/public/pages/tag/index.tsx +++ b/x-pack/plugins/beats_management/public/pages/tag.tsx @@ -4,35 +4,32 @@ * you may not use this file except in compliance with the Elastic License. */ -import 'brace/mode/yaml'; -import 'brace/theme/github'; - import { EuiButton, EuiButtonEmpty, EuiFlexGroup, EuiFlexItem, EuiSpacer } from '@elastic/eui'; -import * as euiVars from '@elastic/eui/dist/eui_theme_k6_light.json'; +import euiVars from '@elastic/eui/dist/eui_theme_k6_light.json'; import { FormattedMessage, InjectedIntl, injectI18n } from '@kbn/i18n/react'; +import 'brace/mode/yaml'; +import 'brace/theme/github'; import { sample } from 'lodash'; import React from 'react'; import { UNIQUENESS_ENFORCING_TYPES } from 'x-pack/plugins/beats_management/common/constants'; -import { BeatTag, CMPopulatedBeat } from '../../../common/domain_types'; -import { AppURLState } from '../../app'; -import { PrimaryLayout } from '../../components/layouts/primary'; -import { TagEdit } from '../../components/tag'; -import { URLStateProps, withUrlState } from '../../containers/with_url_state'; -import { FrontendLibs } from '../../lib/lib'; -interface TagPageProps extends URLStateProps { - libs: FrontendLibs; - match: any; - intl: InjectedIntl; -} +import { BeatTag, CMBeat, CMPopulatedBeat } from '../../common/domain_types'; +import { PrimaryLayout } from '../components/layouts/primary'; +import { TagEdit } from '../components/tag'; +import { AppPageProps } from '../frontend_types'; interface TagPageState { showFlyout: boolean; attachedBeats: CMPopulatedBeat[] | null; tag: BeatTag; } -export class TagPageComponent extends React.PureComponent { +class TagPageComponent extends React.PureComponent< + AppPageProps & { + intl: InjectedIntl; + }, + TagPageState +> { private mode: 'edit' | 'create' = 'create'; - constructor(props: TagPageProps) { + constructor(props: AppPageProps & { intl: InjectedIntl }) { super(props); const randomColor = sample( Object.keys(euiVars) @@ -82,21 +79,23 @@ export class TagPageComponent extends React.PureComponent { - await this.props.libs.beats.removeTagsFromBeats( - beatIds.map(id => { - return { beatId: id, tag: this.state.tag.id }; - }) - ); - await this.loadAttachedBeats(); - }} + onDetachBeat={ + this.mode === 'edit' + ? async (beatIds: string[]) => { + await this.props.containers.beats.removeTagsFromBeats( + beatIds, + this.state.tag.id + ); + await this.loadAttachedBeats(); + } + : undefined + } onTagChange={(field: string, value: string | number) => this.setState(oldState => ({ tag: { ...oldState.tag, [field]: value }, })) } - attachedBeats={this.state.attachedBeats} + attachedBeats={this.state.attachedBeats as CMBeat[]} /> @@ -117,7 +116,7 @@ export class TagPageComponent extends React.PureComponent - this.props.goTo('/overview/tags')}> + this.props.goTo('/overview/configuration_tags')}> { const tags = await this.props.libs.tags.getTagsWithIds([this.props.match.params.tagid]); if (tags.length === 0) { - // TODO do something to error + // TODO do something to error https://github.com/elastic/kibana/issues/26023 } this.setState({ tag: tags[0], @@ -159,13 +158,12 @@ export class TagPageComponent extends React.PureComponent { await this.props.libs.tags.upsertTag(this.state.tag as BeatTag); - this.props.goTo(`/overview/tags`); + this.props.goTo(`/overview/configuration_tags`); }; private getNumExclusiveConfigurationBlocks = () => this.state.tag.configuration_blocks .map(({ type }) => UNIQUENESS_ENFORCING_TYPES.some(uniqueType => uniqueType === type)) .reduce((acc, cur) => (cur ? acc + 1 : acc), 0); } -export const TagPageUi = withUrlState(TagPageComponent); -export const TagPage = injectI18n(TagPageUi); +export const TagPage = injectI18n(TagPageComponent); diff --git a/x-pack/plugins/beats_management/public/pages/walkthrough/initial/beat.tsx b/x-pack/plugins/beats_management/public/pages/walkthrough/initial/beat.tsx new file mode 100644 index 0000000000000..0ceed78fc3f21 --- /dev/null +++ b/x-pack/plugins/beats_management/public/pages/walkthrough/initial/beat.tsx @@ -0,0 +1,63 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { EuiButton } from '@elastic/eui'; +import React, { Component } from 'react'; +import { EnrollBeat } from '../../../components/enroll_beats'; +import { AppPageProps } from '../../../frontend_types'; + +interface ComponentState { + readyToContinue: boolean; +} + +export class BeatsInitialEnrollmentPage extends Component { + constructor(props: AppPageProps) { + super(props); + this.state = { + readyToContinue: false, + }; + } + + public onBeatEnrolled = () => { + this.setState({ + readyToContinue: true, + }); + }; + + public createEnrollmentToken = async () => { + const enrollmentToken = await this.props.libs.tokens.createEnrollmentToken(); + this.props.setUrlState({ + enrollmentToken, + }); + }; + + public render() { + return ( + + + {this.state.readyToContinue && ( + + { + this.props.goTo('/walkthrough/initial/tag'); + }} + > + Continue + + + )} + + ); + } +} diff --git a/x-pack/plugins/beats_management/public/pages/main/finish_walkthrough.tsx b/x-pack/plugins/beats_management/public/pages/walkthrough/initial/finish.tsx similarity index 74% rename from x-pack/plugins/beats_management/public/pages/main/finish_walkthrough.tsx rename to x-pack/plugins/beats_management/public/pages/walkthrough/initial/finish.tsx index b3f53dfb5a5c2..392ac808a9dbb 100644 --- a/x-pack/plugins/beats_management/public/pages/main/finish_walkthrough.tsx +++ b/x-pack/plugins/beats_management/public/pages/walkthrough/initial/finish.tsx @@ -6,19 +6,23 @@ import { EuiButton, EuiEmptyPrompt, EuiFlexGroup, EuiFlexItem, EuiPageContent } from '@elastic/eui'; import { FormattedMessage, InjectedIntl, injectI18n } from '@kbn/i18n/react'; import React from 'react'; -import { RouteComponentProps } from 'react-router'; -import { BeatTag, CMBeat } from '../../../common/domain_types'; -import { BeatsTagAssignment } from '../../../server/lib/adapters/beats/adapter_types'; -import { AppURLState } from '../../app'; -import { URLStateProps, withUrlState } from '../../containers/with_url_state'; -import { FrontendLibs } from '../../lib/lib'; -interface PageProps extends URLStateProps, RouteComponentProps { - loadBeats: any; - libs: FrontendLibs; - intl: InjectedIntl; +import { CMPopulatedBeat } from '../../../../common/domain_types'; +import { AppPageProps } from '../../../frontend_types'; + +interface PageState { + assigned: boolean; } -export class FinishWalkthrough extends React.Component { - constructor(props: PageProps) { +class FinishWalkthrough extends React.Component< + AppPageProps & { + intl: InjectedIntl; + }, + PageState +> { + constructor( + props: AppPageProps & { + intl: InjectedIntl; + } + ) { super(props); this.state = { @@ -28,8 +32,6 @@ export class FinishWalkthrough extends React.Component { public componentDidMount() { setTimeout(async () => { - await this.props.loadBeats(); - const done = await this.assignTagToBeat(); if (done) { @@ -72,7 +74,7 @@ export class FinishWalkthrough extends React.Component { fill disabled={!this.state.assigned} onClick={async () => { - goTo('/overview/beats'); + goTo('/overview/enrolled_beats'); }} > { ); } - private createBeatTagAssignments = (beats: CMBeat[], tag: BeatTag): BeatsTagAssignment[] => - beats.map(({ id }) => ({ beatId: id, tag: tag.id })); - private assignTagToBeat = async () => { const { intl } = this.props; if (!this.props.urlState.enrollmentToken) { @@ -119,10 +118,11 @@ export class FinishWalkthrough extends React.Component { }) ); } - const tags = await this.props.libs.tags.getTagsWithIds([this.props.urlState.createdTag]); - const assignments = this.createBeatTagAssignments([beat], tags[0]); - await this.props.libs.beats.assignTagsToBeats(assignments); + await this.props.containers.beats.assignTagsToBeats( + [beat as CMPopulatedBeat], + this.props.urlState.createdTag + ); this.props.setUrlState({ createdTag: '', enrollmentToken: '', @@ -131,6 +131,4 @@ export class FinishWalkthrough extends React.Component { }; } -const FinishWalkthroughPageUi = withUrlState(FinishWalkthrough); - -export const FinishWalkthroughPage = injectI18n(FinishWalkthroughPageUi); +export const FinishWalkthroughPage = injectI18n(FinishWalkthrough); diff --git a/x-pack/plugins/beats_management/public/pages/walkthrough/initial/index.tsx b/x-pack/plugins/beats_management/public/pages/walkthrough/initial/index.tsx new file mode 100644 index 0000000000000..faf8daafebfbd --- /dev/null +++ b/x-pack/plugins/beats_management/public/pages/walkthrough/initial/index.tsx @@ -0,0 +1,86 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { EuiButton } from '@elastic/eui'; +import { FormattedMessage, InjectedIntl, injectI18n } from '@kbn/i18n/react'; +import React, { Component } from 'react'; +import { NoDataLayout } from '../../../components/layouts/no_data'; +import { WalkthroughLayout } from '../../../components/layouts/walkthrough'; +import { ChildRoutes } from '../../../components/navigation/child_routes'; +import { ConnectedLink } from '../../../components/navigation/connected_link'; +import { AppPageProps } from '../../../frontend_types'; + +class InitialWalkthroughPageComponent extends Component< + AppPageProps & { + intl: InjectedIntl; + } +> { + public render() { + const { intl } = this.props; + + if (this.props.location.pathname === '/walkthrough/initial') { + return ( + + + {' '} + + + } + > +

+ +

+
+ ); + } + return ( + { + // FIXME implament goto + }} + activePath={this.props.location.pathname} + > + + + ); + } +} +export const InitialWalkthroughPage = injectI18n(InitialWalkthroughPageComponent); diff --git a/x-pack/plugins/beats_management/public/pages/main/create_tag_fragment.tsx b/x-pack/plugins/beats_management/public/pages/walkthrough/initial/tag.tsx similarity index 55% rename from x-pack/plugins/beats_management/public/pages/main/create_tag_fragment.tsx rename to x-pack/plugins/beats_management/public/pages/walkthrough/initial/tag.tsx index 6d649cb46b5b1..0e65e6a9e6083 100644 --- a/x-pack/plugins/beats_management/public/pages/main/create_tag_fragment.tsx +++ b/x-pack/plugins/beats_management/public/pages/walkthrough/initial/tag.tsx @@ -3,36 +3,22 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ +import { EuiButton, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; +import React, { Component } from 'react'; +import { BeatTag } from '../../../../common/domain_types'; +import { TagEdit } from '../../../components/tag/tag_edit'; +import { AppPageProps } from '../../../frontend_types'; -import { EuiButton, EuiFlexGroup, EuiFlexItem, EuiHorizontalRule, EuiSpacer } from '@elastic/eui'; -import { FormattedMessage, InjectedIntl, injectI18n } from '@kbn/i18n/react'; -import 'brace/mode/yaml'; - -import 'brace/theme/github'; -import React from 'react'; -import { BeatTag } from '../../../common/domain_types'; -import { AppURLState } from '../../app'; -import { TagEdit } from '../../components/tag'; -import { URLStateProps, withUrlState } from '../../containers/with_url_state'; -import { FrontendLibs } from '../../lib/lib'; - -interface TagPageProps extends URLStateProps { - libs: FrontendLibs; - match: any; - intl: InjectedIntl; -} - -interface TagPageState { - showFlyout: boolean; +interface PageState { tag: BeatTag; } -class CreateTagFragment extends React.PureComponent { - private mode: 'edit' | 'create' = 'create'; - constructor(props: TagPageProps) { +export class InitialTagPage extends Component { + constructor(props: AppPageProps) { super(props); this.state = { - showFlyout: false, tag: { id: props.urlState.createdTag ? props.urlState.createdTag : '', color: '#DD0A73', @@ -42,7 +28,6 @@ class CreateTagFragment extends React.PureComponent }; if (props.urlState.createdTag) { - this.mode = 'edit'; this.loadTag(); } } @@ -52,24 +37,12 @@ class CreateTagFragment extends React.PureComponent { - this.props.libs.beats.removeTagsFromBeats( - beatIds.map(id => { - return { beatId: id, tag: this.state.tag.id }; - }) - ); - }} onTagChange={(field: string, value: string | number) => this.setState(oldState => ({ tag: { ...oldState.tag, [field]: value }, })) } - attachedBeats={null} /> - - - }; private saveTag = async () => { - const { intl } = this.props; const newTag = await this.props.libs.tags.upsertTag(this.state.tag as BeatTag); if (!newTag) { return alert( - intl.formatMessage({ - id: 'xpack.beatsManagement.createTag.errorSavingTagTitle', + i18n.translate('xpack.beatsManagement.createTag.errorSavingTagTitle', { defaultMessage: 'error saving tag', }) ); @@ -115,9 +86,6 @@ class CreateTagFragment extends React.PureComponent this.props.setUrlState({ createdTag: newTag.id, }); - this.props.goTo(`/overview/initial/finish`); + this.props.goTo(`/walkthrough/initial/finish`); }; } -const CreateTagPageFragmentUi = withUrlState(CreateTagFragment); - -export const CreateTagPageFragment = injectI18n(CreateTagPageFragmentUi); diff --git a/x-pack/plugins/beats_management/public/router.tsx b/x-pack/plugins/beats_management/public/router.tsx index 1e1531d4d9269..febf5d73ed096 100644 --- a/x-pack/plugins/beats_management/public/router.tsx +++ b/x-pack/plugins/beats_management/public/router.tsx @@ -4,103 +4,135 @@ * you may not use this file except in compliance with the Elastic License. */ -import { i18n } from '@kbn/i18n'; -import React from 'react'; -import { HashRouter, Redirect, Route, Switch } from 'react-router-dom'; -import { Header } from './components/layouts/header'; -import { BreadcrumbConsumer, RouteWithBreadcrumb } from './components/route_with_breadcrumb'; -import { FrontendLibs } from './lib/lib'; -import { BeatDetailsPage } from './pages/beat'; -import { EnforceSecurityPage } from './pages/enforce_security'; -import { InvalidLicensePage } from './pages/invalid_license'; -import { MainPages } from './pages/main'; -import { NoAccessPage } from './pages/no_access'; -import { TagPage } from './pages/tag'; +import { get } from 'lodash'; +import React, { Component } from 'react'; +import { Redirect, Route, Switch } from 'react-router-dom'; +import { Loading } from './components/loading'; +import { ChildRoutes } from './components/navigation/child_routes'; +import { BeatsContainer } from './containers/beats'; +import { TagsContainer } from './containers/tags'; +import { URLStateProps, WithURLState } from './containers/with_url_state'; +import { FrontendLibs } from './lib/types'; +import { RouteTreeBuilder } from './utils/page_loader/page_loader'; -export const PageRouter: React.SFC<{ libs: FrontendLibs }> = ({ libs }) => { - return ( - -
- - {({ breadcrumbs }) => ( -
{ + constructor(props: RouterProps) { + super(props); + this.state = { + loadingStatus: 'loading', + }; + } + + public async componentWillMount() { + if (this.state.loadingStatus === 'loading') { + await this.props.beatsContainer.reload(); + await this.props.tagsContainer.reload(); + + const countOfEverything = + this.props.beatsContainer.state.list.length + this.props.tagsContainer.state.list.length; + + this.setState({ + loadingStatus: countOfEverything > 0 ? 'loaded' : 'loaded:empty', + }); + } + } + + public render() { + if (this.state.loadingStatus === 'loading') { + return ; + } + + return ( + + {/* Redirects mapping */} + + {/* License check (UI displays when license exists but is expired) */} + {get(this.props.libs.framework.info, 'license.expired', true) && ( + + !props.location.pathname.includes('/error') ? ( + + ) : null + } /> )} - - - {libs.framework.licenseExpired() && } />} - {!libs.framework.securityEnabled() && } />} - {!libs.framework.getCurrentUser() || - (!libs.framework.getCurrentUser().roles.includes('beats_admin') && - !libs.framework - .getDefaultUserRoles() - .some(r => libs.framework.getCurrentUser().roles.includes(r)) && ( - } /> - ))} - } - /> - } /> - { - return i18n.translate('xpack.beatsManagement.router.beatTitle', { - defaultMessage: 'Beats: {beatId}', - values: { beatId: params.beatId }, - }); - }} - parentBreadcrumbs={[ - { - text: i18n.translate('xpack.beatsManagement.router.beatsListTitle', { - defaultMessage: 'Beats List', - }), - href: '#/management/beats_management/overview/beats', - }, - ]} - path="/beat/:beatId" - render={(props: any) => } - /> - { - if (params.action === 'create') { - return i18n.translate('xpack.beatsManagement.router.createTagTitle', { - defaultMessage: 'Create Tag', - }); + + {/* Ensure security is eanabled for elastic and kibana */} + {!get(this.props.libs.framework.info, 'security.enabled', true) && ( + + !props.location.pathname.includes('/error') ? ( + + ) : null + } + /> + )} + + {/* Make sure the user has correct permissions */} + {!this.props.libs.framework.currentUserHasOneOfRoles( + ['beats_admin'].concat(this.props.libs.framework.info.settings.defaultUserRoles) + ) && ( + + !props.location.pathname.includes('/error') ? ( + + ) : null + } + /> + )} + + {/* If there are no beats or tags yet, redirect to the walkthrough */} + {this.state.loadingStatus === 'loaded:empty' && ( + + !props.location.pathname.includes('/walkthrough') ? ( + + ) : null } - return i18n.translate('xpack.beatsManagement.router.tagTitle', { - defaultMessage: 'Tag: {tagId}', - values: { tagId: params.tagid }, - }); - }} - parentBreadcrumbs={[ - { - text: i18n.translate('xpack.beatsManagement.router.tagsListTitle', { - defaultMessage: 'Tags List', - }), - href: '#/management/beats_management/overview/tags', - }, - ]} - path="/tag/:action/:tagid?" - render={(props: any) => } - /> + /> + )} + + {/* This app does not make use of a homepage. The mainpage is overview/enrolled_beats */} + } /> -
-
- ); -}; + + {/* Render routes from the FS */} + + {(URLProps: URLStateProps) => ( + + )} + +
+ ); + } +} diff --git a/x-pack/plugins/beats_management/public/utils/page_loader/__snapshots__/page_loader.test.ts.snap b/x-pack/plugins/beats_management/public/utils/page_loader/__snapshots__/page_loader.test.ts.snap new file mode 100644 index 0000000000000..91852239ba6fd --- /dev/null +++ b/x-pack/plugins/beats_management/public/utils/page_loader/__snapshots__/page_loader.test.ts.snap @@ -0,0 +1,143 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`RouteTreeBuilder routeTreeFromPaths Should create a route tree 1`] = ` +Array [ + Object { + "component": null, + "path": "/tag", + }, + Object { + "component": null, + "path": "/beat", + "routes": Array [ + Object { + "component": null, + "path": "/beat/detail", + }, + Object { + "component": null, + "path": "/beat/tags", + }, + ], + }, + Object { + "component": null, + "path": "/error/enforce_security", + }, + Object { + "component": null, + "path": "/error/invalid_license", + }, + Object { + "component": null, + "path": "/error/no_access", + }, + Object { + "component": null, + "path": "/overview", + "routes": Array [ + Object { + "component": null, + "path": "/overview/enrolled_beats", + }, + Object { + "component": null, + "path": "/overview/tag_configurations", + }, + ], + }, + Object { + "component": null, + "path": "/walkthrough/initial", + "routes": Array [ + Object { + "component": null, + "path": "/walkthrough/initial/beat", + }, + Object { + "component": null, + "path": "/walkthrough/initial/finish", + }, + Object { + "component": null, + "path": "/walkthrough/initial/tag", + }, + ], + }, + Object { + "component": null, + "path": "*", + }, +] +`; + +exports[`RouteTreeBuilder routeTreeFromPaths Should create a route tree, with top level route having params 1`] = ` +Array [ + Object { + "component": null, + "path": "/tag/:action/:tagid?", + }, + Object { + "component": null, + "path": "/beat", + "routes": Array [ + Object { + "component": null, + "path": "/beat/detail", + }, + Object { + "component": null, + "path": "/beat/tags", + }, + ], + }, + Object { + "component": null, + "path": "/error/enforce_security", + }, + Object { + "component": null, + "path": "/error/invalid_license", + }, + Object { + "component": null, + "path": "/error/no_access", + }, + Object { + "component": null, + "path": "/overview", + "routes": Array [ + Object { + "component": null, + "path": "/overview/enrolled_beats", + }, + Object { + "component": null, + "path": "/overview/tag_configurations", + }, + ], + }, + Object { + "component": null, + "path": "/walkthrough/initial", + "routes": Array [ + Object { + "component": null, + "path": "/walkthrough/initial/beat", + }, + Object { + "component": null, + "path": "/walkthrough/initial/finish", + }, + Object { + "component": null, + "path": "/walkthrough/initial/tag", + }, + ], + }, + Object { + "component": null, + "path": "*", + }, +] +`; diff --git a/x-pack/plugins/beats_management/public/utils/page_loader/page_loader.test.ts b/x-pack/plugins/beats_management/public/utils/page_loader/page_loader.test.ts new file mode 100644 index 0000000000000..e7618588e536e --- /dev/null +++ b/x-pack/plugins/beats_management/public/utils/page_loader/page_loader.test.ts @@ -0,0 +1,138 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { RouteTreeBuilder } from './page_loader'; + +const pages = [ + './_404.tsx', + './beat/detail.tsx', + './beat/index.tsx', + './beat/tags.tsx', + './error/enforce_security.tsx', + './error/invalid_license.tsx', + './error/no_access.tsx', + './overview/enrolled_beats.tsx', + './overview/index.tsx', + './overview/tag_configurations.tsx', + './tag.tsx', + './walkthrough/initial/beat.tsx', + './walkthrough/initial/finish.tsx', + './walkthrough/initial/index.tsx', + './walkthrough/initial/tag.tsx', +]; + +describe('RouteTreeBuilder', () => { + describe('routeTreeFromPaths', () => { + it('Should fail to create a route tree due to no exported *Page component', () => { + const mockRequire = jest.fn(path => ({ + path, + testComponent: null, + })); + + const treeBuilder = new RouteTreeBuilder(mockRequire); + + expect(() => { + treeBuilder.routeTreeFromPaths(pages); + }).toThrowError(/in the pages folder does not include an exported/); + }); + + it('Should create a route tree', () => { + const mockRequire = jest.fn(path => ({ + path, + testPage: null, + })); + + const treeBuilder = new RouteTreeBuilder(mockRequire); + + let tree; + expect(() => { + tree = treeBuilder.routeTreeFromPaths(pages); + }).not.toThrow(); + expect(tree).toMatchSnapshot(); + }); + + it('Should fail to create a route tree due to no exported custom *Component component', () => { + const mockRequire = jest.fn(path => ({ + path, + testComponent: null, + })); + + const treeBuilder = new RouteTreeBuilder(mockRequire, /Component$/); + + expect(() => { + treeBuilder.routeTreeFromPaths(pages); + }).not.toThrow(); + }); + + it('Should create a route tree, with top level route having params', () => { + const mockRequire = jest.fn(path => ({ + path, + testPage: null, + })); + + const treeBuilder = new RouteTreeBuilder(mockRequire); + const tree = treeBuilder.routeTreeFromPaths(pages, { + '/tag': ['action', 'tagid?'], + }); + expect(tree).toMatchSnapshot(); + }); + + it('Should create a route tree, with a nested route having params', () => { + const mockRequire = jest.fn(path => ({ + path, + testPage: null, + })); + + const treeBuilder = new RouteTreeBuilder(mockRequire); + const tree = treeBuilder.routeTreeFromPaths(pages, { + '/beat': ['beatId'], + }); + expect(tree[1].path).toEqual('/beat/:beatId'); + }); + }); + it('Should create a route tree, with a deep nested route having params', () => { + const mockRequire = jest.fn(path => ({ + path, + testPage: null, + })); + + const treeBuilder = new RouteTreeBuilder(mockRequire); + const tree = treeBuilder.routeTreeFromPaths(pages, { + '/beat': ['beatId'], + '/beat/detail': ['other'], + }); + expect(tree[1].path).toEqual('/beat/:beatId'); + expect(tree[1].routes![0].path).toEqual('/beat/:beatId/detail/:other'); + expect(tree[1].routes![1].path).toEqual('/beat/:beatId/tags'); + }); + it('Should throw an error on invalid mapped path', () => { + const mockRequire = jest.fn(path => ({ + path, + testPage: null, + })); + + const treeBuilder = new RouteTreeBuilder(mockRequire); + expect(() => { + treeBuilder.routeTreeFromPaths(pages, { + '/non-existant-path': ['beatId'], + }); + }).toThrowError(/Invalid overrideMap provided to 'routeTreeFromPaths', \/non-existant-path /); + }); + it('Should rended 404.tsx as a 404 route not /404', () => { + const mockRequire = jest.fn(path => ({ + path, + testPage: null, + })); + + const treeBuilder = new RouteTreeBuilder(mockRequire); + const tree = treeBuilder.routeTreeFromPaths(pages); + const firstPath = tree[0].path; + const lastPath = tree[tree.length - 1].path; + + expect(firstPath).not.toBe('/_404'); + expect(lastPath).toBe('*'); + }); +}); diff --git a/x-pack/plugins/beats_management/public/utils/page_loader/page_loader.ts b/x-pack/plugins/beats_management/public/utils/page_loader/page_loader.ts new file mode 100644 index 0000000000000..c6ccd14dbd825 --- /dev/null +++ b/x-pack/plugins/beats_management/public/utils/page_loader/page_loader.ts @@ -0,0 +1,170 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { difference, flatten, last } from 'lodash'; + +interface PathTree { + [path: string]: string[]; +} +export interface RouteConfig { + path: string; + component: React.ComponentType; + routes?: RouteConfig[]; +} + +interface RouteParamsMap { + [path: string]: string[]; +} + +export class RouteTreeBuilder { + constructor( + private readonly requireWithContext: any, + private readonly pageComponentPattern: RegExp = /Page$/ + ) {} + + public routeTreeFromPaths(paths: string[], mapParams: RouteParamsMap = {}): RouteConfig[] { + const pathTree = this.buildTree('./', paths); + const allRoutes = Object.keys(pathTree).reduce((routes: any[], filePath) => { + if (pathTree[filePath].includes('index.tsx')) { + routes.push(this.buildRouteWithChildren(filePath, pathTree[filePath], mapParams)); + } else { + routes.concat( + pathTree[filePath].map(file => routes.push(this.buildRoute(filePath, file, mapParams))) + ); + } + + return routes; + }, []); + // Check that no overide maps are ignored due to being invalid + const flatRoutes = this.flatpackRoutes(allRoutes); + const mappedPaths = Object.keys(mapParams); + const invalidOverrides = difference(mappedPaths, flatRoutes); + if (invalidOverrides.length > 0 && flatRoutes.length > 0) { + throw new Error( + `Invalid overrideMap provided to 'routeTreeFromPaths', ${ + invalidOverrides[0] + } is not a valid route. Only the following are: ${flatRoutes.join(', ')}` + ); + } + + // 404 route MUST be last or it gets used first in a switch + return allRoutes.sort((a: RouteConfig) => { + return a.path === '*' ? 1 : 0; + }); + } + + private flatpackRoutes(arr: RouteConfig[], pre: string = ''): string[] { + return flatten( + [].concat.apply( + [], + arr.map(item => { + const path = (pre + item.path).trim(); + + // The flattened route based on files without params added + const route = item.path.includes('/:') + ? item.path + .split('/') + .filter(s => s.charAt(0) !== ':') + .join('/') + : item.path; + return item.routes ? [route, this.flatpackRoutes(item.routes, path)] : route; + }) + ) + ); + } + + private buildRouteWithChildren(dir: string, files: string[], mapParams: RouteParamsMap) { + const childFiles = files.filter(f => f !== 'index.tsx'); + const parentConfig = this.buildRoute(dir, 'index.tsx', mapParams); + parentConfig.routes = childFiles.map(cf => this.buildRoute(dir, cf, mapParams)); + return parentConfig; + } + + private buildRoute(dir: string, file: string, mapParams: RouteParamsMap): RouteConfig { + // Remove the file extension as we dont want that in the URL... also index resolves to parent route + // so remove that... e.g. /beats/index is not the url we want, /beats should resolve to /beats/index + // just like how files resolve in node + const filePath = `${mapParams[dir] || dir}${file.replace('.tsx', '')}`.replace('/index', ''); + const page = this.requireWithContext(`.${dir}${file}`); + const cleanDir = dir.replace(/\/$/, ''); + + // Make sure the expored variable name matches a pattern. By default it will choose the first + // exported variable that matches *Page + const componentExportName = Object.keys(page).find(varName => + this.pageComponentPattern.test(varName) + ); + + if (!componentExportName) { + throw new Error( + `${dir}${file} in the pages folder does not include an exported \`${this.pageComponentPattern.toString()}\` component` + ); + } + + // _404 route is special and maps to a 404 page + if (filePath === '/_404') { + return { + path: '*', + component: page[componentExportName], + }; + } + + // mapped route has a parent with mapped params, so we map it here too + // e.g. /beat has a beatid param, so /beat/detail, a child of /beat + // should also have that param resulting in /beat/:beatid/detail/:other + if (mapParams[cleanDir] && filePath !== cleanDir) { + const dirWithParams = `${cleanDir}/:${mapParams[cleanDir].join('/:')}`; + const path = `${dirWithParams}/${file.replace('.tsx', '')}${ + mapParams[filePath] ? '/:' : '' + }${(mapParams[filePath] || []).join('/:')}`; + return { + path, + component: page[componentExportName], + }; + } + + // route matches a mapped param exactly + // e.g. /beat has a beatid param, so it becomes /beat/:beatid + if (mapParams[filePath]) { + return { + path: `${filePath}/:${mapParams[filePath].join('/:')}`, + component: page[componentExportName], + }; + } + + return { + path: filePath, + component: page[componentExportName], + }; + } + + // Build tree recursively + private buildTree(basePath: string, paths: string[]): PathTree { + return paths.reduce( + (dir: any, p) => { + const path = { + dir: + p + .replace(basePath, '/') // make path absolute + .split('/') + .slice(0, -1) // remove file from path + .join('/') + .replace(/^\/\//, '') + '/', // should end in a slash but not be only // + file: last(p.split('/')), + }; + // take each, remove the file name + + if (dir[path.dir]) { + dir[path.dir].push(path.file); + } else { + dir[path.dir] = [path.file]; + } + return dir; + }, + + {} + ); + } +} diff --git a/x-pack/plugins/beats_management/public/utils/page_loader/readme.md b/x-pack/plugins/beats_management/public/utils/page_loader/readme.md new file mode 100644 index 0000000000000..cd53a6eae9901 --- /dev/null +++ b/x-pack/plugins/beats_management/public/utils/page_loader/readme.md @@ -0,0 +1,21 @@ +# Page loader + +Routing in React is not easy, nether is ensuring a clean and simple api within pages. +This solves for both without massive config files. It also ensure URL paths match our files to make things easier to find + +It works like this... + +```ts +// Create a webpack context, ensureing all pages in the pages dir are included in the build +const requirePages = require.context('./pages', true, /\.tsx$/); +// Pass the context based require into the RouteTreeBuilder for require the files as-needed +const routeTreeBuilder = new RouteTreeBuilder(requirePages); +// turn the array of file paths from the require context into a nested tree of routes based on folder structure +const routesFromFilesystem = routeTreeBuilder.routeTreeFromPaths(requirePages.keys(), { + '/tag': ['action', 'tagid?'], // add params to a page. In this case /tag turns into /tag/:action/:tagid? + '/beat': ['beatId'], + '/beat/detail': ['action'], // it nests too, in this case, because of the above line, this is /beat/:beatId/detail/:action +}); +``` + +In the above example to allow for flexability, the `./pages/beat.tsx` page would receve a prop of `routes` that is an array of sub-pages diff --git a/x-pack/plugins/beats_management/server/lib/adapters/beats/elasticsearch_beats_adapter.ts b/x-pack/plugins/beats_management/server/lib/adapters/beats/elasticsearch_beats_adapter.ts index e8307e09b6567..0aa04f04b66d3 100644 --- a/x-pack/plugins/beats_management/server/lib/adapters/beats/elasticsearch_beats_adapter.ts +++ b/x-pack/plugins/beats_management/server/lib/adapters/beats/elasticsearch_beats_adapter.ts @@ -8,7 +8,6 @@ import { flatten, get as _get, omit } from 'lodash'; import { INDEX_NAMES } from '../../../../common/constants'; import { CMBeat } from '../../../../common/domain_types'; import { DatabaseAdapter } from '../database/adapter_types'; - import { FrameworkUser } from '../framework/adapter_types'; import { BeatsTagAssignment, CMBeatsAdapter } from './adapter_types'; @@ -71,7 +70,6 @@ export class ElasticsearchBeatsAdapter implements CMBeatsAdapter { const ids = beatIds.map(beatId => `beat:${beatId}`); const params = { - _sourceIncludes: ['beat.id', 'beat.verified_on'], body: { ids, }, diff --git a/x-pack/plugins/beats_management/server/lib/adapters/database/adapter_types.ts b/x-pack/plugins/beats_management/server/lib/adapters/database/adapter_types.ts index 59a36dceac50f..c0cd1e561b587 100644 --- a/x-pack/plugins/beats_management/server/lib/adapters/database/adapter_types.ts +++ b/x-pack/plugins/beats_management/server/lib/adapters/database/adapter_types.ts @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ import { FrameworkRequest, FrameworkUser } from '../framework/adapter_types'; + export interface DatabaseAdapter { putTemplate(user: FrameworkUser, params: DatabasePutTemplateParams): Promise; get( @@ -62,8 +63,8 @@ export interface DatabaseSearchParams extends DatabaseGenericParams { size?: number; sort?: DatabaseNameList; _source?: DatabaseNameList; - _sourceExcludes?: DatabaseNameList; - _sourceIncludes?: DatabaseNameList; + _sourceExclude?: DatabaseNameList; + _source_includes?: DatabaseNameList; terminateAfter?: number; stats?: DatabaseNameList; suggestField?: string; @@ -141,8 +142,8 @@ export interface DatabaseBulkIndexDocumentsParams extends DatabaseGenericParams type?: string; fields?: DatabaseNameList; _source?: DatabaseNameList; - _sourceExcludes?: DatabaseNameList; - _sourceIncludes?: DatabaseNameList; + _sourceExclude?: DatabaseNameList; + _source_includes?: DatabaseNameList; pipeline?: string; index?: string; } @@ -153,8 +154,8 @@ export interface DatabaseMGetParams extends DatabaseGenericParams { realtime?: boolean; refresh?: boolean; _source?: DatabaseNameList; - _sourceExcludes?: DatabaseNameList; - _sourceIncludes?: DatabaseNameList; + _sourceExclude?: DatabaseNameList; + _source_includes?: DatabaseNameList; index: string; type?: string; } @@ -272,8 +273,8 @@ export interface DatabaseGetParams extends DatabaseGenericParams { refresh?: boolean; routing?: string; _source?: DatabaseNameList; - _sourceExcludes?: DatabaseNameList; - _sourceIncludes?: DatabaseNameList; + _sourceExclude?: DatabaseNameList; + _source_includes?: DatabaseNameList; version?: number; versionType?: DatabaseVersionType; id: string; diff --git a/x-pack/plugins/beats_management/server/lib/adapters/database/kibana_database_adapter.ts b/x-pack/plugins/beats_management/server/lib/adapters/database/kibana_database_adapter.ts index ba593a793e34b..9a9424fc54e4e 100644 --- a/x-pack/plugins/beats_management/server/lib/adapters/database/kibana_database_adapter.ts +++ b/x-pack/plugins/beats_management/server/lib/adapters/database/kibana_database_adapter.ts @@ -3,8 +3,8 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { internalAuthData } from '../../../utils/wrap_request'; import { FrameworkUser } from '../framework/adapter_types'; +import { internalAuthData } from './../framework/adapter_types'; import { DatabaseAdapter, DatabaseBulkIndexDocumentsParams, diff --git a/x-pack/plugins/beats_management/server/lib/adapters/framework/__tests__/kibana.ts b/x-pack/plugins/beats_management/server/lib/adapters/framework/__tests__/kibana.ts index b483379d444c0..9ef126ec69296 100644 --- a/x-pack/plugins/beats_management/server/lib/adapters/framework/__tests__/kibana.ts +++ b/x-pack/plugins/beats_management/server/lib/adapters/framework/__tests__/kibana.ts @@ -7,10 +7,12 @@ // @ts-ignore import { createEsTestCluster } from '@kbn/test'; -import { config as beatsPluginConfig, configPrefix } from '../../../../..'; +import { config as beatsPluginConfig } from '../../../../..'; // @ts-ignore import * as kbnTestServer from '../../../../../../../../src/test_utils/kbn_server'; import { KibanaBackendFrameworkAdapter } from '../kibana_framework_adapter'; +import { PLUGIN } from './../../../../../common/constants/plugin'; +import { CONFIG_PREFIX } from './../../../../../common/constants/plugin'; import { contractTests } from './test_contract'; const kbnServer = kbnTestServer.createRootWithCorePlugins({ server: { maxPayloadBytes: 100 } }); @@ -21,7 +23,7 @@ contractTests('Kibana Framework Adapter', { await kbnServer.start(); const config = legacyServer.server.config(); - config.extendSchema(beatsPluginConfig, {}, configPrefix); + config.extendSchema(beatsPluginConfig, {}, CONFIG_PREFIX); config.set('xpack.beats.encryptionKey', 'foo'); }, @@ -29,6 +31,6 @@ contractTests('Kibana Framework Adapter', { await kbnServer.shutdown(); }, adapterSetup: () => { - return new KibanaBackendFrameworkAdapter(legacyServer.server); + return new KibanaBackendFrameworkAdapter(PLUGIN.ID, legacyServer.server); }, }); diff --git a/x-pack/plugins/beats_management/server/lib/adapters/framework/adapter_types.ts b/x-pack/plugins/beats_management/server/lib/adapters/framework/adapter_types.ts index 64dca03e68d56..c02df7a42030e 100644 --- a/x-pack/plugins/beats_management/server/lib/adapters/framework/adapter_types.ts +++ b/x-pack/plugins/beats_management/server/lib/adapters/framework/adapter_types.ts @@ -4,21 +4,118 @@ * you may not use this file except in compliance with the Elastic License. */ import { Lifecycle, ResponseToolkit } from 'hapi'; -import { internalAuthData } from '../../../utils/wrap_request'; +import * as t from 'io-ts'; +import { LicenseType } from '../../../../common/constants/security'; + +export const internalAuthData = Symbol('internalAuthData'); +export const internalUser: FrameworkInternalUser = { + kind: 'internal', +}; + +export interface XpackInfo { + license: { + getType: () => LicenseType; + /** Is the license expired */ + isActive: () => boolean; + getExpiryDateInMillis: () => number; + }; + feature: (pluginId: string) => any; + isAvailable: () => boolean; +} export interface BackendFrameworkAdapter { internalUser: FrameworkInternalUser; - version: string; + info: null | FrameworkInfo; + log(text: string): void; + on(event: 'xpack.status.green', cb: () => void): void; getSetting(settingPath: string): any; exposeStaticDir(urlPath: string, dir: string): void; - registerRoute< - RouteRequest extends FrameworkWrappableRequest, - RouteResponse extends FrameworkResponse - >( + registerRoute( route: FrameworkRouteOptions ): void; } +export interface KibanaLegacyServer { + plugins: { + xpack_main: { + status: { + once: (status: 'green' | 'yellow' | 'red', callback: () => void) => void; + }; + info: XpackInfo; + }; + kibana: { + status: { + plugin: { + version: string; + }; + }; + }; + security: { + getUser: (request: KibanaServerRequest) => any; + }; + elasticsearch: { + getCluster: () => any; + }; + beats_management: {}; + }; + config: () => any; + route: (routeConfig: any) => void; + log: (message: string) => void; +} + +export const RuntimeFrameworkInfo = t.interface( + { + kibana: t.type({ + version: t.string, + }), + license: t.type({ + type: t.union( + ['oss', 'trial', 'standard', 'basic', 'gold', 'platinum'].map(s => t.literal(s)) + ), + expired: t.boolean, + expiry_date_in_millis: t.number, + }), + security: t.type({ + enabled: t.boolean, + available: t.boolean, + }), + watcher: t.type({ + enabled: t.boolean, + available: t.boolean, + }), + }, + 'FrameworkInfo' +); +export interface FrameworkInfo extends t.TypeOf {} + +export const RuntimeKibanaServerRequest = t.interface( + { + params: t.object, + payload: t.object, + query: t.object, + headers: t.type({ + authorization: t.union([t.string, t.null]), + }), + info: t.type({ + remoteAddress: t.string, + }), + }, + 'KibanaServerRequest' +); +export interface KibanaServerRequest extends t.TypeOf {} + +export const RuntimeKibanaUser = t.interface( + { + username: t.string, + roles: t.array(t.string), + full_name: t.union([t.null, t.string]), + email: t.union([t.null, t.string]), + enabled: t.boolean, + }, + 'KibanaUser' +); +export interface KibanaUser extends t.TypeOf {} + export interface FrameworkAuthenticatedUser { kind: 'authenticated'; [internalAuthData]: AuthDataType; @@ -26,9 +123,6 @@ export interface FrameworkAuthenticatedUser { roles: string[]; full_name: string | null; email: string | null; - metadata: { - [key: string]: any; - }; enabled: boolean; } @@ -45,46 +139,32 @@ export type FrameworkUser = | FrameworkUnAuthenticatedUser | FrameworkInternalUser; export interface FrameworkRequest< - InternalRequest extends FrameworkWrappableRequest = FrameworkWrappableRequest + KibanaServerRequestGenaric extends Partial = any > { - user: FrameworkUser; - headers: InternalRequest['headers']; - info: InternalRequest['info']; - payload: InternalRequest['payload']; - params: InternalRequest['params']; - query: InternalRequest['query']; + user: FrameworkUser; + headers: KibanaServerRequestGenaric['headers']; + info: KibanaServerRequest['info']; + payload: KibanaServerRequestGenaric['payload']; + params: KibanaServerRequestGenaric['params']; + query: KibanaServerRequestGenaric['query']; } export interface FrameworkRouteOptions< - RouteRequest extends FrameworkWrappableRequest, - RouteResponse extends FrameworkResponse + RouteRequest extends FrameworkRequest = FrameworkRequest, + RouteResponse extends FrameworkResponse = any > { path: string; method: string | string[]; vhost?: string; - licenseRequired?: boolean; + licenseRequired?: string[]; requiredRoles?: string[]; handler: FrameworkRouteHandler; config?: {}; } export type FrameworkRouteHandler< - RouteRequest extends FrameworkWrappableRequest, + RouteRequest extends KibanaServerRequest, RouteResponse extends FrameworkResponse > = (request: FrameworkRequest, h: ResponseToolkit) => void; -export interface FrameworkWrappableRequest< - Payload = any, - Params = any, - Query = any, - Headers = any, - Info = any -> { - headers: Headers; - info: Info; - payload: Payload; - params: Params; - query: Query; -} - export type FrameworkResponse = Lifecycle.ReturnValue; diff --git a/x-pack/plugins/beats_management/server/lib/adapters/framework/hapi_framework_adapter.ts b/x-pack/plugins/beats_management/server/lib/adapters/framework/hapi_framework_adapter.ts index 62e8b0599097d..90500e0283511 100644 --- a/x-pack/plugins/beats_management/server/lib/adapters/framework/hapi_framework_adapter.ts +++ b/x-pack/plugins/beats_management/server/lib/adapters/framework/hapi_framework_adapter.ts @@ -4,13 +4,16 @@ * you may not use this file except in compliance with the Elastic License. */ -import { wrapRequest } from '../../../utils/wrap_request'; -import { FrameworkInternalUser } from './adapter_types'; +import { LicenseType } from './../../../../common/constants/security'; +import { KibanaServerRequest } from './adapter_types'; import { BackendFrameworkAdapter, + FrameworkInfo, + FrameworkRequest, FrameworkResponse, FrameworkRouteOptions, - FrameworkWrappableRequest, + internalAuthData, + internalUser, } from './adapter_types'; interface TestSettings { @@ -19,10 +22,9 @@ interface TestSettings { } export class HapiBackendFrameworkAdapter implements BackendFrameworkAdapter { - public readonly internalUser: FrameworkInternalUser = { - kind: 'internal', - }; - public version: string; + public info: null | FrameworkInfo = null; + public readonly internalUser = internalUser; + private settings: TestSettings; private server: any; @@ -31,13 +33,40 @@ export class HapiBackendFrameworkAdapter implements BackendFrameworkAdapter { encryptionKey: 'something_who_cares', enrollmentTokensTtlInSeconds: 10 * 60, // 10 minutes }, - hapiServer?: any + hapiServer?: any, + license: LicenseType = 'trial', + securityEnabled: boolean = true, + licenseActive: boolean = true ) { this.server = hapiServer; this.settings = settings; - this.version = 'testing'; - } + const now = new Date(); + this.info = { + kibana: { + version: 'unknown', + }, + license: { + type: license, + expired: !licenseActive, + expiry_date_in_millis: new Date(now.getFullYear(), now.getMonth() + 1, 1).getTime(), + }, + security: { + enabled: securityEnabled, + available: securityEnabled, + }, + watcher: { + enabled: true, + available: true, + }, + }; + } + public log(text: string) { + this.server.log(text); + } + public on(event: 'xpack.status.green', cb: () => void) { + cb(); + } public getSetting(settingPath: string) { switch (settingPath) { case 'xpack.beats.enrollmentTokensTtlInSeconds': @@ -63,18 +92,18 @@ export class HapiBackendFrameworkAdapter implements BackendFrameworkAdapter { } public registerRoute< - RouteRequest extends FrameworkWrappableRequest, + RouteRequest extends FrameworkRequest, RouteResponse extends FrameworkResponse >(route: FrameworkRouteOptions) { if (!this.server) { throw new Error('Must pass a hapi server into the adapter to use registerRoute'); } - const wrappedHandler = (licenseRequired: boolean) => (request: any, h: any) => { - return route.handler(wrapRequest(request), h); + const wrappedHandler = (licenseRequired: string[]) => (request: any, h: any) => { + return route.handler(this.wrapRequest(request), h); }; this.server.route({ - handler: wrappedHandler(route.licenseRequired || false), + handler: wrappedHandler(route.licenseRequired || []), method: route.method, path: route.path, config: { @@ -87,4 +116,33 @@ export class HapiBackendFrameworkAdapter implements BackendFrameworkAdapter { public async injectRequstForTesting({ method, url, headers, payload }: any) { return await this.server.inject({ method, url, headers, payload }); } + + private wrapRequest( + req: InternalRequest + ): FrameworkRequest { + const { params, payload, query, headers, info } = req; + + const isAuthenticated = headers.authorization != null; + + return { + user: isAuthenticated + ? { + kind: 'authenticated', + [internalAuthData]: headers, + username: 'elastic', + roles: ['superuser'], + full_name: null, + email: null, + enabled: true, + } + : { + kind: 'unauthenticated', + }, + headers, + info, + params, + payload, + query, + }; + } } diff --git a/x-pack/plugins/beats_management/server/lib/adapters/framework/kibana_framework_adapter.ts b/x-pack/plugins/beats_management/server/lib/adapters/framework/kibana_framework_adapter.ts index 2004bf723f007..8a1bf22c434c2 100644 --- a/x-pack/plugins/beats_management/server/lib/adapters/framework/kibana_framework_adapter.ts +++ b/x-pack/plugins/beats_management/server/lib/adapters/framework/kibana_framework_adapter.ts @@ -4,61 +4,64 @@ * you may not use this file except in compliance with the Elastic License. */ -// @ts-ignore -import Boom from 'boom'; -import { difference } from 'lodash'; +import { ResponseToolkit } from 'hapi'; +import { PathReporter } from 'io-ts/lib/PathReporter'; +import { get } from 'lodash'; // @ts-ignore import { mirrorPluginStatus } from '../../../../../../server/lib/mirror_plugin_status'; -import { PLUGIN } from '../../../../common/constants/plugin'; -import { wrapRequest } from '../../../utils/wrap_request'; -import { FrameworkRequest } from './adapter_types'; import { BackendFrameworkAdapter, - FrameworkInternalUser, + FrameworkInfo, + FrameworkRequest, FrameworkResponse, FrameworkRouteOptions, - FrameworkWrappableRequest, + internalAuthData, + internalUser, + KibanaLegacyServer, + KibanaServerRequest, + KibanaUser, + RuntimeFrameworkInfo, + RuntimeKibanaUser, + XpackInfo, } from './adapter_types'; export class KibanaBackendFrameworkAdapter implements BackendFrameworkAdapter { - public readonly internalUser: FrameworkInternalUser = { - kind: 'internal', - }; - public version: string; - private server: any; - private cryptoHash: string | null; - - constructor(hapiServer: any) { - this.server = hapiServer; - if (hapiServer.plugins.kibana) { - this.version = hapiServer.plugins.kibana.status.plugin.version; - } else { - this.version = 'unknown'; - } - this.cryptoHash = null; - this.validateConfig(); + public readonly internalUser = internalUser; + public info: null | FrameworkInfo = null; - const xpackMainPlugin = hapiServer.plugins.xpack_main; - const thisPlugin = hapiServer.plugins.beats_management; + constructor( + private readonly PLUGIN_ID: string, + private readonly server: KibanaLegacyServer, + private readonly CONFIG_PREFIX?: string + ) { + const xpackMainPlugin = this.server.plugins.xpack_main; + const thisPlugin = this.server.plugins.beats_management; mirrorPluginStatus(xpackMainPlugin, thisPlugin); + xpackMainPlugin.status.once('green', () => { + this.xpackInfoWasUpdatedHandler(xpackMainPlugin.info); // Register a function that is called whenever the xpack info changes, // to re-compute the license check results for this plugin xpackMainPlugin.info - .feature(PLUGIN.ID) - .registerLicenseCheckResultsGenerator((xPackInfo: any) => this.checkLicense(xPackInfo)); + .feature(this.PLUGIN_ID) + .registerLicenseCheckResultsGenerator(this.xpackInfoWasUpdatedHandler); }); } - // TODO make base path a constructor level param - public getSetting(settingPath: string) { - // TODO type check server properly - if (settingPath === 'xpack.beats.encryptionKey') { - // @ts-ignore - return this.server.config().get(settingPath) || this.cryptoHash; + + public on(event: 'xpack.status.green', cb: () => void) { + switch (event) { + case 'xpack.status.green': + this.server.plugins.xpack_main.status.once('green', cb); } - // @ts-ignore - return this.server.config().get(settingPath) || this.cryptoHash; + } + + public getSetting(settingPath: string) { + return this.server.config().get(settingPath); + } + + public log(text: string) { + this.server.log(text); } public exposeStaticDir(urlPath: string, dir: string): void { @@ -74,136 +77,120 @@ export class KibanaBackendFrameworkAdapter implements BackendFrameworkAdapter { } public registerRoute< - RouteRequest extends FrameworkWrappableRequest, + RouteRequest extends FrameworkRequest, RouteResponse extends FrameworkResponse >(route: FrameworkRouteOptions) { - const hasAny = (roles: string[], requiredRoles: string[]) => - requiredRoles.some(r => roles.includes(r)); - - const wrappedHandler = (licenseRequired: boolean, requiredRoles?: string[]) => async ( - request: any, - h: any - ) => { - const xpackMainPlugin = this.server.plugins.xpack_main; - const licenseCheckResults = xpackMainPlugin.info.feature(PLUGIN.ID).getLicenseCheckResults(); - if (licenseRequired && !licenseCheckResults.licenseValid) { - return Boom.forbidden(licenseCheckResults.message); - } - const wrappedRequest = wrapRequest(request); - if (requiredRoles) { - if (wrappedRequest.user.kind !== 'authenticated') { - return h.response().code(403); - } - wrappedRequest.user = { - ...wrappedRequest.user, - ...(await this.getUser(request)), - }; - - if ( - wrappedRequest.user.kind === 'authenticated' && - (!hasAny(wrappedRequest.user.roles, this.getSetting('xpack.beats.defaultUserRoles')) || - !wrappedRequest.user.roles) && - difference(requiredRoles, wrappedRequest.user.roles).length !== 0 - ) { - return h.response().code(403); - } - } - return route.handler(wrappedRequest, h); - }; - this.server.route({ - handler: wrappedHandler(route.licenseRequired || false, route.requiredRoles), + handler: async (request: KibanaServerRequest, h: ResponseToolkit) => { + // Note, RuntimeKibanaServerRequest is avalaible to validate request, and its type *is* KibanaServerRequest + // but is not used here for perf reasons. It's value here is not high enough... + return await route.handler(await this.wrapRequest(request), h); + }, method: route.method, path: route.path, config: route.config, }); } - private async getUser(request: FrameworkRequest) { + private async wrapRequest( + req: KibanaServerRequest + ): Promise> { + const { params, payload, query, headers, info } = req; + + let isAuthenticated = headers.authorization != null; + let user; + if (isAuthenticated) { + user = await this.getUser(req); + if (!user) { + isAuthenticated = false; + } + } + return { + user: + isAuthenticated && user + ? { + kind: 'authenticated', + [internalAuthData]: headers, + ...user, + } + : { + kind: 'unauthenticated', + }, + headers, + info, + params, + payload, + query, + }; + } + + private async getUser(request: KibanaServerRequest): Promise { + let user; try { - return await this.server.plugins.security.getUser(request); + user = await this.server.plugins.security.getUser(request); } catch (e) { return null; } - } - - // TODO make key a param - private validateConfig() { - // @ts-ignore - const config = this.server.config(); - const encryptionKey = config.get('xpack.beats.encryptionKey'); - - if (!encryptionKey) { - this.server.log( - 'Using a default encryption key for xpack.beats.encryptionKey. It is recommended that you set xpack.beats.encryptionKey in kibana.yml with a unique token' + const assertKibanaUser = RuntimeKibanaUser.decode(user); + if (assertKibanaUser.isLeft()) { + throw new Error( + `Error parsing user info in ${this.PLUGIN_ID}, ${ + PathReporter.report(assertKibanaUser)[0] + }` ); - this.cryptoHash = 'xpack_beats_default_encryptionKey'; } + + return user; } - // TODO this should NOT be in an adapter, break up and move validation to a lib - private checkLicense(xPackInfo: any) { - // If, for some reason, we cannot get the license information - // from Elasticsearch, assume worst case and disable the Logstash pipeline UI - if (!xPackInfo || !xPackInfo.isAvailable()) { - return { - securityEnabled: false, - licenseValid: false, - message: - 'You cannot manage Beats central management because license information is not available at this time.', - }; - } + private xpackInfoWasUpdatedHandler = (xpackInfo: XpackInfo) => { + let xpackInfoUnpacked: FrameworkInfo; - const VALID_LICENSE_MODES = ['trial', 'standard', 'gold', 'platinum']; - - const isLicenseValid = xPackInfo.license.isOneOf(VALID_LICENSE_MODES); - const isLicenseActive = xPackInfo.license.isActive(); - const licenseType = xPackInfo.license.getType(); - const isSecurityEnabled = xPackInfo.feature('security').isEnabled(); - - // License is not valid - if (!isLicenseValid) { - return { - defaultUserRoles: this.getSetting('xpack.beats.defaultUserRoles'), - securityEnabled: true, - licenseValid: false, - licenseExpired: false, - message: `Your ${licenseType} license does not support Beats central management features. Please upgrade your license.`, - }; + // If, for some reason, we cannot get the license information + // from Elasticsearch, assume worst case and disable + if (!xpackInfo || !xpackInfo.isAvailable()) { + this.info = null; + return; } - // License is valid but not active, we go into a read-only mode. - if (!isLicenseActive) { - return { - defaultUserRoles: this.getSetting('xpack.beats.defaultUserRoles'), - securityEnabled: true, - licenseValid: true, - licenseExpired: true, - message: `You cannot edit, create, or delete your Beats central management configurations because your ${licenseType} license has expired.`, + try { + xpackInfoUnpacked = { + kibana: { + version: get(this.server, 'plugins.kibana.status.plugin.version', 'unknown'), + }, + license: { + type: xpackInfo.license.getType(), + expired: !xpackInfo.license.isActive(), + expiry_date_in_millis: + xpackInfo.license.getExpiryDateInMillis() !== undefined + ? xpackInfo.license.getExpiryDateInMillis() + : -1, + }, + security: { + enabled: !!xpackInfo.feature('security') && xpackInfo.feature('security').isEnabled(), + available: !!xpackInfo.feature('security'), + }, + watcher: { + enabled: !!xpackInfo.feature('watcher') && xpackInfo.feature('watcher').isEnabled(), + available: !!xpackInfo.feature('watcher'), + }, }; + } catch (e) { + this.server.log(`Error accessing required xPackInfo in ${this.PLUGIN_ID} Kibana adapter`); + throw e; } - // Security is not enabled in ES - if (!isSecurityEnabled) { - const message = - 'Security must be enabled in order to use Beats central management features.' + - ' Please set xpack.security.enabled: true in your elasticsearch.yml.'; - return { - defaultUserRoles: this.getSetting('xpack.beats.defaultUserRoles'), - securityEnabled: false, - licenseValid: true, - licenseExpired: false, - - message, - }; + const assertData = RuntimeFrameworkInfo.decode(xpackInfoUnpacked); + if (assertData.isLeft()) { + throw new Error( + `Error parsing xpack info in ${this.PLUGIN_ID}, ${PathReporter.report(assertData)[0]}` + ); } + this.info = xpackInfoUnpacked; - // License is valid and active return { - defaultUserRoles: this.getSetting('xpack.beats.defaultUserRoles'), - securityEnabled: true, - licenseValid: true, - licenseExpired: false, + security: xpackInfoUnpacked.security, + settings: this.getSetting(this.CONFIG_PREFIX || this.PLUGIN_ID), }; - } + }; } diff --git a/x-pack/plugins/beats_management/server/lib/adapters/tags/elasticsearch_tags_adapter.ts b/x-pack/plugins/beats_management/server/lib/adapters/tags/elasticsearch_tags_adapter.ts index e3afa544fa0e1..e70d073858706 100644 --- a/x-pack/plugins/beats_management/server/lib/adapters/tags/elasticsearch_tags_adapter.ts +++ b/x-pack/plugins/beats_management/server/lib/adapters/tags/elasticsearch_tags_adapter.ts @@ -21,6 +21,7 @@ export class ElasticsearchTagsAdapter implements CMTagsAdapter { public async getAll(user: FrameworkUser, ESQuery?: any) { const params = { + ignore: [404], _source: true, size: 10000, index: INDEX_NAMES.BEATS, @@ -112,6 +113,7 @@ export class ElasticsearchTagsAdapter implements CMTagsAdapter { const ids = tagIds.map(tag => `tag:${tag}`); const params = { + ignore: [404], _source: true, body: { ids, diff --git a/x-pack/plugins/beats_management/server/lib/adapters/tokens/adapter_types.ts b/x-pack/plugins/beats_management/server/lib/adapters/tokens/adapter_types.ts index 2fe8c811c396e..51d846931ed2e 100644 --- a/x-pack/plugins/beats_management/server/lib/adapters/tokens/adapter_types.ts +++ b/x-pack/plugins/beats_management/server/lib/adapters/tokens/adapter_types.ts @@ -11,7 +11,7 @@ export interface TokenEnrollmentData { } export interface CMTokensAdapter { - deleteEnrollmentToken(enrollmentToken: string): Promise; - getEnrollmentToken(enrollmentToken: string): Promise; + deleteEnrollmentToken(user: FrameworkUser, enrollmentToken: string): Promise; + getEnrollmentToken(user: FrameworkUser, enrollmentToken: string): Promise; upsertTokens(user: FrameworkUser, tokens: TokenEnrollmentData[]): Promise; } diff --git a/x-pack/plugins/beats_management/server/lib/adapters/tokens/elasticsearch_tokens_adapter.ts b/x-pack/plugins/beats_management/server/lib/adapters/tokens/elasticsearch_tokens_adapter.ts index 6aa9ceff46629..53038651cc4c5 100644 --- a/x-pack/plugins/beats_management/server/lib/adapters/tokens/elasticsearch_tokens_adapter.ts +++ b/x-pack/plugins/beats_management/server/lib/adapters/tokens/elasticsearch_tokens_adapter.ts @@ -7,29 +7,26 @@ import { flatten, get } from 'lodash'; import { INDEX_NAMES } from '../../../../common/constants'; import { DatabaseAdapter } from '../database/adapter_types'; -import { BackendFrameworkAdapter, FrameworkUser } from '../framework/adapter_types'; +import { FrameworkUser } from '../framework/adapter_types'; import { CMTokensAdapter, TokenEnrollmentData } from './adapter_types'; export class ElasticsearchTokensAdapter implements CMTokensAdapter { - private database: DatabaseAdapter; - private framework: BackendFrameworkAdapter; + constructor(private readonly database: DatabaseAdapter) {} - constructor(database: DatabaseAdapter, framework: BackendFrameworkAdapter) { - this.database = database; - this.framework = framework; - } - - public async deleteEnrollmentToken(enrollmentToken: string) { + public async deleteEnrollmentToken(user: FrameworkUser, enrollmentToken: string) { const params = { id: `enrollment_token:${enrollmentToken}`, index: INDEX_NAMES.BEATS, type: '_doc', }; - await this.database.delete(this.framework.internalUser, params); + await this.database.delete(user, params); } - public async getEnrollmentToken(tokenString: string): Promise { + public async getEnrollmentToken( + user: FrameworkUser, + tokenString: string + ): Promise { const params = { id: `enrollment_token:${tokenString}`, ignore: [404], @@ -37,7 +34,7 @@ export class ElasticsearchTokensAdapter implements CMTokensAdapter { type: '_doc', }; - const response = await this.database.get(this.framework.internalUser, params); + const response = await this.database.get(user, params); const tokenDetails = get(response, '_source.enrollment_token', { expires_on: '0', token: null, diff --git a/x-pack/plugins/beats_management/server/lib/adapters/tokens/memory_tokens_adapter.ts b/x-pack/plugins/beats_management/server/lib/adapters/tokens/memory_tokens_adapter.ts index fabbafc040969..dcb0ab7bad0aa 100644 --- a/x-pack/plugins/beats_management/server/lib/adapters/tokens/memory_tokens_adapter.ts +++ b/x-pack/plugins/beats_management/server/lib/adapters/tokens/memory_tokens_adapter.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { FrameworkAuthenticatedUser } from '../framework/adapter_types'; +import { FrameworkAuthenticatedUser, FrameworkUser } from '../framework/adapter_types'; import { CMTokensAdapter, TokenEnrollmentData } from './adapter_types'; export class MemoryTokensAdapter implements CMTokensAdapter { @@ -14,7 +14,7 @@ export class MemoryTokensAdapter implements CMTokensAdapter { this.tokenDB = tokenDB; } - public async deleteEnrollmentToken(enrollmentToken: string) { + public async deleteEnrollmentToken(user: FrameworkUser, enrollmentToken: string) { const index = this.tokenDB.findIndex(token => token.token === enrollmentToken); if (index > -1) { @@ -22,7 +22,10 @@ export class MemoryTokensAdapter implements CMTokensAdapter { } } - public async getEnrollmentToken(tokenString: string): Promise { + public async getEnrollmentToken( + user: FrameworkUser, + tokenString: string + ): Promise { return new Promise(resolve => { return resolve(this.tokenDB.find(token => token.token === tokenString)); }); diff --git a/x-pack/plugins/beats_management/server/lib/domains/beats.ts b/x-pack/plugins/beats_management/server/lib/beats.ts similarity index 88% rename from x-pack/plugins/beats_management/server/lib/domains/beats.ts rename to x-pack/plugins/beats_management/server/lib/beats.ts index a1b890119fc3e..5bcb10bd04a97 100644 --- a/x-pack/plugins/beats_management/server/lib/domains/beats.ts +++ b/x-pack/plugins/beats_management/server/lib/beats.ts @@ -6,26 +6,26 @@ import { uniq } from 'lodash'; import moment from 'moment'; -import { findNonExistentItems } from '../../utils/find_non_existent_items'; +import { findNonExistentItems } from '../utils/find_non_existent_items'; -import { CMBeat } from '../../../common/domain_types'; -import { BeatsTagAssignment, CMBeatsAdapter } from '../adapters/beats/adapter_types'; -import { FrameworkUser } from '../adapters/framework/adapter_types'; +import { CMBeat } from '../../common/domain_types'; +import { BeatsTagAssignment, CMBeatsAdapter } from './adapters/beats/adapter_types'; +import { FrameworkUser } from './adapters/framework/adapter_types'; -import { CMAssignmentReturn } from '../adapters/beats/adapter_types'; -import { BeatsRemovalReturn } from '../adapters/beats/adapter_types'; -import { BeatEnrollmentStatus, CMDomainLibs, CMServerLibs, UserOrToken } from '../lib'; +import { CMAssignmentReturn } from './adapters/beats/adapter_types'; +import { BeatsRemovalReturn } from './adapters/beats/adapter_types'; +import { BeatEnrollmentStatus, CMServerLibs, UserOrToken } from './types'; export class CMBeatsDomain { - private tags: CMDomainLibs['tags']; - private tokens: CMDomainLibs['tokens']; + private tags: CMServerLibs['tags']; + private tokens: CMServerLibs['tokens']; private framework: CMServerLibs['framework']; constructor( private readonly adapter: CMBeatsAdapter, libs: { - tags: CMDomainLibs['tags']; - tokens: CMDomainLibs['tokens']; + tags: CMServerLibs['tags']; + tokens: CMServerLibs['tokens']; framework: CMServerLibs['framework']; } ) { @@ -60,7 +60,7 @@ export class CMBeatsDomain { public async update(userOrToken: UserOrToken, beatId: string, beatData: Partial) { const beat = await this.adapter.get(this.framework.internalUser, beatId); - // TODO make return type enum + // FIXME make return type enum if (beat === null) { return 'beat-not-found'; } @@ -83,7 +83,6 @@ export class CMBeatsDomain { }); } - // TODO more strongly type this public async enrollBeat( enrollmentToken: string, beatId: string, @@ -148,7 +147,7 @@ export class CMBeatsDomain { 'removals' ); - // TODO abstract this + // FIXME abstract this const validRemovals = removals .map((removal, idxInRequest) => ({ beatId: removal.beatId, @@ -180,8 +179,8 @@ export class CMBeatsDomain { const nonExistentBeatIds = findNonExistentItems(beats, beatIds); const nonExistentTags = findNonExistentItems(tags, tagIds); - // TODO break out back into route / function response - // TODO causes function to error if a beat or tag does not exist + // FIXME break out back into route / function response + // FIXME causes function to error if a beat or tag does not exist addNonExistentItemToResponse( response, assignments, @@ -190,7 +189,7 @@ export class CMBeatsDomain { 'assignments' ); - // TODO abstract this + // FIXME abstract this const validAssignments = assignments .map((assignment, idxInRequest) => ({ beatId: assignment.beatId, @@ -209,7 +208,7 @@ export class CMBeatsDomain { } } -// TODO abstract to the route, also the key arg is a temp fix +// FIXME abstract to the route, also the key arg is a temp fix function addNonExistentItemToResponse( response: any, assignments: any, diff --git a/x-pack/plugins/beats_management/server/lib/compose/kibana.ts b/x-pack/plugins/beats_management/server/lib/compose/kibana.ts index bc00278251610..f2886e4efc323 100644 --- a/x-pack/plugins/beats_management/server/lib/compose/kibana.ts +++ b/x-pack/plugins/beats_management/server/lib/compose/kibana.ts @@ -10,19 +10,26 @@ import { ElasticsearchTagsAdapter } from '../adapters/tags/elasticsearch_tags_ad import { ElasticsearchTokensAdapter } from '../adapters/tokens/elasticsearch_tokens_adapter'; import { KibanaBackendFrameworkAdapter } from '../adapters/framework/kibana_framework_adapter'; +import { BackendFrameworkLib } from './../framework'; -import { CMBeatsDomain } from '../domains/beats'; -import { CMTagsDomain } from '../domains/tags'; -import { CMTokensDomain } from '../domains/tokens'; +import { CMBeatsDomain } from '../beats'; +import { CMTagsDomain } from '../tags'; +import { CMTokensDomain } from '../tokens'; -import { CMDomainLibs, CMServerLibs } from '../lib'; +import { PLUGIN } from 'x-pack/plugins/beats_management/common/constants'; +import { CONFIG_PREFIX } from 'x-pack/plugins/beats_management/common/constants/plugin'; +import { DatabaseKbnESPlugin } from '../adapters/database/adapter_types'; +import { KibanaLegacyServer } from '../adapters/framework/adapter_types'; +import { CMServerLibs } from '../types'; -export function compose(server: any): CMServerLibs { - const framework = new KibanaBackendFrameworkAdapter(server); - const database = new KibanaDatabaseAdapter(server.plugins.elasticsearch); +export function compose(server: KibanaLegacyServer): CMServerLibs { + const framework = new BackendFrameworkLib( + new KibanaBackendFrameworkAdapter(PLUGIN.ID, server, CONFIG_PREFIX) + ); + const database = new KibanaDatabaseAdapter(server.plugins.elasticsearch as DatabaseKbnESPlugin); const tags = new CMTagsDomain(new ElasticsearchTagsAdapter(database)); - const tokens = new CMTokensDomain(new ElasticsearchTokensAdapter(database, framework), { + const tokens = new CMTokensDomain(new ElasticsearchTokensAdapter(database), { framework, }); const beats = new CMBeatsDomain(new ElasticsearchBeatsAdapter(database), { @@ -31,16 +38,12 @@ export function compose(server: any): CMServerLibs { framework, }); - const domainLibs: CMDomainLibs = { - beats, - tags, - tokens, - }; - const libs: CMServerLibs = { framework, database, - ...domainLibs, + beats, + tags, + tokens, }; return libs; diff --git a/x-pack/plugins/beats_management/server/lib/compose/testing.ts b/x-pack/plugins/beats_management/server/lib/compose/testing.ts index 41fc18b80aeef..7a3f5ed8b5d6a 100644 --- a/x-pack/plugins/beats_management/server/lib/compose/testing.ts +++ b/x-pack/plugins/beats_management/server/lib/compose/testing.ts @@ -10,14 +10,15 @@ import { MemoryTokensAdapter } from '../adapters/tokens/memory_tokens_adapter'; import { HapiBackendFrameworkAdapter } from '../adapters/framework/hapi_framework_adapter'; -import { CMBeatsDomain } from '../domains/beats'; -import { CMTagsDomain } from '../domains/tags'; -import { CMTokensDomain } from '../domains/tokens'; +import { CMBeatsDomain } from '../beats'; +import { CMTagsDomain } from '../tags'; +import { CMTokensDomain } from '../tokens'; -import { CMDomainLibs, CMServerLibs } from '../lib'; +import { BackendFrameworkLib } from '../framework'; +import { CMServerLibs } from '../types'; export function compose(server: any): CMServerLibs { - const framework = new HapiBackendFrameworkAdapter(undefined, server); + const framework = new BackendFrameworkLib(new HapiBackendFrameworkAdapter(undefined, server)); const tags = new CMTagsDomain(new MemoryTagsAdapter(server.tagsDB || [])); const tokens = new CMTokensDomain(new MemoryTokensAdapter(server.tokensDB || []), { @@ -29,16 +30,12 @@ export function compose(server: any): CMServerLibs { framework, }); - const domainLibs: CMDomainLibs = { + const libs: CMServerLibs = { + framework, beats, tags, tokens, }; - const libs: CMServerLibs = { - framework, - ...domainLibs, - }; - return libs; } diff --git a/x-pack/plugins/beats_management/server/lib/domains/__tests__/beats/assign_tags.test.ts b/x-pack/plugins/beats_management/server/lib/domains/__tests__/beats/assign_tags.test.ts deleted file mode 100644 index 96ff86013762f..0000000000000 --- a/x-pack/plugins/beats_management/server/lib/domains/__tests__/beats/assign_tags.test.ts +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { FrameworkInternalUser } from '../../../adapters/framework/adapter_types'; - -import { MemoryBeatsAdapter } from '../../../adapters/beats/memory_beats_adapter'; -import { HapiBackendFrameworkAdapter } from '../../../adapters/framework/hapi_framework_adapter'; -import { MemoryTagsAdapter } from '../../../adapters/tags/memory_tags_adapter'; -import { MemoryTokensAdapter } from '../../../adapters/tokens/memory_tokens_adapter'; - -import { BeatTag, CMBeat } from '../../../../../common/domain_types'; - -import { CMBeatsDomain } from '../../beats'; -import { CMTagsDomain } from '../../tags'; -import { CMTokensDomain } from '../../tokens'; - -import Chance from 'chance'; - -const seed = Date.now(); -const chance = new Chance(seed); - -const internalUser: FrameworkInternalUser = { kind: 'internal' }; - -const settings = { - encryptionKey: 'something_who_cares', - enrollmentTokensTtlInSeconds: 10 * 60, // 10 minutes -}; - -describe('Beats Domain Lib', () => { - let beatsLib: CMBeatsDomain; - let beatsDB: CMBeat[] = []; - let tagsDB: BeatTag[] = []; - - describe('assign_tags_to_beats', () => { - beforeEach(async () => { - beatsDB = [ - { - access_token: '9a6c99ae0fd84b068819701169cd8a4b', - config_status: 'OK', - active: true, - enrollment_token: '23423423423', - host_ip: '1.2.3.4', - host_name: 'foo.bar.com', - id: 'qux', - type: 'filebeat', - }, - { - access_token: '188255eb560a4448b72656c5e99cae6f', - active: true, - config_status: 'OK', - enrollment_token: 'reertrte', - host_ip: '22.33.11.44', - host_name: 'baz.bar.com', - id: 'baz', - type: 'metricbeat', - }, - { - access_token: '93c4a4dd08564c189a7ec4e4f046b975', - active: true, - enrollment_token: '23s423423423', - config_status: 'OK', - host_ip: '1.2.3.4', - host_name: 'foo.bar.com', - id: 'foo', - tags: ['production', 'qa'], - type: 'metricbeat', - verified_on: '2018-05-15T16:25:38.924Z', - }, - { - access_token: '3c4a4dd08564c189a7ec4e4f046b9759', - enrollment_token: 'gdfsgdf', - active: true, - config_status: 'OK', - host_ip: '11.22.33.44', - host_name: 'foo.com', - id: 'bar', - type: 'filebeat', - }, - ]; - tagsDB = [ - { - configuration_blocks: [], - id: 'production', - last_updated: new Date(), - }, - { - configuration_blocks: [], - id: 'development', - last_updated: new Date(), - }, - { - configuration_blocks: [], - id: 'qa', - last_updated: new Date(), - }, - ]; - const framework = new HapiBackendFrameworkAdapter(settings); - - const tokensLib = new CMTokensDomain(new MemoryTokensAdapter([]), { - framework, - }); - - const tagsLib = new CMTagsDomain(new MemoryTagsAdapter(tagsDB)); - - beatsLib = new CMBeatsDomain(new MemoryBeatsAdapter(beatsDB), { - tags: tagsLib, - tokens: tokensLib, - framework, - }); - }); - - it('should add a single tag to a single beat', async () => { - const apiResponse = await beatsLib.assignTagsToBeats(internalUser, [ - { beatId: 'bar', tag: 'production' }, - ]); - - expect(apiResponse.assignments).toEqual([{ status: 200, result: 'updated' }]); - }); - - it('should not re-add an existing tag to a beat', async () => { - const tags = ['production']; - - let beat = beatsDB.find(b => b.id === 'foo') as any; - expect(beat.tags).toEqual([...tags, 'qa']); - - // Adding the existing tag - const apiResponse = await beatsLib.assignTagsToBeats(internalUser, [ - { beatId: 'foo', tag: 'production' }, - ]); - - expect(apiResponse.assignments).toEqual([{ status: 200, result: 'updated' }]); - - beat = beatsDB.find(b => b.id === 'foo') as any; - expect(beat.tags).toEqual([...tags, 'qa']); - }); - - it('should add a single tag to a multiple beats', async () => { - const apiResponse = await beatsLib.assignTagsToBeats(internalUser, [ - { beatId: 'foo', tag: 'development' }, - { beatId: 'bar', tag: 'development' }, - ]); - - expect(apiResponse.assignments).toEqual([ - { status: 200, result: 'updated' }, - { status: 200, result: 'updated' }, - ]); - - let beat = beatsDB.find(b => b.id === 'foo') as any; - expect(beat.tags).toEqual(['production', 'qa', 'development']); // as beat 'foo' already had 'production' and 'qa' tags attached to it - - beat = beatsDB.find(b => b.id === 'bar') as any; - expect(beat.tags).toEqual(['development']); - }); - - it('should add multiple tags to a single beat', async () => { - const apiResponse = await beatsLib.assignTagsToBeats(internalUser, [ - { beatId: 'bar', tag: 'development' }, - { beatId: 'bar', tag: 'production' }, - ]); - - expect(apiResponse.assignments).toEqual([ - { status: 200, result: 'updated' }, - { status: 200, result: 'updated' }, - ]); - - const beat = beatsDB.find(b => b.id === 'bar') as any; - expect(beat.tags).toEqual(['development', 'production']); - }); - - it('should add multiple tags to a multiple beats', async () => { - const apiResponse = await beatsLib.assignTagsToBeats(internalUser, [ - { beatId: 'foo', tag: 'development' }, - { beatId: 'bar', tag: 'production' }, - ]); - - expect(apiResponse.assignments).toEqual([ - { status: 200, result: 'updated' }, - { status: 200, result: 'updated' }, - ]); - - let beat = beatsDB.find(b => b.id === 'foo') as any; - expect(beat.tags).toEqual(['production', 'qa', 'development']); // as beat 'foo' already had 'production' and 'qa' tags attached to it - - beat = beatsDB.find(b => b.id === 'bar') as any; - expect(beat.tags).toEqual(['production']); - }); - - it('should return errors for non-existent beats', async () => { - const nonExistentBeatId = chance.word(); - - const apiResponse = await beatsLib.assignTagsToBeats(internalUser, [ - { beatId: nonExistentBeatId, tag: 'production' }, - ]); - - expect(apiResponse.assignments).toEqual([ - { status: 404, result: `Beat ${nonExistentBeatId} not found` }, - ]); - }); - - it('should return errors for non-existent tags', async () => { - const nonExistentTag = chance.word(); - - const apiResponse = await beatsLib.assignTagsToBeats(internalUser, [ - { beatId: 'bar', tag: nonExistentTag }, - ]); - - expect(apiResponse.assignments).toEqual([ - { status: 404, result: `Tag ${nonExistentTag} not found` }, - ]); - - const beat = beatsDB.find(b => b.id === 'bar') as any; - expect(beat).not.toHaveProperty('tags'); - }); - - it('should return errors for non-existent beats and tags', async () => { - const nonExistentBeatId = chance.word(); - const nonExistentTag = chance.word(); - - const apiResponse = await beatsLib.assignTagsToBeats(internalUser, [ - { beatId: nonExistentBeatId, tag: nonExistentTag }, - ]); - - expect(apiResponse.assignments).toEqual([ - { - result: `Beat ${nonExistentBeatId} and tag ${nonExistentTag} not found`, - status: 404, - }, - ]); - - const beat = beatsDB.find(b => b.id === 'bar') as any; - expect(beat).not.toHaveProperty('tags'); - }); - }); -}); diff --git a/x-pack/plugins/beats_management/server/lib/domains/__tests__/beats/enroll.test.ts b/x-pack/plugins/beats_management/server/lib/domains/__tests__/beats/enroll.test.ts deleted file mode 100644 index d115c49244c65..0000000000000 --- a/x-pack/plugins/beats_management/server/lib/domains/__tests__/beats/enroll.test.ts +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { MemoryBeatsAdapter } from '../../../adapters/beats/memory_beats_adapter'; -import { HapiBackendFrameworkAdapter } from '../../../adapters/framework/hapi_framework_adapter'; -import { MemoryTagsAdapter } from '../../../adapters/tags/memory_tags_adapter'; -import { MemoryTokensAdapter } from '../../../adapters/tokens/memory_tokens_adapter'; -import { BeatEnrollmentStatus } from '../../../lib'; - -import { BeatTag, CMBeat } from '../../../../../common/domain_types'; -import { TokenEnrollmentData } from '../../../adapters/tokens/adapter_types'; - -import { CMBeatsDomain } from '../../beats'; -import { CMTagsDomain } from '../../tags'; -import { CMTokensDomain } from '../../tokens'; - -import Chance from 'chance'; -import { sign as signToken } from 'jsonwebtoken'; -import { omit } from 'lodash'; -import moment from 'moment'; - -const seed = Date.now(); -const chance = new Chance(seed); - -const settings = { - encryptionKey: 'something_who_cares', - enrollmentTokensTtlInSeconds: 10 * 60, // 10 minutes -}; - -describe('Beats Domain Lib', () => { - let beatsLib: CMBeatsDomain; - let tokensLib: CMTokensDomain; - - let beatsDB: CMBeat[] = []; - let tagsDB: BeatTag[] = []; - let tokensDB: TokenEnrollmentData[] = []; - let validEnrollmentToken: string; - let beatId: string; - let beat: Partial; - - describe('enroll_beat', () => { - beforeEach(async () => { - validEnrollmentToken = chance.word(); - beatId = chance.word(); - - beatsDB = []; - tagsDB = []; - tokensDB = [ - { - expires_on: moment() - .add(4, 'hours') - .toJSON(), - token: validEnrollmentToken, - }, - ]; - - const version = - chance.integer({ min: 1, max: 10 }) + - '.' + - chance.integer({ min: 1, max: 10 }) + - '.' + - chance.integer({ min: 1, max: 10 }); - - beat = { - host_name: 'foo.bar.com', - type: 'filebeat', - version, - }; - - const framework = new HapiBackendFrameworkAdapter(settings); - - tokensLib = new CMTokensDomain(new MemoryTokensAdapter(tokensDB), { - framework, - }); - - const tagsLib = new CMTagsDomain(new MemoryTagsAdapter(tagsDB)); - - beatsLib = new CMBeatsDomain(new MemoryBeatsAdapter(beatsDB), { - tags: tagsLib, - tokens: tokensLib, - framework, - }); - }); - - it('should enroll beat, returning an access token', async () => { - const { token } = await tokensLib.getEnrollmentToken(validEnrollmentToken); - - expect(token).toEqual(validEnrollmentToken); - const { accessToken, status } = await beatsLib.enrollBeat( - validEnrollmentToken, - beatId, - '192.168.1.1', - omit(beat, 'enrollment_token') - ); - expect(status).toEqual(BeatEnrollmentStatus.Success); - - expect(beatsDB.length).toEqual(1); - expect(beatsDB[0]).toHaveProperty('host_ip'); - expect(beatsDB[0]).toHaveProperty('verified_on'); - - expect(accessToken).toEqual(beatsDB[0].access_token); - - await tokensLib.deleteEnrollmentToken(validEnrollmentToken); - - expect(tokensDB.length).toEqual(0); - }); - - it('should reject an invalid enrollment token', async () => { - const { token } = await tokensLib.getEnrollmentToken(chance.word()); - - expect(token).toEqual(null); - }); - - it('should reject an expired enrollment token', async () => { - const { token } = await tokensLib.getEnrollmentToken( - signToken({}, settings.encryptionKey, { - expiresIn: '-1min', - }) - ); - - expect(token).toEqual(null); - }); - - it('should delete the given enrollment token so it may not be reused', async () => { - expect(tokensDB[0].token).toEqual(validEnrollmentToken); - await tokensLib.deleteEnrollmentToken(validEnrollmentToken); - expect(tokensDB.length).toEqual(0); - - const { token } = await tokensLib.getEnrollmentToken(validEnrollmentToken); - - expect(token).toEqual(null); - }); - }); -}); diff --git a/x-pack/plugins/beats_management/server/lib/domains/__tests__/beats/remove_tags.test.ts b/x-pack/plugins/beats_management/server/lib/domains/__tests__/beats/remove_tags.test.ts deleted file mode 100644 index 63a98f5c054df..0000000000000 --- a/x-pack/plugins/beats_management/server/lib/domains/__tests__/beats/remove_tags.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { BeatTag, CMBeat } from '../../../../../common/domain_types'; -import { FrameworkInternalUser } from '../../../adapters/framework/adapter_types'; -import { compose } from '../../../compose/testing'; -import { CMServerLibs } from '../../../lib'; - -const internalUser: FrameworkInternalUser = { kind: 'internal' }; - -describe('Beats Domain Lib', () => { - let libs: CMServerLibs; - let beatsDB: Array> = []; - let tagsDB: BeatTag[] = []; - - describe('remove_tags_from_beats', () => { - beforeEach(async () => { - beatsDB = [ - { - access_token: '9a6c99ae0fd84b068819701169cd8a4b', - active: true, - enrollment_token: '123kuil;4', - host_ip: '1.2.3.4', - host_name: 'foo.bar.com', - id: 'qux', - type: 'filebeat', - }, - { - access_token: '188255eb560a4448b72656c5e99cae6f', - active: true, - enrollment_token: '12fghjyu34', - host_ip: '22.33.11.44', - host_name: 'baz.bar.com', - id: 'baz', - type: 'metricbeat', - }, - { - access_token: '93c4a4dd08564c189a7ec4e4f046b975', - active: true, - enrollment_token: '12nfhgj34', - host_ip: '1.2.3.4', - host_name: 'foo.bar.com', - id: 'foo', - tags: ['production', 'qa'], - type: 'metricbeat', - verified_on: '2018-05-15T16:25:38.924Z', - }, - { - access_token: '3c4a4dd08564c189a7ec4e4f046b9759', - active: true, - - enrollment_token: '123sfd4', - host_ip: '11.22.33.44', - host_name: 'foo.com', - id: 'bar', - type: 'filebeat', - }, - ]; - tagsDB = [ - { - configuration_blocks: [], - id: 'production', - last_updated: new Date(), - }, - { - configuration_blocks: [], - id: 'development', - last_updated: new Date(), - }, - { - configuration_blocks: [], - id: 'qa', - last_updated: new Date(), - }, - ]; - - libs = compose({ - tagsDB, - beatsDB, - }); - }); - - it('should remove a single tag from a single beat', async () => { - const apiResponse = await libs.beats.removeTagsFromBeats(internalUser, [ - { beatId: 'foo', tag: 'production' }, - ]); - - expect(apiResponse.removals).toEqual([{ status: 200, result: 'updated' }]); - // @ts-ignore - expect(beatsDB.find(b => b.id === 'foo').tags).toEqual(['qa']); - }); - - it('should remove a single tag from a multiple beats', async () => { - const apiResponse = await libs.beats.removeTagsFromBeats(internalUser, [ - { beatId: 'foo', tag: 'development' }, - { beatId: 'bar', tag: 'development' }, - ]); - - expect(apiResponse.removals).toEqual([ - { status: 200, result: 'updated' }, - { status: 200, result: 'updated' }, - ]); - - // @ts-ignore - expect(beatsDB.find(b => b.id === 'foo').tags).toEqual(['production', 'qa']); - expect(beatsDB.find(b => b.id === 'bar')).not.toHaveProperty('tags'); - }); - }); -}); diff --git a/x-pack/plugins/beats_management/server/lib/domains/__tests__/beats/update.test.ts b/x-pack/plugins/beats_management/server/lib/domains/__tests__/beats/update.test.ts deleted file mode 100644 index 74f747374e755..0000000000000 --- a/x-pack/plugins/beats_management/server/lib/domains/__tests__/beats/update.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import Chance from 'chance'; -import { BeatTag, CMBeat } from '../../../../../common/domain_types'; -import { MemoryBeatsAdapter } from '../../../adapters/beats/memory_beats_adapter'; -import { HapiBackendFrameworkAdapter } from '../../../adapters/framework/hapi_framework_adapter'; -import { MemoryTagsAdapter } from '../../../adapters/tags/memory_tags_adapter'; -import { TokenEnrollmentData } from '../../../adapters/tokens/adapter_types'; -import { MemoryTokensAdapter } from '../../../adapters/tokens/memory_tokens_adapter'; -import { CMBeatsDomain } from '../../beats'; -import { CMTagsDomain } from '../../tags'; -import { CMTokensDomain } from '../../tokens'; - -const seed = Date.now(); -const chance = new Chance(seed); - -const settings = { - encryptionKey: `it's_a_secret`, - enrollmentTokensTtlInSeconds: 10 * 60, // 10 minutes -}; - -describe('Beats Domain lib', () => { - describe('update_beat', () => { - let beatsLib: CMBeatsDomain; - let tokensLib: CMTokensDomain; - let token: TokenEnrollmentData; - let beatsDB: CMBeat[] = []; - let tagsDB: BeatTag[] = []; - let tokensDB: TokenEnrollmentData[]; - let beatId: string; - let beat: Partial; - - const getBeatsLib = async () => { - const framework = new HapiBackendFrameworkAdapter(settings); - - tokensLib = new CMTokensDomain(new MemoryTokensAdapter(tokensDB), { framework }); - const tagsLib = new CMTagsDomain(new MemoryTagsAdapter(tagsDB)); - - beatsLib = new CMBeatsDomain(new MemoryBeatsAdapter(beatsDB), { - framework, - tags: tagsLib, - tokens: tokensLib, - }); - - await tokensLib.createEnrollmentTokens(framework.internalUser, 1); - token = tokensDB[0]; - }; - - beforeEach(async () => { - beatId = chance.word(); - beat = { - host_name: 'foo.bar.com', - type: 'filebeat', - version: '6.4.0', - }; - beatsDB = []; - tagsDB = []; - tokensDB = []; - - getBeatsLib(); - }); - - it('should return a not-found message if beat does not exist', async () => { - const tokenString = token.token || ''; - const result = await beatsLib.update(tokenString, beatId, beat); - - expect(result).toBe('beat-not-found'); - }); - - it('should return an invalid message if token validation fails', async () => { - const beatToFind: CMBeat = { - id: beatId, - config_status: 'OK', - enrollment_token: '', - active: true, - access_token: token.token || '', - type: 'filebeat', - host_ip: 'localhost', - host_name: 'foo.bar.com', - }; - beatsDB = [beatToFind]; - - getBeatsLib(); - - const result = await beatsLib.update('something_invalid', beatId, beat); - - expect(result).toBe('invalid-access-token'); - }); - - it('should update the beat when a valid token is provided', async () => { - const beatToFind: CMBeat = { - id: beatId, - config_status: 'OK', - enrollment_token: '', - active: true, - access_token: token.token || '', - type: 'metricbeat', - host_ip: 'localhost', - host_name: 'bar.foo.com', - version: '6.3.5', - }; - beatsDB = [beatToFind]; - getBeatsLib(); - // @ts-ignore - await beatsLib.update(token, beatId, beat); - expect(beatsDB).toHaveLength(1); - const updatedBeat = beatsDB[0]; - expect(updatedBeat.id).toBe(beatId); - expect(updatedBeat.host_name).toBe('foo.bar.com'); - expect(updatedBeat.version).toBe('6.4.0'); - expect(updatedBeat.type).toBe('filebeat'); - }); - }); -}); diff --git a/x-pack/plugins/beats_management/server/lib/domains/__tests__/tokens.test.ts b/x-pack/plugins/beats_management/server/lib/domains/__tests__/tokens.test.ts deleted file mode 100644 index 91c504cd9f503..0000000000000 --- a/x-pack/plugins/beats_management/server/lib/domains/__tests__/tokens.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { HapiBackendFrameworkAdapter } from '../../adapters/framework/hapi_framework_adapter'; -import { TokenEnrollmentData } from '../../adapters/tokens/adapter_types'; -import { MemoryTokensAdapter } from '../../adapters/tokens/memory_tokens_adapter'; -import { CMTokensDomain } from '../tokens'; - -import Chance from 'chance'; -import moment from 'moment'; -import { BackendFrameworkAdapter } from '../../adapters/framework/adapter_types'; - -const seed = Date.now(); -const chance = new Chance(seed); - -const settings = { - encryptionKey: 'something_who_cares', - enrollmentTokensTtlInSeconds: 10 * 60, // 10 minutes -}; - -describe('Token Domain Lib', () => { - let tokensLib: CMTokensDomain; - let tokensDB: TokenEnrollmentData[] = []; - let framework: BackendFrameworkAdapter; - - beforeEach(async () => { - tokensDB = []; - framework = new HapiBackendFrameworkAdapter(settings); - - tokensLib = new CMTokensDomain(new MemoryTokensAdapter(tokensDB), { - framework, - }); - }); - - it('should generate webtokens with a qty of 1', async () => { - const tokens = await tokensLib.createEnrollmentTokens(framework.internalUser, 1); - - expect(tokens.length).toBe(1); - - expect(typeof tokens[0]).toBe('string'); - }); - - it('should create the specified number of tokens', async () => { - const numTokens = chance.integer({ min: 1, max: 20 }); - const tokensFromApi = await tokensLib.createEnrollmentTokens(framework.internalUser, numTokens); - - expect(tokensFromApi.length).toEqual(numTokens); - expect(tokensFromApi).toEqual(tokensDB.map((t: TokenEnrollmentData) => t.token)); - }); - - it('should set token expiration to 10 minutes from now by default', async () => { - await tokensLib.createEnrollmentTokens(framework.internalUser, 1); - - const token = tokensDB[0]; - - // We do a fuzzy check to see if the token expires between 9 and 10 minutes - // from now because a bit of time has elapsed been the creation of the - // tokens and this check. - const tokenExpiresOn = moment(token.expires_on).valueOf(); - - // Because sometimes the test runs so fast it it equal, and we dont use expect.js version that has toBeLessThanOrEqualTo - const tenMinutesFromNow = moment() - .add('10', 'minutes') - .add('1', 'seconds') - .valueOf(); - - const almostTenMinutesFromNow = moment(tenMinutesFromNow) - .subtract('2', 'seconds') - .valueOf(); - expect(tokenExpiresOn).toBeLessThan(tenMinutesFromNow); - expect(tokenExpiresOn).toBeGreaterThan(almostTenMinutesFromNow); - }); -}); diff --git a/x-pack/plugins/beats_management/server/lib/framework.ts b/x-pack/plugins/beats_management/server/lib/framework.ts new file mode 100644 index 0000000000000..3a79afa1c1ef7 --- /dev/null +++ b/x-pack/plugins/beats_management/server/lib/framework.ts @@ -0,0 +1,104 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import Boom from 'boom'; +import { difference } from 'lodash'; +import { FrameworkRouteHandler } from './adapters/framework/adapter_types'; +import { FrameworkRequest } from './adapters/framework/adapter_types'; +import { + BackendFrameworkAdapter, + FrameworkResponse, + FrameworkRouteOptions, +} from './adapters/framework/adapter_types'; + +export class BackendFrameworkLib { + public exposeStaticDir = this.adapter.exposeStaticDir; + public internalUser = this.adapter.internalUser; + constructor(private readonly adapter: BackendFrameworkAdapter) { + this.validateConfig(); + } + + public registerRoute< + RouteRequest extends FrameworkRequest, + RouteResponse extends FrameworkResponse + >(route: FrameworkRouteOptions) { + this.adapter.registerRoute({ + ...route, + handler: this.wrapRouteWithSecurity( + route.handler, + route.licenseRequired || [], + route.requiredRoles + ), + }); + } + + public getSetting(setting: 'encryptionKey'): string; + public getSetting(setting: 'enrollmentTokensTtlInSeconds'): number; + public getSetting(setting: 'defaultUserRoles'): string[]; + public getSetting( + setting: 'encryptionKey' | 'enrollmentTokensTtlInSeconds' | 'defaultUserRoles' + ) { + return this.adapter.getSetting(`xpack.beats.${setting}`); + } + + /** + * Expired `null` happens when we have no xpack info + */ + get license() { + return { + type: this.adapter.info ? this.adapter.info.license.type : 'unknown', + expired: this.adapter.info ? this.adapter.info.license.expired : null, + }; + } + + get securityIsEnabled() { + return this.adapter.info ? this.adapter.info.security.enabled : false; + } + + private validateConfig() { + const encryptionKey = this.adapter.getSetting('xpack.beats.encryptionKey'); + + if (!encryptionKey) { + this.adapter.log( + 'Using a default encryption key for xpack.beats.encryptionKey. It is recommended that you set xpack.beats.encryptionKey in kibana.yml with a unique token' + ); + } + } + + private wrapRouteWithSecurity( + handler: FrameworkRouteHandler, + requiredLicense: string[], + requiredRoles?: string[] + ) { + return async (request: FrameworkRequest, h: any) => { + if ( + requiredLicense.length > 0 && + (this.license.expired || !requiredLicense.includes(this.license.type)) + ) { + return Boom.forbidden( + `Your ${ + this.license + } license does not support this API or is expired. Please upgrade your license.` + ); + } + + if (requiredRoles) { + if (request.user.kind !== 'authenticated') { + return h.response().code(403); + } + + if ( + request.user.kind === 'authenticated' && + !request.user.roles.includes('superuser') && + difference(requiredRoles, request.user.roles).length !== 0 + ) { + return h.response().code(403); + } + } + return await handler(request, h); + }; + } +} diff --git a/x-pack/plugins/beats_management/server/lib/domains/tags.ts b/x-pack/plugins/beats_management/server/lib/tags.ts similarity index 89% rename from x-pack/plugins/beats_management/server/lib/domains/tags.ts rename to x-pack/plugins/beats_management/server/lib/tags.ts index 79ff2007d1160..01ad2e9ee0265 100644 --- a/x-pack/plugins/beats_management/server/lib/domains/tags.ts +++ b/x-pack/plugins/beats_management/server/lib/tags.ts @@ -5,12 +5,12 @@ */ import { intersection, uniq, values } from 'lodash'; -import { UNIQUENESS_ENFORCING_TYPES } from '../../../common/constants'; -import { ConfigurationBlock } from '../../../common/domain_types'; -import { FrameworkUser } from '../adapters/framework/adapter_types'; +import { UNIQUENESS_ENFORCING_TYPES } from '../../common/constants'; +import { ConfigurationBlock } from '../../common/domain_types'; +import { FrameworkUser } from './adapters/framework/adapter_types'; -import { entries } from '../../utils/polyfills'; -import { CMTagsAdapter } from '../adapters/tags/adapter_types'; +import { entries } from '../utils/polyfills'; +import { CMTagsAdapter } from './adapters/tags/adapter_types'; export class CMTagsDomain { constructor(private readonly adapter: CMTagsAdapter) {} diff --git a/x-pack/plugins/beats_management/server/lib/domains/tokens.ts b/x-pack/plugins/beats_management/server/lib/tokens.ts similarity index 81% rename from x-pack/plugins/beats_management/server/lib/domains/tokens.ts rename to x-pack/plugins/beats_management/server/lib/tokens.ts index 529a526bea75d..c6c1a06985d8f 100644 --- a/x-pack/plugins/beats_management/server/lib/domains/tokens.ts +++ b/x-pack/plugins/beats_management/server/lib/tokens.ts @@ -7,24 +7,27 @@ import { timingSafeEqual } from 'crypto'; import { sign as signToken, verify as verifyToken } from 'jsonwebtoken'; import moment from 'moment'; import uuid from 'uuid'; -import { BackendFrameworkAdapter } from '../adapters/framework/adapter_types'; -import { FrameworkUser } from '../adapters/framework/adapter_types'; -import { CMTokensAdapter } from '../adapters/tokens/adapter_types'; +import { FrameworkUser } from './adapters/framework/adapter_types'; +import { CMTokensAdapter } from './adapters/tokens/adapter_types'; +import { CMServerLibs } from './types'; const RANDOM_TOKEN_1 = 'b48c4bda384a40cb91c6eb9b8849e77f'; const RANDOM_TOKEN_2 = '80a3819e3cd64f4399f1d4886be7a08b'; export class CMTokensDomain { private adapter: CMTokensAdapter; - private framework: BackendFrameworkAdapter; + private framework: CMServerLibs['framework']; - constructor(adapter: CMTokensAdapter, libs: { framework: BackendFrameworkAdapter }) { + constructor(adapter: CMTokensAdapter, libs: { framework: CMServerLibs['framework'] }) { this.adapter = adapter; this.framework = libs.framework; } public async getEnrollmentToken(enrollmentToken: string) { - const fullToken = await this.adapter.getEnrollmentToken(enrollmentToken); + const fullToken = await this.adapter.getEnrollmentToken( + this.framework.internalUser, + enrollmentToken + ); if (!fullToken) { return { @@ -48,7 +51,7 @@ export class CMTokensDomain { } public async deleteEnrollmentToken(enrollmentToken: string) { - return await this.adapter.deleteEnrollmentToken(enrollmentToken); + return await this.adapter.deleteEnrollmentToken(this.framework.internalUser, enrollmentToken); } public verifyToken(recivedToken: string, token2: string, decode = true) { @@ -56,7 +59,7 @@ export class CMTokensDomain { let expired = false; if (decode) { - const enrollmentTokenSecret = this.framework.getSetting('xpack.beats.encryptionKey'); + const enrollmentTokenSecret = this.framework.getSetting('encryptionKey'); try { verifyToken(recivedToken, enrollmentTokenSecret); @@ -96,7 +99,7 @@ export class CMTokensDomain { } public generateAccessToken() { - const enrollmentTokenSecret = this.framework.getSetting('xpack.beats.encryptionKey'); + const enrollmentTokenSecret = this.framework.getSetting('encryptionKey'); const tokenData = { created: moment().toJSON(), @@ -111,9 +114,7 @@ export class CMTokensDomain { numTokens: number = 1 ): Promise { const tokens = []; - const enrollmentTokensTtlInSeconds = this.framework.getSetting( - 'xpack.beats.enrollmentTokensTtlInSeconds' - ); + const enrollmentTokensTtlInSeconds = this.framework.getSetting('enrollmentTokensTtlInSeconds'); const enrollmentTokenExpiration = moment() .add(enrollmentTokensTtlInSeconds, 'seconds') diff --git a/x-pack/plugins/beats_management/server/lib/lib.ts b/x-pack/plugins/beats_management/server/lib/types.ts similarity index 63% rename from x-pack/plugins/beats_management/server/lib/lib.ts rename to x-pack/plugins/beats_management/server/lib/types.ts index b8d51374741fe..d9f2a922ebb34 100644 --- a/x-pack/plugins/beats_management/server/lib/lib.ts +++ b/x-pack/plugins/beats_management/server/lib/types.ts @@ -5,25 +5,23 @@ */ import { DatabaseAdapter } from './adapters/database/adapter_types'; -import { BackendFrameworkAdapter, FrameworkUser } from './adapters/framework/adapter_types'; +import { FrameworkUser } from './adapters/framework/adapter_types'; -import { CMBeatsDomain } from './domains/beats'; -import { CMTagsDomain } from './domains/tags'; -import { CMTokensDomain } from './domains/tokens'; +import { CMBeatsDomain } from './beats'; +import { BackendFrameworkLib } from './framework'; +import { CMTagsDomain } from './tags'; +import { CMTokensDomain } from './tokens'; export type UserOrToken = FrameworkUser | string; -export interface CMDomainLibs { +export interface CMServerLibs { + framework: BackendFrameworkLib; + database?: DatabaseAdapter; beats: CMBeatsDomain; tags: CMTagsDomain; tokens: CMTokensDomain; } -export interface CMServerLibs extends CMDomainLibs { - framework: BackendFrameworkAdapter; - database?: DatabaseAdapter; -} - export enum BeatEnrollmentStatus { Success = 'Success', ExpiredEnrollmentToken = 'Expired enrollment token', diff --git a/x-pack/plugins/beats_management/server/management_server.ts b/x-pack/plugins/beats_management/server/management_server.ts index e278e6ff735c1..679f8f3423867 100644 --- a/x-pack/plugins/beats_management/server/management_server.ts +++ b/x-pack/plugins/beats_management/server/management_server.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { CMServerLibs } from './lib/lib'; +import { CMServerLibs } from './lib/types'; import { createGetBeatConfigurationRoute } from './rest_api/beats/configuration'; import { createBeatEnrollmentRoute } from './rest_api/beats/enroll'; import { createGetBeatRoute } from './rest_api/beats/get'; diff --git a/x-pack/plugins/beats_management/server/rest_api/__tests__/beats_assignments.test.ts b/x-pack/plugins/beats_management/server/rest_api/__tests__/beats_assignments.test.ts index 331403e8145c3..e427c9b0b1115 100644 --- a/x-pack/plugins/beats_management/server/rest_api/__tests__/beats_assignments.test.ts +++ b/x-pack/plugins/beats_management/server/rest_api/__tests__/beats_assignments.test.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { CMServerLibs } from '../../lib/lib'; +import { CMServerLibs } from '../../lib/types'; import { HapiBackendFrameworkAdapter } from './../../lib/adapters/framework/hapi_framework_adapter'; import { testHarnes } from './test_harnes'; @@ -19,10 +19,8 @@ describe('assign_tags_to_beats', () => { beforeEach(async () => await testHarnes.loadData()); it('should add a single tag to a single beat', async () => { - const { - result, - statusCode, - } = await (serverLibs.framework as HapiBackendFrameworkAdapter).injectRequstForTesting({ + const { result, statusCode } = await ((serverLibs.framework as any) + .adapter as HapiBackendFrameworkAdapter).injectRequstForTesting({ method: 'POST', url: '/api/beats/agents_tags/assignments', headers: { @@ -39,10 +37,8 @@ describe('assign_tags_to_beats', () => { }); it('should not re-add an existing tag to a beat', async () => { - const { - result, - statusCode, - } = await (serverLibs.framework as HapiBackendFrameworkAdapter).injectRequstForTesting({ + const { result, statusCode } = await ((serverLibs.framework as any) + .adapter as HapiBackendFrameworkAdapter).injectRequstForTesting({ method: 'POST', url: '/api/beats/agents_tags/assignments', headers: { @@ -70,10 +66,8 @@ describe('assign_tags_to_beats', () => { }); it('should add a single tag to a multiple beats', async () => { - const { - result, - statusCode, - } = await (serverLibs.framework as HapiBackendFrameworkAdapter).injectRequstForTesting({ + const { result, statusCode } = await ((serverLibs.framework as any) + .adapter as HapiBackendFrameworkAdapter).injectRequstForTesting({ method: 'POST', url: '/api/beats/agents_tags/assignments', headers: { @@ -114,10 +108,8 @@ describe('assign_tags_to_beats', () => { }); it('should add multiple tags to a single beat', async () => { - const { - result, - statusCode, - } = await (serverLibs.framework as HapiBackendFrameworkAdapter).injectRequstForTesting({ + const { result, statusCode } = await ((serverLibs.framework as any) + .adapter as HapiBackendFrameworkAdapter).injectRequstForTesting({ method: 'POST', url: '/api/beats/agents_tags/assignments', headers: { diff --git a/x-pack/plugins/beats_management/server/rest_api/__tests__/test_harnes.ts b/x-pack/plugins/beats_management/server/rest_api/__tests__/test_harnes.ts index ed93ffbe36e1e..590ce0bd7b287 100644 --- a/x-pack/plugins/beats_management/server/rest_api/__tests__/test_harnes.ts +++ b/x-pack/plugins/beats_management/server/rest_api/__tests__/test_harnes.ts @@ -13,7 +13,7 @@ import { promisify } from 'util'; import { BeatTag, CMBeat } from '../../../common/domain_types'; import { TokenEnrollmentData } from '../../lib/adapters/tokens/adapter_types'; import { compose } from '../../lib/compose/testing'; -import { CMServerLibs } from '../../lib/lib'; +import { CMServerLibs } from '../../lib/types'; import { initManagementServer } from './../../management_server'; const readFileAsync = promisify(readFile); diff --git a/x-pack/plugins/beats_management/server/rest_api/beats/configuration.ts b/x-pack/plugins/beats_management/server/rest_api/beats/configuration.ts index a24d6dee05132..d342a293c97ea 100644 --- a/x-pack/plugins/beats_management/server/rest_api/beats/configuration.ts +++ b/x-pack/plugins/beats_management/server/rest_api/beats/configuration.ts @@ -6,7 +6,7 @@ import Joi from 'joi'; import { omit } from 'lodash'; import { BeatTag, CMBeat, ConfigurationBlock } from '../../../common/domain_types'; -import { CMServerLibs } from '../../lib/lib'; +import { CMServerLibs } from '../../lib/types'; import { wrapEsError } from '../../utils/error_wrappers'; import { ReturnedConfigurationBlock } from './../../../common/domain_types'; diff --git a/x-pack/plugins/beats_management/server/rest_api/beats/enroll.ts b/x-pack/plugins/beats_management/server/rest_api/beats/enroll.ts index 266e3baa3829f..9c2b69908febd 100644 --- a/x-pack/plugins/beats_management/server/rest_api/beats/enroll.ts +++ b/x-pack/plugins/beats_management/server/rest_api/beats/enroll.ts @@ -5,16 +5,16 @@ */ import Joi from 'joi'; import { omit } from 'lodash'; +import { REQUIRED_LICENSES } from 'x-pack/plugins/beats_management/common/constants'; import { FrameworkRequest } from '../../lib/adapters/framework/adapter_types'; -import { CMServerLibs } from '../../lib/lib'; -import { BeatEnrollmentStatus } from '../../lib/lib'; +import { BeatEnrollmentStatus, CMServerLibs } from '../../lib/types'; import { wrapEsError } from '../../utils/error_wrappers'; -// TODO: write to Kibana audit log file +// TODO: write to Kibana audit log file https://github.com/elastic/kibana/issues/26024 export const createBeatEnrollmentRoute = (libs: CMServerLibs) => ({ method: 'POST', path: '/api/beats/agent/{beatId}', - licenseRequired: true, + licenseRequired: REQUIRED_LICENSES, config: { auth: false, validate: { @@ -61,7 +61,7 @@ export const createBeatEnrollmentRoute = (libs: CMServerLibs) => ({ return h.response({ access_token: accessToken }).code(201); } } catch (err) { - // TODO move this to kibana route thing in adapter + // FIXME move this to kibana route thing in adapter return wrapEsError(err); } }, diff --git a/x-pack/plugins/beats_management/server/rest_api/beats/get.ts b/x-pack/plugins/beats_management/server/rest_api/beats/get.ts index 49fac5e9f009c..41415521c7bca 100644 --- a/x-pack/plugins/beats_management/server/rest_api/beats/get.ts +++ b/x-pack/plugins/beats_management/server/rest_api/beats/get.ts @@ -5,7 +5,7 @@ */ import { CMBeat } from '../../../common/domain_types'; -import { CMServerLibs } from '../../lib/lib'; +import { CMServerLibs } from '../../lib/types'; import { wrapEsError } from '../../utils/error_wrappers'; export const createGetBeatRoute = (libs: CMServerLibs) => ({ diff --git a/x-pack/plugins/beats_management/server/rest_api/beats/list.ts b/x-pack/plugins/beats_management/server/rest_api/beats/list.ts index 6dfec291f602b..1bf96fba96f98 100644 --- a/x-pack/plugins/beats_management/server/rest_api/beats/list.ts +++ b/x-pack/plugins/beats_management/server/rest_api/beats/list.ts @@ -5,15 +5,18 @@ */ import * as Joi from 'joi'; +import { REQUIRED_LICENSES } from 'x-pack/plugins/beats_management/common/constants'; import { CMBeat } from '../../../common/domain_types'; import { FrameworkRequest } from '../../lib/adapters/framework/adapter_types'; -import { CMServerLibs } from '../../lib/lib'; +import { CMServerLibs } from '../../lib/types'; import { wrapEsError } from '../../utils/error_wrappers'; export const createListAgentsRoute = (libs: CMServerLibs) => ({ method: 'GET', path: '/api/beats/agents/{listByAndValue*}', requiredRoles: ['beats_admin'], + licenseRequired: REQUIRED_LICENSES, + validate: { headers: Joi.object({ 'kbn-beats-enrollment-token': Joi.string().required(), @@ -24,7 +27,6 @@ export const createListAgentsRoute = (libs: CMServerLibs) => ({ ESQuery: Joi.string(), }), }, - licenseRequired: true, handler: async (request: FrameworkRequest) => { const listByAndValueParts = request.params.listByAndValue ? request.params.listByAndValue.split('/') @@ -56,7 +58,7 @@ export const createListAgentsRoute = (libs: CMServerLibs) => ({ return { beats }; } catch (err) { - // TODO move this to kibana route thing in adapter + // FIXME move this to kibana route thing in adapter return wrapEsError(err); } }, diff --git a/x-pack/plugins/beats_management/server/rest_api/beats/tag_assignment.ts b/x-pack/plugins/beats_management/server/rest_api/beats/tag_assignment.ts index 91cda6e9524f9..cc40e3d8ae642 100644 --- a/x-pack/plugins/beats_management/server/rest_api/beats/tag_assignment.ts +++ b/x-pack/plugins/beats_management/server/rest_api/beats/tag_assignment.ts @@ -8,14 +8,15 @@ import Joi from 'joi'; import { BeatsTagAssignment } from '../../../public/lib/adapters/beats/adapter_types'; import { FrameworkRequest } from '../../lib/adapters/framework/adapter_types'; -import { CMServerLibs } from '../../lib/lib'; +import { REQUIRED_LICENSES } from 'x-pack/plugins/beats_management/common/constants'; +import { CMServerLibs } from '../../lib/types'; import { wrapEsError } from '../../utils/error_wrappers'; -// TODO: write to Kibana audit log file +// TODO: write to Kibana audit log file https://github.com/elastic/kibana/issues/26024 export const createTagAssignmentsRoute = (libs: CMServerLibs) => ({ method: 'POST', path: '/api/beats/agents_tags/assignments', - licenseRequired: true, + licenseRequired: REQUIRED_LICENSES, requiredRoles: ['beats_admin'], config: { validate: { diff --git a/x-pack/plugins/beats_management/server/rest_api/beats/tag_removal.ts b/x-pack/plugins/beats_management/server/rest_api/beats/tag_removal.ts index d1912d96fdcdb..b38cc43fd7e05 100644 --- a/x-pack/plugins/beats_management/server/rest_api/beats/tag_removal.ts +++ b/x-pack/plugins/beats_management/server/rest_api/beats/tag_removal.ts @@ -5,15 +5,16 @@ */ import Joi from 'joi'; +import { REQUIRED_LICENSES } from 'x-pack/plugins/beats_management/common/constants'; import { FrameworkRequest } from '../../lib/adapters/framework/adapter_types'; -import { CMServerLibs } from '../../lib/lib'; +import { CMServerLibs } from '../../lib/types'; import { wrapEsError } from '../../utils/error_wrappers'; -// TODO: write to Kibana audit log file +// TODO: write to Kibana audit log file https://github.com/elastic/kibana/issues/26024 export const createTagRemovalsRoute = (libs: CMServerLibs) => ({ method: 'POST', path: '/api/beats/agents_tags/removals', - licenseRequired: true, + licenseRequired: REQUIRED_LICENSES, requiredRoles: ['beats_admin'], config: { validate: { diff --git a/x-pack/plugins/beats_management/server/rest_api/beats/update.ts b/x-pack/plugins/beats_management/server/rest_api/beats/update.ts index 64e08330734d0..2e1dc51f142fd 100644 --- a/x-pack/plugins/beats_management/server/rest_api/beats/update.ts +++ b/x-pack/plugins/beats_management/server/rest_api/beats/update.ts @@ -5,15 +5,16 @@ */ import Joi from 'joi'; +import { REQUIRED_LICENSES } from 'x-pack/plugins/beats_management/common/constants'; import { FrameworkRequest } from '../../lib/adapters/framework/adapter_types'; -import { CMServerLibs } from '../../lib/lib'; +import { CMServerLibs } from '../../lib/types'; import { wrapEsError } from '../../utils/error_wrappers'; -// TODO: write to Kibana audit log file (include who did the verification as well) +// TODO: write to Kibana audit log file (include who did the verification as well) https://github.com/elastic/kibana/issues/26024 export const createBeatUpdateRoute = (libs: CMServerLibs) => ({ method: 'PUT', path: '/api/beats/agent/{beatId}', - licenseRequired: true, + licenseRequired: REQUIRED_LICENSES, requiredRoles: ['beats_admin'], config: { validate: { diff --git a/x-pack/plugins/beats_management/server/rest_api/tags/delete.ts b/x-pack/plugins/beats_management/server/rest_api/tags/delete.ts index 0f138ecf04a14..a533a1d2bace6 100644 --- a/x-pack/plugins/beats_management/server/rest_api/tags/delete.ts +++ b/x-pack/plugins/beats_management/server/rest_api/tags/delete.ts @@ -4,14 +4,15 @@ * you may not use this file except in compliance with the Elastic License. */ -import { CMServerLibs } from '../../lib/lib'; +import { REQUIRED_LICENSES } from 'x-pack/plugins/beats_management/common/constants'; +import { CMServerLibs } from '../../lib/types'; import { wrapEsError } from '../../utils/error_wrappers'; export const createDeleteTagsWithIdsRoute = (libs: CMServerLibs) => ({ method: 'DELETE', path: '/api/beats/tags/{tagIds}', requiredRoles: ['beats_admin'], - licenseRequired: true, + licenseRequired: REQUIRED_LICENSES, handler: async (request: any) => { const tagIdString: string = request.params.tagIds; const tagIds = tagIdString.split(',').filter((id: string) => id.length > 0); diff --git a/x-pack/plugins/beats_management/server/rest_api/tags/get.ts b/x-pack/plugins/beats_management/server/rest_api/tags/get.ts index 36d00208066c2..c7f76dbd989c9 100644 --- a/x-pack/plugins/beats_management/server/rest_api/tags/get.ts +++ b/x-pack/plugins/beats_management/server/rest_api/tags/get.ts @@ -4,15 +4,17 @@ * you may not use this file except in compliance with the Elastic License. */ +import { REQUIRED_LICENSES } from 'x-pack/plugins/beats_management/common/constants'; import { BeatTag } from '../../../common/domain_types'; -import { CMServerLibs } from '../../lib/lib'; +import { CMServerLibs } from '../../lib/types'; import { wrapEsError } from '../../utils/error_wrappers'; +import { FrameworkRouteOptions } from './../../lib/adapters/framework/adapter_types'; -export const createGetTagsWithIdsRoute = (libs: CMServerLibs) => ({ +export const createGetTagsWithIdsRoute = (libs: CMServerLibs): FrameworkRouteOptions => ({ method: 'GET', path: '/api/beats/tags/{tagIds}', requiredRoles: ['beats_admin'], - licenseRequired: true, + licenseRequired: REQUIRED_LICENSES, handler: async (request: any) => { const tagIdString: string = request.params.tagIds; const tagIds = tagIdString.split(',').filter((id: string) => id.length > 0); diff --git a/x-pack/plugins/beats_management/server/rest_api/tags/list.ts b/x-pack/plugins/beats_management/server/rest_api/tags/list.ts index f255a627220d3..91bf7f92b9782 100644 --- a/x-pack/plugins/beats_management/server/rest_api/tags/list.ts +++ b/x-pack/plugins/beats_management/server/rest_api/tags/list.ts @@ -5,14 +5,16 @@ */ import * as Joi from 'joi'; +import { REQUIRED_LICENSES } from 'x-pack/plugins/beats_management/common/constants'; import { BeatTag } from '../../../common/domain_types'; -import { CMServerLibs } from '../../lib/lib'; +import { CMServerLibs } from '../../lib/types'; import { wrapEsError } from '../../utils/error_wrappers'; export const createListTagsRoute = (libs: CMServerLibs) => ({ method: 'GET', path: '/api/beats/tags', requiredRoles: ['beats_admin'], + licenseRequired: REQUIRED_LICENSES, validate: { headers: Joi.object({ 'kbn-beats-enrollment-token': Joi.string().required(), @@ -23,7 +25,6 @@ export const createListTagsRoute = (libs: CMServerLibs) => ({ ESQuery: Joi.string(), }), }, - licenseRequired: true, handler: async (request: any) => { let tags: BeatTag[]; try { diff --git a/x-pack/plugins/beats_management/server/rest_api/tags/set.ts b/x-pack/plugins/beats_management/server/rest_api/tags/set.ts index 600eef42d90af..afc6e6b81538a 100644 --- a/x-pack/plugins/beats_management/server/rest_api/tags/set.ts +++ b/x-pack/plugins/beats_management/server/rest_api/tags/set.ts @@ -6,16 +6,16 @@ import Joi from 'joi'; import { get, values } from 'lodash'; -import { ConfigurationBlockTypes } from '../../../common/constants'; +import { ConfigurationBlockTypes, REQUIRED_LICENSES } from '../../../common/constants'; import { FrameworkRequest } from '../../lib/adapters/framework/adapter_types'; -import { CMServerLibs } from '../../lib/lib'; +import { CMServerLibs } from '../../lib/types'; import { wrapEsError } from '../../utils/error_wrappers'; // TODO: write to Kibana audit log file export const createSetTagRoute = (libs: CMServerLibs) => ({ method: 'PUT', path: '/api/beats/tag/{tag}', - licenseRequired: true, + licenseRequired: REQUIRED_LICENSES, requiredRoles: ['beats_admin'], config: { validate: { diff --git a/x-pack/plugins/beats_management/server/rest_api/tokens/create.ts b/x-pack/plugins/beats_management/server/rest_api/tokens/create.ts index 42604ced8a972..1b70bd3b3ad8f 100644 --- a/x-pack/plugins/beats_management/server/rest_api/tokens/create.ts +++ b/x-pack/plugins/beats_management/server/rest_api/tokens/create.ts @@ -6,8 +6,9 @@ import Joi from 'joi'; import { get } from 'lodash'; +import { REQUIRED_LICENSES } from 'x-pack/plugins/beats_management/common/constants'; import { FrameworkRequest } from '../../lib/adapters/framework/adapter_types'; -import { CMServerLibs } from '../../lib/lib'; +import { CMServerLibs } from '../../lib/types'; import { wrapEsError } from '../../utils/error_wrappers'; // TODO: write to Kibana audit log file @@ -15,7 +16,7 @@ const DEFAULT_NUM_TOKENS = 1; export const createTokensRoute = (libs: CMServerLibs) => ({ method: 'POST', path: '/api/beats/enrollment_tokens', - licenseRequired: true, + licenseRequired: REQUIRED_LICENSES, requiredRoles: ['beats_admin'], config: { validate: { diff --git a/x-pack/plugins/beats_management/server/utils/wrap_request.ts b/x-pack/plugins/beats_management/server/utils/wrap_request.ts index 83838eb12b335..57cf70a99a296 100644 --- a/x-pack/plugins/beats_management/server/utils/wrap_request.ts +++ b/x-pack/plugins/beats_management/server/utils/wrap_request.ts @@ -6,12 +6,11 @@ import { FrameworkRequest, - FrameworkWrappableRequest, + internalAuthData, + KibanaServerRequest, } from '../lib/adapters/framework/adapter_types'; -export const internalAuthData = Symbol('internalAuthData'); - -export function wrapRequest( +export function wrapRequest( req: InternalRequest ): FrameworkRequest { const { params, payload, query, headers, info } = req; diff --git a/x-pack/plugins/beats_management/wallaby.js b/x-pack/plugins/beats_management/wallaby.js index bb57d22afafb3..eb5652f154774 100644 --- a/x-pack/plugins/beats_management/wallaby.js +++ b/x-pack/plugins/beats_management/wallaby.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ const path = require('path'); -process.env.NODE_PATH = path.join(__dirname, '..', '..', 'node_modules'); +process.env.NODE_PATH = path.resolve(__dirname, '..', '..', '..', 'node_modules'); module.exports = function (wallaby) { return { @@ -23,7 +23,10 @@ module.exports = function (wallaby) { type: 'node', runner: 'node', }, - testFramework: 'jest', + testFramework: { + type: 'jest', + //path: jestPath, + }, compilers: { '**/*.ts?(x)': wallaby.compilers.typeScript({ typescript: require('typescript'), // eslint-disable-line @@ -38,7 +41,6 @@ module.exports = function (wallaby) { const path = require('path'); const kibanaDirectory = path.resolve(wallaby.localProjectDir, '..', '..', '..'); - wallaby.testFramework.configure({ rootDir: wallaby.localProjectDir, moduleNameMapper: { diff --git a/x-pack/test/functional/config.js b/x-pack/test/functional/config.js index 51432cff565f5..00fe02cbb7e07 100644 --- a/x-pack/test/functional/config.js +++ b/x-pack/test/functional/config.js @@ -49,16 +49,20 @@ import { RandomProvider, AceEditorProvider, GrokDebuggerProvider, - } from './services'; // the default export of config files must be a config provider // that returns an object with the projects config values export default async function ({ readConfigFile }) { - - const kibanaCommonConfig = await readConfigFile(require.resolve('../../../test/common/config.js')); - const kibanaFunctionalConfig = await readConfigFile(require.resolve('../../../test/functional/config.js')); - const kibanaAPITestsConfig = await readConfigFile(require.resolve('../../../test/api_integration/config.js')); + const kibanaCommonConfig = await readConfigFile( + require.resolve('../../../test/common/config.js') + ); + const kibanaFunctionalConfig = await readConfigFile( + require.resolve('../../../test/functional/config.js') + ); + const kibanaAPITestsConfig = await readConfigFile( + require.resolve('../../../test/api_integration/config.js') + ); return { // list paths to the files that contain your plugins tests @@ -132,10 +136,7 @@ export default async function ({ readConfigFile }) { esTestCluster: { license: 'trial', from: 'snapshot', - serverArgs: [ - 'xpack.license.self_generated.type=trial', - 'xpack.security.enabled=true', - ], + serverArgs: ['xpack.license.self_generated.type=trial', 'xpack.security.enabled=true'], }, kbnTestServer: { @@ -160,47 +161,47 @@ export default async function ({ readConfigFile }) { apps: { ...kibanaFunctionalConfig.get('apps'), login: { - pathname: '/login' + pathname: '/login', }, monitoring: { - pathname: '/app/monitoring' + pathname: '/app/monitoring', }, logstashPipelines: { pathname: '/app/kibana', - hash: '/management/logstash/pipelines' + hash: '/management/logstash/pipelines', }, graph: { pathname: '/app/graph', }, grokDebugger: { pathname: '/app/kibana', - hash: '/dev_tools/grokdebugger' + hash: '/dev_tools/grokdebugger', }, spaceSelector: { pathname: '/', }, infraOps: { - pathname: '/app/infra' + pathname: '/app/infra', }, canvas: { pathname: '/app/canvas', hash: '/', - } + }, }, // choose where esArchiver should load archives from esArchiver: { - directory: resolve(__dirname, 'es_archives') + directory: resolve(__dirname, 'es_archives'), }, // choose where screenshots should be saved screenshots: { - directory: resolve(__dirname, 'screenshots') + directory: resolve(__dirname, 'screenshots'), }, junit: { reportName: 'X-Pack Functional Tests', rootDirectory: resolve(__dirname, '../../'), - } + }, }; } diff --git a/yarn.lock b/yarn.lock index 0bb48abad29a7..c2c196472c3d8 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5963,6 +5963,11 @@ create-react-class@^15.5.2: loose-envify "^1.3.1" object-assign "^4.1.1" +create-react-context@^0.1.5: + version "0.1.6" + resolved "https://registry.yarnpkg.com/create-react-context/-/create-react-context-0.1.6.tgz#0f425931d907741127acc6e31acb4f9015dd9fdc" + integrity sha512-eCnYYEUEc5i32LHwpE/W7NlddOB9oHwsPaWtWzYtflNkkwa3IfindIcoXdVWs12zCbwaMCavKNu84EXogVIWHw== + cronstrue@^1.51.0: version "1.51.0" resolved "https://registry.yarnpkg.com/cronstrue/-/cronstrue-1.51.0.tgz#7a63153d61d940344049037628da38a60784c8e2" @@ -8877,6 +8882,11 @@ forwarded@~0.1.2: resolved "https://registry.yarnpkg.com/forwarded/-/forwarded-0.1.2.tgz#98c23dab1175657b8c0573e8ceccd91b0ff18c84" integrity sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ= +fp-ts@^1.0.0: + version "1.12.0" + resolved "https://registry.yarnpkg.com/fp-ts/-/fp-ts-1.12.0.tgz#d333310e4ac104cdcb6bea47908e381bb09978e7" + integrity sha512-fWwnAgVlTsV26Ruo9nx+fxNHIm6l1puE1VJ/C0XJ3nRQJJJIgRHYw6sigB3MuNFZL1o4fpGlhwFhcbxHK0RsOA== + fragment-cache@^0.2.1: version "0.2.1" resolved "https://registry.yarnpkg.com/fragment-cache/-/fragment-cache-0.2.1.tgz#4290fad27f13e89be7f33799c6bc5a0abfff0d19" @@ -11086,6 +11096,13 @@ invert-kv@^2.0.0: resolved "https://registry.yarnpkg.com/invert-kv/-/invert-kv-2.0.0.tgz#7393f5afa59ec9ff5f67a27620d11c226e3eec02" integrity sha512-wPVv/y/QQ/Uiirj/vh3oP+1Ww+AWehmi1g5fFWGPF6IpCBCDVrhgHRMvrLfdYcwDh3QJbGXDW4JAuzxElLSqKA== +io-ts@^1.4.2: + version "1.4.2" + resolved "https://registry.yarnpkg.com/io-ts/-/io-ts-1.4.2.tgz#d3cb1ef7d7ba68d59af85d839a728aad7f4b1c28" + integrity sha512-U4uw8jjj8jYZip7zHgBj40GW0DpYdVi1i0J3anezp2ytYHDg7+cKc7iIFlIyCh+NLwMxzwu6OQ/b9S61KUjPGg== + dependencies: + fp-ts "^1.0.0" + ip-regex@^1.0.1: version "1.0.3" resolved "https://registry.yarnpkg.com/ip-regex/-/ip-regex-1.0.3.tgz#dc589076f659f419c222039a33316f1c7387effd" @@ -20821,6 +20838,13 @@ unset-value@^1.0.0: has-value "^0.3.1" isobject "^3.0.0" +unstated@^2.1.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/unstated/-/unstated-2.1.1.tgz#36b124dfb2e7a12d39d0bb9c46dfb6e51276e3a2" + integrity sha512-fORlTWMZxq7NuMJDxyIrrYIZKN7wEWYQ9SiaJfIRcSpsowr6Ph/JIfK2tgtXLW614JfPG/t5q9eEIhXRCf55xg== + dependencies: + create-react-context "^0.1.5" + untildify@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/untildify/-/untildify-2.1.0.tgz#17eb2807987f76952e9c0485fc311d06a826a2e0" From 5764dec8fc279a168ceea790acc25a9c6fe09235 Mon Sep 17 00:00:00 2001 From: Oliver Gupte Date: Fri, 7 Dec 2018 22:57:53 -0800 Subject: [PATCH 26/85] [APM] Transaction group agg size config (#26683) * [APM] Fixes #24204 by adding default configs to kibana.yml * [APM] fixes #25940 by adding APM config to control top transation group agg size * Revert the default configs added to kibana.yml and define joi validations for `xpack.apm.ui.transactionGroupBucketSize` * fix broken test for incorrect config * [APM] add docs entry for `xpack.apm.ui.transactionGroupBucketSize` --- docs/settings/apm-settings.asciidoc | 2 ++ x-pack/plugins/apm/index.js | 3 ++- .../apm/server/lib/transaction_groups/fetcher.test.ts | 9 ++++++++- .../plugins/apm/server/lib/transaction_groups/fetcher.ts | 2 +- 4 files changed, 13 insertions(+), 3 deletions(-) diff --git a/docs/settings/apm-settings.asciidoc b/docs/settings/apm-settings.asciidoc index 31ebe5ac6034e..cb454874276ab 100644 --- a/docs/settings/apm-settings.asciidoc +++ b/docs/settings/apm-settings.asciidoc @@ -17,6 +17,8 @@ xpack.apm.enabled:: Set to `false` to disabled the APM plugin {kib}. Defaults to xpack.apm.ui.enabled:: Set to `false` to hide the APM plugin {kib} from the menu. Defaults to `true`. +xpack.apm.ui.transactionGroupBucketSize:: Number of top transaction groups displayed in APM plugin in Kibana. Defaults to `100`. + apm_oss.indexPattern:: Index pattern is used for integrations with Machine Learning and Kuery Bar. It must match all apm indices. Defaults to `apm-*`. apm_oss.errorIndices:: Matcher for indices containing error documents. Defaults to `apm-*`. diff --git a/x-pack/plugins/apm/index.js b/x-pack/plugins/apm/index.js index 5337aa5817276..b9965ccac70ec 100644 --- a/x-pack/plugins/apm/index.js +++ b/x-pack/plugins/apm/index.js @@ -51,7 +51,8 @@ export function apm(kibana) { return Joi.object({ // display menu item ui: Joi.object({ - enabled: Joi.boolean().default(true) + enabled: Joi.boolean().default(true), + transactionGroupBucketSize: Joi.number().default(100) }).default(), // enable plugin diff --git a/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.test.ts b/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.test.ts index cfbffe77222f3..6dc8680a706c4 100644 --- a/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.test.ts +++ b/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.test.ts @@ -17,7 +17,14 @@ describe('transactionGroupsFetcher', () => { end: 1528977600000, client: clientSpy, config: { - get: () => 'myIndex' as any + get: jest.fn((key: string) => { + switch (key) { + case 'apm_oss.transactionIndices': + return 'myIndex'; + case 'xpack.apm.ui.transactionGroupBucketSize': + return 100; + } + }) } }; const bodyQuery = { my: 'bodyQuery' }; diff --git a/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.ts b/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.ts index ad0aa00d35bc9..eda72b750a7aa 100644 --- a/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.ts +++ b/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.ts @@ -53,7 +53,7 @@ export function transactionGroupsFetcher( terms: { field: `${TRANSACTION_NAME}.keyword`, order: { sum: 'desc' }, - size: 100 + size: config.get('xpack.apm.ui.transactionGroupBucketSize') }, aggs: { sample: { From 311a8bffb8aa5044d296267b550e1130d001fd28 Mon Sep 17 00:00:00 2001 From: Oliver Gupte Date: Fri, 7 Dec 2018 23:53:27 -0800 Subject: [PATCH 27/85] [APM] fixes #26784 by updateing import from a default to a named import (#26785) --- .../public/components/app/ErrorGroupDetails/DetailView/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/index.js b/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/index.js index 461df0cc66776..f0917077c1754 100644 --- a/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/index.js +++ b/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/DetailView/index.js @@ -24,7 +24,7 @@ import { PropertiesTable, getPropertyTabNames } from '../../../shared/PropertiesTable'; -import Stacktrace from '../../../shared/Stacktrace'; +import { Stacktrace } from '../../../shared/Stacktrace'; import { SERVICE_AGENT_NAME, SERVICE_LANGUAGE_NAME, From 5f9f8d949321301b38601c1bf9d530d57e8ff479 Mon Sep 17 00:00:00 2001 From: Peter Pisljar Date: Mon, 10 Dec 2018 08:22:33 +0100 Subject: [PATCH 28/85] allow disabling gpu in tests (#26684) --- test/functional/services/remote/leadfoot_command.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/functional/services/remote/leadfoot_command.js b/test/functional/services/remote/leadfoot_command.js index 34c0ba1fa8801..748cea2746b6f 100644 --- a/test/functional/services/remote/leadfoot_command.js +++ b/test/functional/services/remote/leadfoot_command.js @@ -32,6 +32,9 @@ async function attemptToCreateCommand(log, server, driverApi) { log.debug('[leadfoot:command] Creating session'); let browserOptions = {}; + if (process.env.TEST_DISABLE_GPU) { + browserOptions = { chromeOptions: { args: ['disable-gpu'] } }; + } if (process.env.TEST_BROWSER_HEADLESS) { browserOptions = { chromeOptions: { args: ['headless', 'disable-gpu'] } }; } From ab913ebe68328ad3250bdd8484e9d8e4f8405f18 Mon Sep 17 00:00:00 2001 From: Peter Pisljar Date: Mon, 10 Dec 2018 16:24:37 +0100 Subject: [PATCH 29/85] skipping failing tests (#26877) --- .../api_integration/apis/monitoring/elasticsearch/overview.js | 2 +- x-pack/test/reporting/api/bwc_existing_indexes.js | 2 +- x-pack/test/reporting/api/bwc_generation_urls.js | 2 +- x-pack/test/reporting/api/usage.js | 2 +- x-pack/test/reporting/functional/reporting.js | 4 ++-- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/x-pack/test/api_integration/apis/monitoring/elasticsearch/overview.js b/x-pack/test/api_integration/apis/monitoring/elasticsearch/overview.js index 170fe101433b4..951e6ef937b23 100644 --- a/x-pack/test/api_integration/apis/monitoring/elasticsearch/overview.js +++ b/x-pack/test/api_integration/apis/monitoring/elasticsearch/overview.js @@ -14,7 +14,7 @@ export default function ({ getService }) { const supertest = getService('supertest'); const esArchiver = getService('esArchiver'); - describe('overview', () => { + describe.skip('overview', () => { describe('with green platinum cluster', () => { const archive = 'monitoring/singlecluster-green-platinum'; const timeRange = { diff --git a/x-pack/test/reporting/api/bwc_existing_indexes.js b/x-pack/test/reporting/api/bwc_existing_indexes.js index 7743e99c03de4..0af9cd8188922 100644 --- a/x-pack/test/reporting/api/bwc_existing_indexes.js +++ b/x-pack/test/reporting/api/bwc_existing_indexes.js @@ -24,7 +24,7 @@ export default function ({ getService }) { let expectedCompletedReportCount; let cleanupIndexAlias; - describe('existing 6_2 index', () => { + describe.skip('existing 6_2 index', () => { before('load data and add index alias', async () => { await reportingAPI.deleteAllReportingIndexes(); await esArchiver.load('bwc/6_2'); diff --git a/x-pack/test/reporting/api/bwc_generation_urls.js b/x-pack/test/reporting/api/bwc_generation_urls.js index 6127cbfa2b045..c7ca0ee0a19ca 100644 --- a/x-pack/test/reporting/api/bwc_generation_urls.js +++ b/x-pack/test/reporting/api/bwc_generation_urls.js @@ -26,7 +26,7 @@ export default function ({ getService }) { }).timeout(500000); }); - describe('6_2', () => { + describe.skip('6_2', () => { before(async () => { await reportingAPI.deleteAllReportingIndexes(); }); diff --git a/x-pack/test/reporting/api/usage.js b/x-pack/test/reporting/api/usage.js index 53f292b7bf706..d9e10eb1f01f9 100644 --- a/x-pack/test/reporting/api/usage.js +++ b/x-pack/test/reporting/api/usage.js @@ -88,7 +88,7 @@ export default function ({ getService }) { }); }); - describe('usage updated when new jobs are posted', async () => { + describe.skip('usage updated when new jobs are posted', async () => { it('post jobs', async () => { const reportPaths = []; reportPaths.push(await reportingAPI.postJob(GenerationUrls.CSV_DISCOVER_KUERY_AND_FILTER_6_3)); diff --git a/x-pack/test/reporting/functional/reporting.js b/x-pack/test/reporting/functional/reporting.js index 49960679a89c4..cc996d89877f8 100644 --- a/x-pack/test/reporting/functional/reporting.js +++ b/x-pack/test/reporting/functional/reporting.js @@ -273,13 +273,13 @@ export default function ({ getService, getPageObjects }) { await expectEnabledGenerateReportButton(); }); - it('generates a report with data', async () => { + it.skip('generates a report with data', async () => { await PageObjects.reporting.setTimepickerInDataRange(); await PageObjects.reporting.openCsvReportingPanel(); await expectReportCanBeCreated(); }); - it('generates a report with no data', async () => { + it.skip('generates a report with no data', async () => { await PageObjects.reporting.setTimepickerInNoDataRange(); await PageObjects.reporting.openCsvReportingPanel(); await expectReportCanBeCreated(); From 6316dd25922dede9ce4bb8243977d621460c54d6 Mon Sep 17 00:00:00 2001 From: Nox911 Date: Mon, 10 Dec 2018 19:22:42 +0300 Subject: [PATCH 30/85] Feature/translate ml - jobs(part 2) (#25528) Translate ml -> jobs - jobs-list(part_2) --- .../create_watch_flyout.js | 43 +++++++--- .../job_details/extract_job_details.js | 45 +++++++--- .../forecasts_table/forecasts_table.js | 86 +++++++++++++++---- .../components/job_details/job_details.js | 49 ++++++++--- .../job_details/job_messages_pane.js | 22 +++-- .../job_filter_bar/job_filter_bar.js | 53 +++++++++--- .../public/jobs/jobs_list/components/utils.js | 76 +++++++++++----- 7 files changed, 292 insertions(+), 82 deletions(-) diff --git a/x-pack/plugins/ml/public/jobs/jobs_list/components/create_watch_flyout/create_watch_flyout.js b/x-pack/plugins/ml/public/jobs/jobs_list/components/create_watch_flyout/create_watch_flyout.js index ac432e8323d05..ab84ee7dbd795 100644 --- a/x-pack/plugins/ml/public/jobs/jobs_list/components/create_watch_flyout/create_watch_flyout.js +++ b/x-pack/plugins/ml/public/jobs/jobs_list/components/create_watch_flyout/create_watch_flyout.js @@ -26,11 +26,16 @@ import { toastNotifications } from 'ui/notify'; import { loadFullJob } from '../utils'; import { mlCreateWatchService } from '../../../../jobs/new_job/simple/components/watcher/create_watch_service'; import { CreateWatch } from '../../../../jobs/new_job/simple/components/watcher/create_watch_view'; +import { FormattedMessage, injectI18n } from '@kbn/i18n/react'; -function getSuccessToast(id, url) { +function getSuccessToast(id, url, intl) { return { - title: `Watch ${id} created successfully`, + title: intl.formatMessage({ + id: 'xpack.ml.jobsList.createWatchFlyout.watchCreatedSuccessfullyNotificationMessage', + defaultMessage: 'Watch {id} created successfully' }, + { id } + ), text: ( @@ -41,7 +46,10 @@ function getSuccessToast(id, url) { target="_blank" iconType="link" > - Edit watch + {intl.formatMessage({ + id: 'xpack.ml.jobsList.createWatchFlyout.editWatchButtonLabel', + defaultMessage: 'Edit watch' } + )}
@@ -50,7 +58,7 @@ function getSuccessToast(id, url) { }; } -export class CreateWatchFlyout extends Component { +class CreateWatchFlyoutUI extends Component { constructor(props) { super(props); @@ -95,13 +103,17 @@ export class CreateWatchFlyout extends Component { } save = () => { + const { intl } = this.props; mlCreateWatchService.createNewWatch(this.state.jobId) .then((resp) => { - toastNotifications.addSuccess(getSuccessToast(resp.id, resp.url)); + toastNotifications.addSuccess(getSuccessToast(resp.id, resp.url, intl)); this.closeFlyout(); }) .catch((error) => { - toastNotifications.addDanger(`Could not save watch`); + toastNotifications.addDanger(intl.formatMessage({ + id: 'xpack.ml.jobsList.createWatchFlyout.watchNotSavedErrorNotificationMessage', + defaultMessage: 'Could not save watch' + })); console.error(error); }); } @@ -125,7 +137,11 @@ export class CreateWatchFlyout extends Component {

- Create watch for {jobId} +

@@ -145,7 +161,10 @@ export class CreateWatchFlyout extends Component { onClick={this.closeFlyout} flush="left" > - Close + @@ -153,7 +172,10 @@ export class CreateWatchFlyout extends Component { onClick={this.save} fill > - Save + @@ -169,8 +191,9 @@ export class CreateWatchFlyout extends Component { } } -CreateWatchFlyout.propTypes = { +CreateWatchFlyoutUI.propTypes = { setShowFunction: PropTypes.func.isRequired, unsetShowFunction: PropTypes.func.isRequired, }; +export const CreateWatchFlyout = injectI18n(CreateWatchFlyoutUI); diff --git a/x-pack/plugins/ml/public/jobs/jobs_list/components/job_details/extract_job_details.js b/x-pack/plugins/ml/public/jobs/jobs_list/components/job_details/extract_job_details.js index 27aebbfa66e37..390939d33f9cc 100644 --- a/x-pack/plugins/ml/public/jobs/jobs_list/components/job_details/extract_job_details.js +++ b/x-pack/plugins/ml/public/jobs/jobs_list/components/job_details/extract_job_details.js @@ -7,6 +7,7 @@ import { detectorToString } from 'plugins/ml/util/string_utils'; import { formatValues, filterObjects } from './format_values'; +import { i18n } from '@kbn/i18n'; export function extractJobDetails(job) { @@ -15,14 +16,18 @@ export function extractJobDetails(job) { } const general = { - title: 'General', + title: i18n.translate('xpack.ml.jobsList.jobDetails.generalTitle', { + defaultMessage: 'General' + }), position: 'left', items: filterObjects(job, true).map(formatValues) }; const customUrl = { - title: 'Custom URLs', + title: i18n.translate('xpack.ml.jobsList.jobDetails.customUrlsTitle', { + defaultMessage: 'Custom URLs' + }), position: 'right', items: [] }; @@ -31,7 +36,9 @@ export function extractJobDetails(job) { } const node = { - title: 'Node', + title: i18n.translate('xpack.ml.jobsList.jobDetails.nodeTitle', { + defaultMessage: 'Node' + }), position: 'right', items: [] }; @@ -40,7 +47,9 @@ export function extractJobDetails(job) { } const detectors = { - title: 'Detectors', + title: i18n.translate('xpack.ml.jobsList.jobDetails.detectorsTitle', { + defaultMessage: 'Detectors' + }), position: 'left', items: [] }; @@ -55,31 +64,41 @@ export function extractJobDetails(job) { } const influencers = { - title: 'Influencers', + title: i18n.translate('xpack.ml.jobsList.jobDetails.influencersTitle', { + defaultMessage: 'Influencers' + }), position: 'left', items: job.analysis_config.influencers.map(i => ['', i]) }; const analysisConfig = { - title: 'Analysis config', + title: i18n.translate('xpack.ml.jobsList.jobDetails.analysisConfigTitle', { + defaultMessage: 'Analysis config' + }), position: 'left', items: filterObjects(job.analysis_config) }; const analysisLimits = { - title: 'Analysis limits', + title: i18n.translate('xpack.ml.jobsList.jobDetails.analysisLimitsTitle', { + defaultMessage: 'Analysis limits' + }), position: 'left', items: filterObjects(job.analysis_limits) }; const dataDescription = { - title: 'Data description', + title: i18n.translate('xpack.ml.jobsList.jobDetails.dataDescriptionTitle', { + defaultMessage: 'Data description' + }), position: 'right', items: filterObjects(job.data_description) }; const datafeed = { - title: 'Datafeed', + title: i18n.translate('xpack.ml.jobsList.jobDetails.datafeedTitle', { + defaultMessage: 'Datafeed' + }), position: 'left', items: filterObjects(job.datafeed_config, true, true) }; @@ -88,13 +107,17 @@ export function extractJobDetails(job) { } const counts = { - title: 'Counts', + title: i18n.translate('xpack.ml.jobsList.jobDetails.countsTitle', { + defaultMessage: 'Counts' + }), position: 'left', items: filterObjects(job.data_counts).map(formatValues) }; const modelSizeStats = { - title: 'Model size stats', + title: i18n.translate('xpack.ml.jobsList.jobDetails.modelSizeStatsTitle', { + defaultMessage: 'Model size stats' + }), position: 'right', items: filterObjects(job.model_size_stats).map(formatValues) }; diff --git a/x-pack/plugins/ml/public/jobs/jobs_list/components/job_details/forecasts_table/forecasts_table.js b/x-pack/plugins/ml/public/jobs/jobs_list/components/job_details/forecasts_table/forecasts_table.js index 157bc9ae71981..7d286612e6a3d 100644 --- a/x-pack/plugins/ml/public/jobs/jobs_list/components/job_details/forecasts_table/forecasts_table.js +++ b/x-pack/plugins/ml/public/jobs/jobs_list/components/job_details/forecasts_table/forecasts_table.js @@ -28,6 +28,7 @@ import chrome from 'ui/chrome'; import { FORECAST_REQUEST_STATE } from 'plugins/ml/../common/constants/states'; import { addItemToRecentlyAccessed } from 'plugins/ml/util/recently_accessed'; import { mlForecastService } from 'plugins/ml/services/forecast_service'; +import { FormattedMessage, injectI18n } from '@kbn/i18n/react'; const MAX_FORECASTS = 500; const TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss'; @@ -35,7 +36,7 @@ const TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss'; /** * Table component for rendering the lists of forecasts run on an ML job. */ -class ForecastsTable extends Component { +class ForecastsTableUI extends Component { constructor(props) { super(props); this.state = { @@ -63,7 +64,10 @@ class ForecastsTable extends Component { console.log('Error loading list of forecasts for jobs list:', resp); this.setState({ isLoading: false, - errorMessage: 'Error loading the list of forecasts run on this job', + errorMessage: this.props.intl.formatMessage({ + id: 'xpack.ml.jobsList.jobDetails.forecastsTable.loadingErrorMessage', + defaultMessage: 'Error loading the list of forecasts run on this job' + }), forecasts: [] }); }); @@ -150,65 +154,110 @@ class ForecastsTable extends Component { if (forecasts.length === 0) { return ( )} iconType="iInCircle" >

- To run a forecast, - open the this.openSingleMetricView()}>Single Metric Viewer + this.openSingleMetricView()}> + + + ) + }} + />

); } + const { intl } = this.props; + const columns = [ { field: 'forecast_create_timestamp', - name: 'Created', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobDetails.forecastsTable.createdLabel', + defaultMessage: 'Created' + }), dataType: 'date', render: (date) => formatDate(date, TIME_FORMAT), sortable: true }, { field: 'forecast_start_timestamp', - name: 'From', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobDetails.forecastsTable.fromLabel', + defaultMessage: 'From' + }), dataType: 'date', render: (date) => formatDate(date, TIME_FORMAT), sortable: true }, { field: 'forecast_end_timestamp', - name: 'To', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobDetails.forecastsTable.toLabel', + defaultMessage: 'To' + }), dataType: 'date', render: (date) => formatDate(date, TIME_FORMAT), sortable: true }, { field: 'forecast_status', - name: 'Status', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobDetails.forecastsTable.statusLabel', + defaultMessage: 'Status' + }), sortable: true }, { field: 'forecast_memory_bytes', - name: 'Memory size', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobDetails.forecastsTable.memorySizeLabel', + defaultMessage: 'Memory size' + }), render: (bytes) => formatNumber(bytes, '0b'), sortable: true }, { field: 'processing_time_ms', - name: 'Processing time', - render: (ms) => `${ms} ms`, + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobDetails.forecastsTable.processingTimeLabel', + defaultMessage: 'Processing time' + }), + render: (ms) => intl.formatMessage({ + id: 'xpack.ml.jobsList.jobDetails.forecastsTable.msTimeUnitLabel', + defaultMessage: '{ms} ms' }, { + ms + }), sortable: true }, { field: 'forecast_expiry_timestamp', - name: 'Expires', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobDetails.forecastsTable.expiresLabel', + defaultMessage: 'Expires' + }), render: (date) => formatDate(date, TIME_FORMAT), sortable: true }, { field: 'forecast_messages', - name: 'Messages', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobDetails.forecastsTable.messagesLabel', + defaultMessage: 'Messages' + }), sortable: false, render: (messages) => { return ( @@ -221,7 +270,10 @@ class ForecastsTable extends Component { } }, { - name: 'View', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobDetails.forecastsTable.viewLabel', + defaultMessage: 'View' + }), render: (forecast) => ( this.openSingleMetricView(forecast)} @@ -247,8 +299,10 @@ class ForecastsTable extends Component { ); } } -ForecastsTable.propTypes = { +ForecastsTableUI.propTypes = { job: PropTypes.object.isRequired, }; +const ForecastsTable = injectI18n(ForecastsTableUI); + export { ForecastsTable }; diff --git a/x-pack/plugins/ml/public/jobs/jobs_list/components/job_details/job_details.js b/x-pack/plugins/ml/public/jobs/jobs_list/components/job_details/job_details.js index e51d352b10665..bfdb8fec1a907 100644 --- a/x-pack/plugins/ml/public/jobs/jobs_list/components/job_details/job_details.js +++ b/x-pack/plugins/ml/public/jobs/jobs_list/components/job_details/job_details.js @@ -21,8 +21,9 @@ import { DatafeedPreviewPane } from './datafeed_preview_tab'; import { ForecastsTable } from './forecasts_table'; import { JobDetailsPane } from './job_details_pane'; import { JobMessagesPane } from './job_messages_pane'; +import { injectI18n } from '@kbn/i18n/react'; -export class JobDetails extends Component { +class JobDetailsUI extends Component { constructor(props) { super(props); @@ -63,38 +64,64 @@ export class JobDetails extends Component { modelSizeStats } = extractJobDetails(job); + const { intl } = this.props; + const tabs = [{ id: 'job-settings', - name: 'Job settings', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobDetails.tabs.jobSettingsLabel', + defaultMessage: 'Job settings' + }), content: , time: job.open_time }, { id: 'job-config', - name: 'Job config', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobDetails.tabs.jobConfigLabel', + defaultMessage: 'Job config' + }), content: , }, { id: 'datafeed', - name: 'Datafeed', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobDetails.tabs.datafeedLabel', + defaultMessage: 'Datafeed' + }), content: , }, { id: 'counts', - name: 'Counts', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobDetails.tabs.countsLabel', + defaultMessage: 'Counts' + }), content: , }, { id: 'json', - name: 'JSON', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobDetails.tabs.jsonLabel', + defaultMessage: 'JSON' + }), content: , }, { id: 'job-messages', - name: 'Job messages', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobDetails.tabs.jobMessagesLabel', + defaultMessage: 'Job messages' + }), content: , }, { id: 'datafeed-preview', - name: 'Datafeed preview', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobDetails.tabs.datafeedPreviewLabel', + defaultMessage: 'Datafeed preview' + }), content: , }, { id: 'forecasts', - name: 'Forecasts', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobDetails.tabs.forecastsLabel', + defaultMessage: 'Forecasts' + }), content: , } ]; @@ -111,9 +138,11 @@ export class JobDetails extends Component { } } } -JobDetails.propTypes = { +JobDetailsUI.propTypes = { jobId: PropTypes.string.isRequired, job: PropTypes.object, addYourself: PropTypes.func.isRequired, removeYourself: PropTypes.func.isRequired, }; + +export const JobDetails = injectI18n(JobDetailsUI); diff --git a/x-pack/plugins/ml/public/jobs/jobs_list/components/job_details/job_messages_pane.js b/x-pack/plugins/ml/public/jobs/jobs_list/components/job_details/job_messages_pane.js index 5af8199c37b85..9cb3012242544 100644 --- a/x-pack/plugins/ml/public/jobs/jobs_list/components/job_details/job_messages_pane.js +++ b/x-pack/plugins/ml/public/jobs/jobs_list/components/job_details/job_messages_pane.js @@ -18,10 +18,11 @@ import { import { formatDate } from '@elastic/eui/lib/services/format'; import { ml } from 'plugins/ml/services/ml_api_service'; import { JobIcon } from '../job_message_icon'; +import { injectI18n } from '@kbn/i18n/react'; const TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss'; -export class JobMessagesPane extends Component { +class JobMessagesPaneUI extends Component { constructor(props) { super(props); @@ -44,18 +45,28 @@ export class JobMessagesPane extends Component { render() { const { messages } = this.state; + const { intl } = this.props; const columns = [{ name: '', render: item => () }, { - name: 'Time', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobDetails.messagesPane.timeLabel', + defaultMessage: 'Time' + }), render: item => formatDate(item.timestamp, TIME_FORMAT) }, { field: 'node_name', - name: 'Node', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobDetails.messagesPane.nodeLabel', + defaultMessage: 'Node' + }), }, { field: 'message', - name: 'Message', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobDetails.messagesPane.messageLabel', + defaultMessage: 'Message' + }), } ]; return ( @@ -71,7 +82,8 @@ export class JobMessagesPane extends Component { ); } } -JobMessagesPane.propTypes = { +JobMessagesPaneUI.propTypes = { job: PropTypes.object.isRequired, }; +export const JobMessagesPane = injectI18n(JobMessagesPaneUI); diff --git a/x-pack/plugins/ml/public/jobs/jobs_list/components/job_filter_bar/job_filter_bar.js b/x-pack/plugins/ml/public/jobs/jobs_list/components/job_filter_bar/job_filter_bar.js index 189af8900df6d..d53bd5d895613 100644 --- a/x-pack/plugins/ml/public/jobs/jobs_list/components/job_filter_bar/job_filter_bar.js +++ b/x-pack/plugins/ml/public/jobs/jobs_list/components/job_filter_bar/job_filter_bar.js @@ -20,6 +20,7 @@ import { EuiFlexGroup, EuiFlexItem, } from '@elastic/eui'; +import { FormattedMessage, injectI18n } from '@kbn/i18n/react'; function loadGroups() { return ml.jobs.groups() @@ -28,7 +29,14 @@ function loadGroups() { value: g.id, view: (
- ({g.jobIds.length} job{(g.jobIds.length === 1) ? '' : 's'}) +   + + +
) })); @@ -39,7 +47,7 @@ function loadGroups() { }); } -export class JobFilterBar extends Component { +class JobFilterBarUI extends Component { constructor(props) { super(props); @@ -69,7 +77,12 @@ export class JobFilterBar extends Component { + )} /> @@ -77,6 +90,7 @@ export class JobFilterBar extends Component { } render() { + const { intl } = this.props; const filters = [ { type: 'field_value_toggle_group', @@ -84,15 +98,24 @@ export class JobFilterBar extends Component { items: [ { value: 'opened', - name: 'Opened' + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobFilterBar.openedLabel', + defaultMessage: 'Opened' + }) }, { value: 'closed', - name: 'Closed' + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobFilterBar.closedLabel', + defaultMessage: 'Closed' + }) }, { value: 'failed', - name: 'Failed' + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobFilterBar.failedLabel', + defaultMessage: 'Failed' + }) } ] }, @@ -102,18 +125,27 @@ export class JobFilterBar extends Component { items: [ { value: 'started', - name: 'Started' + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobFilterBar.startedLabel', + defaultMessage: 'Started' + }) }, { value: 'stopped', - name: 'Stopped' + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobFilterBar.stoppedLabel', + defaultMessage: 'Stopped' + }) } ] }, { type: 'field_value_selection', field: 'groups', - name: 'Group', + name: intl.formatMessage({ + id: 'xpack.ml.jobsList.jobFilterBar.groupLabel', + defaultMessage: 'Group' + }), multiSelect: 'or', cache: 10000, options: () => loadGroups() @@ -138,7 +170,8 @@ export class JobFilterBar extends Component { ); } } -JobFilterBar.propTypes = { +JobFilterBarUI.propTypes = { setFilters: PropTypes.func.isRequired, }; +export const JobFilterBar = injectI18n(JobFilterBarUI); diff --git a/x-pack/plugins/ml/public/jobs/jobs_list/components/utils.js b/x-pack/plugins/ml/public/jobs/jobs_list/components/utils.js index e34683f263261..173daf41c4b00 100644 --- a/x-pack/plugins/ml/public/jobs/jobs_list/components/utils.js +++ b/x-pack/plugins/ml/public/jobs/jobs_list/components/utils.js @@ -11,6 +11,7 @@ import { mlMessageBarService } from 'plugins/ml/components/messagebar/messagebar import { mlJobService } from 'plugins/ml/services/job_service'; import { ml } from 'plugins/ml/services/ml_api_service'; import { JOB_STATE, DATAFEED_STATE } from 'plugins/ml/../common/constants/states'; +import { i18n } from '@kbn/i18n'; export function loadFullJob(jobId) { return new Promise((resolve, reject) => { @@ -49,7 +50,9 @@ export function forceStartDatafeeds(jobs, start, end, finish = () => {}) { }) .catch((error) => { mlMessageBarService.notify.error(error); - toastNotifications.addDanger(`Jobs failed to start`, error); + toastNotifications.addDanger(i18n.translate('xpack.ml.jobsList.startJobErrorMessage', { + defaultMessage: 'Jobs failed to start' + }), error); finish(); }); } @@ -64,7 +67,9 @@ export function stopDatafeeds(jobs, finish = () => {}) { }) .catch((error) => { mlMessageBarService.notify.error(error); - toastNotifications.addDanger(`Jobs failed to stop`, error); + toastNotifications.addDanger(i18n.translate('xpack.ml.jobsList.stopJobErrorMessage', { + defaultMessage: 'Jobs failed to stop' + }), error); finish(); }); } @@ -87,30 +92,54 @@ function showResults(resp, action) { let actionText = ''; let actionTextPT = ''; if (action === DATAFEED_STATE.STARTED) { - actionText = 'start'; - actionTextPT = 'started'; + actionText = i18n.translate('xpack.ml.jobsList.startActionStatusText', { + defaultMessage: 'start' + }); + actionTextPT = i18n.translate('xpack.ml.jobsList.startedActionStatusText', { + defaultMessage: 'started' + }); } else if (action === DATAFEED_STATE.STOPPED) { - actionText = 'stop'; - actionTextPT = 'stopped'; + actionText = i18n.translate('xpack.ml.jobsList.stopActionStatusText', { + defaultMessage: 'stop' + }); + actionTextPT = i18n.translate('xpack.ml.jobsList.stoppedActionStatusText', { + defaultMessage: 'stopped' + }); } else if (action === DATAFEED_STATE.DELETED) { - actionText = 'delete'; - actionTextPT = 'deleted'; + actionText = i18n.translate('xpack.ml.jobsList.deleteActionStatusText', { + defaultMessage: 'delete' + }); + actionTextPT = i18n.translate('xpack.ml.jobsList.deletedActionStatusText', { + defaultMessage: 'deleted' + }); } else if (action === JOB_STATE.CLOSED) { - actionText = 'close'; - actionTextPT = 'closed'; + actionText = i18n.translate('xpack.ml.jobsList.closeActionStatusText', { + defaultMessage: 'close' + }); + actionTextPT = i18n.translate('xpack.ml.jobsList.closedActionStatusText', { + defaultMessage: 'closed' + }); } - - if (successes.length > 1) { - toastNotifications.addSuccess(`${successes.length} jobs ${actionTextPT} successfully`); - } else if (successes.length === 1) { - toastNotifications.addSuccess(`${successes[0]} ${actionTextPT} successfully`); - } + toastNotifications.addSuccess(i18n.translate('xpack.ml.jobsList.actionExecuteSuccessfullyNotificationMessage', { + defaultMessage: '{successesJobsCount, plural, one{{successJob}} other{# jobs}} {actionTextPT} successfully', + values: { + successesJobsCount: successes.length, + successJob: successes[0], + actionTextPT + } + })); if (failures.length > 0) { failures.forEach((f) => { mlMessageBarService.notify.error(f.result.error); - toastNotifications.addDanger(`${f.id} failed to ${actionText}`); + toastNotifications.addDanger(i18n.translate('xpack.ml.jobsList.actionFailedNotificationMessage', { + defaultMessage: '{failureId} failed to {actionText}', + values: { + failureId: f.id, + actionText + } + })); }); } } @@ -123,7 +152,10 @@ export function cloneJob(jobId) { }) .catch((error) => { mlMessageBarService.notify.error(error); - toastNotifications.addDanger(`Could not clone ${jobId}. Job could not be found`); + toastNotifications.addDanger(i18n.translate('xpack.ml.jobsList.cloneJobErrorMessage', { + defaultMessage: 'Could not clone {jobId}. Job could not be found', + values: { jobId } + })); }); } @@ -136,7 +168,9 @@ export function closeJobs(jobs, finish = () => {}) { }) .catch((error) => { mlMessageBarService.notify.error(error); - toastNotifications.addDanger(`Jobs failed to close`, error); + toastNotifications.addDanger(i18n.translate('xpack.ml.jobsList.closeJobErrorMessage', { + defaultMessage: 'Jobs failed to close', + }), error); finish(); }); } @@ -150,7 +184,9 @@ export function deleteJobs(jobs, finish = () => {}) { }) .catch((error) => { mlMessageBarService.notify.error(error); - toastNotifications.addDanger(`Jobs failed to delete`, error); + toastNotifications.addDanger(i18n.translate('xpack.ml.jobsList.deleteJobErrorMessage', { + defaultMessage: 'Jobs failed to delete', + }), error); finish(); }); } From 34f721bae4ff8e90bab87d04ab1d2acfa33151cf Mon Sep 17 00:00:00 2001 From: Peter Pisljar Date: Mon, 10 Dec 2018 17:41:25 +0100 Subject: [PATCH 31/85] use canvas pipeline in visualize (#25996) --- .../kbn-interpreter/src/plugin/types/index.js | 4 + .../src/plugin/types/kibana_context.js | 36 +++ .../src/plugin/types/kibana_table.js | 41 ++++ packages/kbn-interpreter/src/public/index.js | 2 +- .../kbn-interpreter/src/public/interpreter.js | 8 +- .../interpreter/public/functions/esaggs.js | 97 ++++++++ .../interpreter/public/functions/index.js | 40 ++++ .../public/functions/input_control.js | 50 +++++ .../interpreter/public/functions/kibana.js | 51 +++++ .../public/functions/kibana_context.js | 86 ++++++++ .../interpreter/public/functions/markdown.js | 59 +++++ .../interpreter/public/functions/metric.js | 76 +++++++ .../interpreter/public/functions/pie.js | 84 +++++++ .../interpreter/public/functions/regionmap.js | 74 +++++++ .../interpreter/public/functions/table.js | 103 +++++++++ .../interpreter/public/functions/tagcloud.js | 74 +++++++ .../interpreter/public/functions/tilemap.js | 79 +++++++ .../public/functions/timelion_vis.js | 69 ++++++ .../interpreter/public/functions/tsvb.js | 73 ++++++ .../interpreter/public/functions/vega.js | 70 ++++++ .../interpreter/public/functions/vislib.js | 93 ++++++++ .../public/functions/visualization.js | 147 +++++++++++++ .../public/load_browser_plugins.js | 16 +- .../public/discover/controllers/discover.js | 2 +- src/ui/public/vis/index.d.ts | 2 +- src/ui/public/vis/response_handlers/legacy.js | 22 +- src/ui/public/vis/vis.d.ts | 7 + .../loader/__tests__/visualize_data_loader.js | 8 - .../loader/__tests__/visualize_loader.js | 6 +- .../loader/embedded_visualize_handler.ts | 29 +-- .../visualize/loader/pipeline_data_loader.ts | 46 ++++ .../__snapshots__/build_pipeline.test.js.snap | 31 +++ .../pipeline_helpers/build_pipeline.test.js | 202 +++++++++++++++++ .../loader/pipeline_helpers/build_pipeline.ts | 207 ++++++++++++++++++ .../loader/pipeline_helpers/index.ts | 21 ++ .../loader/pipeline_helpers/run_pipeline.ts | 29 +++ test/functional/apps/visualize/_data_table.js | 4 +- .../embedding_visualizations/embed_by_id.js | 2 + .../canvas/public/components/app/index.js | 9 +- 39 files changed, 2011 insertions(+), 48 deletions(-) create mode 100644 packages/kbn-interpreter/src/plugin/types/kibana_context.js create mode 100644 packages/kbn-interpreter/src/plugin/types/kibana_table.js create mode 100644 src/legacy/core_plugins/interpreter/public/functions/esaggs.js create mode 100644 src/legacy/core_plugins/interpreter/public/functions/index.js create mode 100644 src/legacy/core_plugins/interpreter/public/functions/input_control.js create mode 100644 src/legacy/core_plugins/interpreter/public/functions/kibana.js create mode 100644 src/legacy/core_plugins/interpreter/public/functions/kibana_context.js create mode 100644 src/legacy/core_plugins/interpreter/public/functions/markdown.js create mode 100644 src/legacy/core_plugins/interpreter/public/functions/metric.js create mode 100644 src/legacy/core_plugins/interpreter/public/functions/pie.js create mode 100644 src/legacy/core_plugins/interpreter/public/functions/regionmap.js create mode 100644 src/legacy/core_plugins/interpreter/public/functions/table.js create mode 100644 src/legacy/core_plugins/interpreter/public/functions/tagcloud.js create mode 100644 src/legacy/core_plugins/interpreter/public/functions/tilemap.js create mode 100644 src/legacy/core_plugins/interpreter/public/functions/timelion_vis.js create mode 100644 src/legacy/core_plugins/interpreter/public/functions/tsvb.js create mode 100644 src/legacy/core_plugins/interpreter/public/functions/vega.js create mode 100644 src/legacy/core_plugins/interpreter/public/functions/vislib.js create mode 100644 src/legacy/core_plugins/interpreter/public/functions/visualization.js create mode 100644 src/ui/public/visualize/loader/pipeline_data_loader.ts create mode 100644 src/ui/public/visualize/loader/pipeline_helpers/__snapshots__/build_pipeline.test.js.snap create mode 100644 src/ui/public/visualize/loader/pipeline_helpers/build_pipeline.test.js create mode 100644 src/ui/public/visualize/loader/pipeline_helpers/build_pipeline.ts create mode 100644 src/ui/public/visualize/loader/pipeline_helpers/index.ts create mode 100644 src/ui/public/visualize/loader/pipeline_helpers/run_pipeline.ts diff --git a/packages/kbn-interpreter/src/plugin/types/index.js b/packages/kbn-interpreter/src/plugin/types/index.js index 1ae5f874835c3..ea3aa7d519891 100644 --- a/packages/kbn-interpreter/src/plugin/types/index.js +++ b/packages/kbn-interpreter/src/plugin/types/index.js @@ -29,6 +29,8 @@ import { render } from './render'; import { shape } from './shape'; import { string } from './string'; import { style } from './style'; +import { kibanaTable } from './kibana_table'; +import { kibanaContext } from './kibana_context'; export const typeSpecs = [ boolean, @@ -43,4 +45,6 @@ export const typeSpecs = [ shape, string, style, + kibanaTable, + kibanaContext, ]; diff --git a/packages/kbn-interpreter/src/plugin/types/kibana_context.js b/packages/kbn-interpreter/src/plugin/types/kibana_context.js new file mode 100644 index 0000000000000..b186ae135788d --- /dev/null +++ b/packages/kbn-interpreter/src/plugin/types/kibana_context.js @@ -0,0 +1,36 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export const kibanaContext = () => ({ + name: 'kibana_context', + from: { + null: () => { + return { + type: 'kibana_context', + }; + }, + }, + to: { + null: () => { + return { + type: 'null', + }; + }, + } +}); diff --git a/packages/kbn-interpreter/src/plugin/types/kibana_table.js b/packages/kbn-interpreter/src/plugin/types/kibana_table.js new file mode 100644 index 0000000000000..67cedbded50ae --- /dev/null +++ b/packages/kbn-interpreter/src/plugin/types/kibana_table.js @@ -0,0 +1,41 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export const kibanaTable = () => ({ + name: 'kibana_table', + serialize: context => { + context.columns.forEach(column => { + column.aggConfig = column.aggConfig.toJSON(); + }); + return context; + }, + validate: tabify => { + if (!tabify.columns) { + throw new Error('tabify must have a columns array, even if it is empty'); + } + }, + from: { + null: () => { + return { + type: 'kibana_table', + columns: [], + }; + }, + }, +}); diff --git a/packages/kbn-interpreter/src/public/index.js b/packages/kbn-interpreter/src/public/index.js index de8caad1dbc5b..8c50c66ff2f2e 100644 --- a/packages/kbn-interpreter/src/public/index.js +++ b/packages/kbn-interpreter/src/public/index.js @@ -19,4 +19,4 @@ export { populateBrowserRegistries, getBrowserRegistries } from './browser_registries'; export { createSocket } from './socket'; -export { initializeInterpreter, interpretAst } from './interpreter'; +export { initializeInterpreter, interpretAst, getInitializedFunctions } from './interpreter'; diff --git a/packages/kbn-interpreter/src/public/interpreter.js b/packages/kbn-interpreter/src/public/interpreter.js index ba38df27b6f85..99bf6814deb65 100644 --- a/packages/kbn-interpreter/src/public/interpreter.js +++ b/packages/kbn-interpreter/src/public/interpreter.js @@ -47,14 +47,18 @@ export async function initializeInterpreter() { return functionList; } +export async function getInitializedFunctions() { + return functionList; +} + // Use the above promise to seed the interpreter with the functions it can defer to -export async function interpretAst(ast, context) { +export async function interpretAst(ast, context, handlers) { // Load plugins before attempting to get functions, otherwise this gets racey return Promise.all([functionList, getBrowserRegistries()]) .then(([serverFunctionList]) => { return socketInterpreterProvider({ types: typesRegistry.toJS(), - handlers: createHandlers(socket), + handlers: { ...handlers, ...createHandlers(socket) }, functions: functionsRegistry.toJS(), referableFunctions: serverFunctionList, socket: socket, diff --git a/src/legacy/core_plugins/interpreter/public/functions/esaggs.js b/src/legacy/core_plugins/interpreter/public/functions/esaggs.js new file mode 100644 index 0000000000000..ba5b6c009701f --- /dev/null +++ b/src/legacy/core_plugins/interpreter/public/functions/esaggs.js @@ -0,0 +1,97 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { get } from 'lodash'; +import { i18n } from '@kbn/i18n'; +import { CourierRequestHandlerProvider } from 'ui/vis/request_handlers/courier'; +import { AggConfigs } from 'ui/vis/agg_configs'; + +// need to get rid of angular from these +import { IndexPatternsProvider } from 'ui/index_patterns'; +import { SearchSourceProvider } from 'ui/courier/search_source'; +import { FilterBarQueryFilterProvider } from 'ui/filter_bar/query_filter'; + +import chrome from 'ui/chrome'; + +const courierRequestHandlerProvider = CourierRequestHandlerProvider; +const courierRequestHandler = courierRequestHandlerProvider().handler; + +export const esaggs = () => ({ + name: 'esaggs', + type: 'kibana_table', + context: { + types: [ + 'kibana_context', + 'null', + ], + }, + help: i18n.translate('common.core_plugins.interpreter.public.functions.esaggs.help', { defaultMessage: 'Run AggConfig aggregation' }), + args: { + index: { + types: ['string', 'null'], + default: null, + }, + metricsAtAllLevels: { + types: ['boolean'], + default: false, + }, + partialRows: { + types: ['boolean'], + default: false, + }, + aggConfigs: { + types: ['string'], + default: '""', + }, + }, + async fn(context, args, handlers) { + const $injector = await chrome.dangerouslyGetActiveInjector(); + const Private = $injector.get('Private'); + const indexPatterns = Private(IndexPatternsProvider); + const SearchSource = Private(SearchSourceProvider); + const queryFilter = Private(FilterBarQueryFilterProvider); + + const aggConfigsState = JSON.parse(args.aggConfigs); + const indexPattern = await indexPatterns.get(args.index); + const aggs = new AggConfigs(indexPattern, aggConfigsState); + + // we should move searchSource creation inside courier request handler + const searchSource = new SearchSource(); + searchSource.setField('index', indexPattern); + + const response = await courierRequestHandler({ + searchSource: searchSource, + aggs: aggs, + timeRange: get(context, 'timeRange', null), + query: get(context, 'query', null), + filters: get(context, 'filters', null), + forceFetch: true, + isHierarchical: args.metricsAtAllLevels, + partialRows: args.partialRows, + inspectorAdapters: handlers.inspectorAdapters, + queryFilter, + }); + + return { + type: 'kibana_table', + index: args.index, + ...response, + }; + }, +}); diff --git a/src/legacy/core_plugins/interpreter/public/functions/index.js b/src/legacy/core_plugins/interpreter/public/functions/index.js new file mode 100644 index 0000000000000..27605bf9e69c5 --- /dev/null +++ b/src/legacy/core_plugins/interpreter/public/functions/index.js @@ -0,0 +1,40 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { esaggs } from './esaggs'; +import { kibana } from './kibana'; +import { kibanaContext } from './kibana_context'; +import { vega } from './vega'; +import { timelionVis } from './timelion_vis'; +import { tsvb } from './tsvb'; +import { kibanaMarkdown } from './markdown'; +import { inputControlVis } from './input_control'; +import { metric } from './metric'; +import { kibanaPie } from './pie'; +import { regionmap } from './regionmap'; +import { tilemap } from './tilemap'; +import { kibanaTable } from './table'; +import { tagcloud } from './tagcloud'; +import { vislib } from './vislib'; +import { visualization } from './visualization'; + +export const functions = [ + esaggs, kibana, kibanaContext, vega, timelionVis, tsvb, kibanaMarkdown, inputControlVis, + metric, kibanaPie, regionmap, tilemap, kibanaTable, tagcloud, vislib, visualization +]; diff --git a/src/legacy/core_plugins/interpreter/public/functions/input_control.js b/src/legacy/core_plugins/interpreter/public/functions/input_control.js new file mode 100644 index 0000000000000..db0f5dfe27af6 --- /dev/null +++ b/src/legacy/core_plugins/interpreter/public/functions/input_control.js @@ -0,0 +1,50 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { i18n } from '@kbn/i18n'; + +export const inputControlVis = () => ({ + name: 'input_control_vis', + type: 'render', + context: { + types: [], + }, + help: i18n.translate('common.core_plugins.interpreter.public.functions.input_control.help', { + defaultMessage: 'Input control visualization' + }), + args: { + visConfig: { + types: ['string'], + default: '"{}"', + } + }, + fn(context, args) { + const params = JSON.parse(args.visConfig); + return { + type: 'render', + as: 'visualization', + value: { + visConfig: { + type: 'input_controls_vis', + params: params + }, + } + }; + } +}); diff --git a/src/legacy/core_plugins/interpreter/public/functions/kibana.js b/src/legacy/core_plugins/interpreter/public/functions/kibana.js new file mode 100644 index 0000000000000..faef6a660c063 --- /dev/null +++ b/src/legacy/core_plugins/interpreter/public/functions/kibana.js @@ -0,0 +1,51 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { i18n } from '@kbn/i18n'; + +export const kibana = () => ({ + name: 'kibana', + type: 'kibana_context', + context: {}, + help: i18n.translate('common.core_plugins.interpreter.public.functions.kibana.help', { + defaultMessage: 'Gets kibana global context' + }), + args: {}, + fn(context, args, handlers) { + const initialContext = handlers.getInitialContext ? handlers.getInitialContext() : {}; + + if (context.query) { + initialContext.query = initialContext.query.concat(context.query); + } + + if (context.filters) { + initialContext.filters = initialContext.filters.concat(context.filters); + } + + const timeRange = initialContext.timeRange || context.timeRange; + + return { + ...context, + type: 'kibana_context', + query: initialContext.query, + filters: initialContext.filters, + timeRange: timeRange, + }; + }, +}); diff --git a/src/legacy/core_plugins/interpreter/public/functions/kibana_context.js b/src/legacy/core_plugins/interpreter/public/functions/kibana_context.js new file mode 100644 index 0000000000000..9b6cccb773df9 --- /dev/null +++ b/src/legacy/core_plugins/interpreter/public/functions/kibana_context.js @@ -0,0 +1,86 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import chrome from 'ui/chrome'; +import { i18n } from '@kbn/i18n'; + +export const kibanaContext = () => ({ + name: 'kibana_context', + type: 'kibana_context', + context: { + types: [ + 'kibana_context', + 'null', + ], + }, + help: i18n.translate('common.core_plugins.interpreter.public.functions.kibana_context.help', { + defaultMessage: 'Updates kibana global context' + }), + args: { + q: { + types: ['string', 'null'], + aliases: ['query', '_'], + default: null, + }, + filters: { + types: ['string', 'null'], + default: '"[]"', + }, + timeRange: { + types: ['string', 'null'], + default: null, + }, + savedSearchId: { + types: ['string', 'null'], + default: null, + } + }, + async fn(context, args) { + const $injector = await chrome.dangerouslyGetActiveInjector(); + const savedSearches = $injector.get('savedSearches'); + const queryArg = args.q ? JSON.parse(args.q) : []; + let queries = Array.isArray(queryArg) ? queryArg : [queryArg]; + let filters = args.filters ? JSON.parse(args.filters) : []; + + if (args.savedSearchId) { + const savedSearch = await savedSearches.get(args.savedSearchId); + const searchQuery = savedSearch.searchSource.getField('query'); + const searchFilters = savedSearch.searchSource.getField('filter'); + queries = queries.concat(searchQuery); + filters = filters.concat(searchFilters); + } + + if (context.query) { + queries = queries.concat(context.query); + } + + if (context.filters) { + filters = filters.concat(context.filters); + } + + const timeRange = args.timeRange ? JSON.parse(args.timeRange) : context.timeRange; + + return { + type: 'kibana_context', + query: queries, + filters: filters, + timeRange: timeRange, + }; + }, +}); diff --git a/src/legacy/core_plugins/interpreter/public/functions/markdown.js b/src/legacy/core_plugins/interpreter/public/functions/markdown.js new file mode 100644 index 0000000000000..0b1afda450bd6 --- /dev/null +++ b/src/legacy/core_plugins/interpreter/public/functions/markdown.js @@ -0,0 +1,59 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { i18n } from '@kbn/i18n'; + +export const kibanaMarkdown = () => ({ + name: 'kibana_markdown', + type: 'render', + context: { + types: [], + }, + help: i18n.translate('common.core_plugins.interpreter.public.functions.markdown.help', { + defaultMessage: 'Markdown visualization' + }), + args: { + expression: { + types: ['string'], + aliases: [ '_' ], + default: '', + help: 'markdown', + }, + visConfig: { + types: ['string'], + default: '"{}"', + } + }, + fn(context, args) { + const params = JSON.parse(args.visConfig); + return { + type: 'render', + as: 'visualization', + value: { + visConfig: { + type: 'markdown', + params: { + markdown: args.spec, + ...params, + } + }, + } + }; + } +}); diff --git a/src/legacy/core_plugins/interpreter/public/functions/metric.js b/src/legacy/core_plugins/interpreter/public/functions/metric.js new file mode 100644 index 0000000000000..defa432f65314 --- /dev/null +++ b/src/legacy/core_plugins/interpreter/public/functions/metric.js @@ -0,0 +1,76 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { i18n } from '@kbn/i18n'; + +export const metric = () => ({ + name: 'kibana_metric', + type: 'render', + context: { + types: [ + 'kibana_table' + ], + }, + help: i18n.translate('common.core_plugins.interpreter.public.functions.metric.help', { + defaultMessage: 'Metric visualization' + }), + args: { + bucket: { + types: ['string', 'null'], + default: null, + }, + metric: { + types: ['string'], + default: '1', + }, + visConfig: { + types: ['string', 'null'], + default: '"{}"', + }, + }, + fn(context, args) { + const visConfigParams = JSON.parse(args.visConfig); + const metrics = args.metric.split(','); + metrics.forEach(metric => { + const metricColumn = context.columns.find((column, i) => + column.id === metric || column.name === metric || i === parseInt(metric)); + metricColumn.aggConfig.schema = 'metric'; + }); + if (args.bucket) { + const bucketColumn = context.columns.find((column, i) => + column.id === args.bucket || column.name === args.bucket || i === parseInt(args.bucket)); + bucketColumn.aggConfig.schema = 'segment'; + } + + return { + type: 'render', + as: 'visualization', + value: { + visData: context, + visConfig: { + type: 'metric', + params: visConfigParams, + }, + params: { + listenOnChange: true, + } + }, + }; + }, +}); diff --git a/src/legacy/core_plugins/interpreter/public/functions/pie.js b/src/legacy/core_plugins/interpreter/public/functions/pie.js new file mode 100644 index 0000000000000..e828164e18ee2 --- /dev/null +++ b/src/legacy/core_plugins/interpreter/public/functions/pie.js @@ -0,0 +1,84 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { VisTypesRegistryProvider } from 'ui/registry/vis_types'; +import { VislibSlicesResponseHandlerProvider } from 'ui/vis/response_handlers/vislib'; +import chrome from 'ui/chrome'; +import { i18n } from '@kbn/i18n'; + +export const kibanaPie = () => ({ + name: 'kibana_pie', + type: 'render', + context: { + types: [ + 'kibana_table', 'null' + ], + }, + help: i18n.translate('common.core_plugins.interpreter.public.functions.pie.help', { + defaultMessage: 'Pie visualization' + }), + args: { + schemas: { + types: ['string'], + default: '"{}"', + }, + visConfig: { + types: ['string', 'null'], + default: '"{}"', + }, + }, + async fn(context, args) { + const $injector = await chrome.dangerouslyGetActiveInjector(); + const Private = $injector.get('Private'); + const responseHandler = Private(VislibSlicesResponseHandlerProvider).handler; + const visTypes = Private(VisTypesRegistryProvider); + const visConfigParams = JSON.parse(args.visConfig); + const visType = visTypes.byName.pie; + const schemas = JSON.parse(args.schemas); + + if (context.columns) { + context.columns.forEach(column => { + column.aggConfig.aggConfigs.schemas = visType.schemas.all; + }); + + Object.keys(schemas).forEach(key => { + schemas[key].forEach(i => { + context.columns[i].aggConfig.schema = key; + }); + }); + } + + const convertedData = await responseHandler(context); + + return { + type: 'render', + as: 'visualization', + value: { + visData: convertedData, + visConfig: { + type: args.type, + params: visConfigParams, + }, + params: { + listenOnChange: true, + } + }, + }; + }, +}); diff --git a/src/legacy/core_plugins/interpreter/public/functions/regionmap.js b/src/legacy/core_plugins/interpreter/public/functions/regionmap.js new file mode 100644 index 0000000000000..b92122a726905 --- /dev/null +++ b/src/legacy/core_plugins/interpreter/public/functions/regionmap.js @@ -0,0 +1,74 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { i18n } from '@kbn/i18n'; + +export const regionmap = () => ({ + name: 'regionmap', + type: 'render', + context: { + types: [ + 'kibana_table' + ], + }, + help: i18n.translate('common.core_plugins.interpreter.public.functions.regionmap.help', { + defaultMessage: 'Regionmap visualization' + }), + args: { + bucket: { + types: ['string'], + default: '0', + }, + metric: { + types: ['string'], + default: '1', + }, + visConfig: { + types: ['string', 'null'], + default: '"{}"', + }, + }, + fn(context, args) { + const visConfigParams = JSON.parse(args.visConfig); + const metricColumn = context.columns.find((column, i) => + column.id === args.metric || column.name === args.metric || i === parseInt(args.metric) + ); + const bucketColumn = context.columns.find((column, i) => + column.id === args.bucket || column.name === args.bucket || i === parseInt(args.bucket) + ); + + metricColumn.aggConfig.schema = 'metric'; + bucketColumn.aggConfig.schema = 'segment'; + + return { + type: 'render', + as: 'visualization', + value: { + visData: context, + visConfig: { + type: 'region_map', + params: visConfigParams, + }, + params: { + listenOnChange: true, + } + }, + }; + }, +}); diff --git a/src/legacy/core_plugins/interpreter/public/functions/table.js b/src/legacy/core_plugins/interpreter/public/functions/table.js new file mode 100644 index 0000000000000..d35e81d6b1a74 --- /dev/null +++ b/src/legacy/core_plugins/interpreter/public/functions/table.js @@ -0,0 +1,103 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { LegacyResponseHandlerProvider } from 'ui/vis/response_handlers/legacy'; +import { i18n } from '@kbn/i18n'; + +// eslint-disable-next-line new-cap +const responseHandler = LegacyResponseHandlerProvider().handler; + +export const kibanaTable = () => ({ + name: 'kibana_table', + type: 'render', + context: { + types: [ + 'kibana_table' + ], + }, + help: i18n.translate('common.core_plugins.interpreter.public.functions.table.help', { + defaultMessage: 'Table visualization' + }), + args: { + bucket: { + types: ['string'], + }, + splitRow: { + types: ['string'], + }, + splitColumn: { + types: ['string'], + }, + metric: { + types: ['string'], + default: '1', + }, + visConfig: { + types: ['string', 'null'], + default: '"{}"', + }, + }, + async fn(context, args) { + const visConfigParams = JSON.parse(args.visConfig); + args.metric.split(',').forEach(metric => { + const metricColumn = context.columns.find((column, i) => + column.id === metric || column.name === metric || i === parseInt(metric)); + metricColumn.aggConfig.schema = 'metric'; + }); + if (args.bucket) { + args.bucket.split(',').forEach(bucket => { + const bucketColumn = context.columns.find((column, i) => + column.id === bucket || column.name === bucket || i === parseInt(bucket)); + bucketColumn.aggConfig.schema = 'bucket'; + }); + } + if (args.splitColumn) { + args.splitColumn.split(',').forEach(split => { + const splitColumn = context.columns.find((column, i) => + column.id === split || column.name === split || i === parseInt(split)); + splitColumn.aggConfig.schema = 'split'; + }); + } + if (args.splitRow) { + args.splitRow.split(',').forEach(split => { + const splitColumn = context.columns.find((column, i) => + column.id === split || column.name === split || i === parseInt(split)); + splitColumn.aggConfig.schema = 'split'; + splitColumn.aggConfig.params.row = true; + }); + } + + const convertedData = await responseHandler(context); + + return { + type: 'render', + as: 'visualization', + value: { + visData: convertedData, + visConfig: { + type: 'table', + params: visConfigParams, + }, + params: { + listenOnChange: true, + } + }, + }; + }, +}); diff --git a/src/legacy/core_plugins/interpreter/public/functions/tagcloud.js b/src/legacy/core_plugins/interpreter/public/functions/tagcloud.js new file mode 100644 index 0000000000000..fbad1dd39acc4 --- /dev/null +++ b/src/legacy/core_plugins/interpreter/public/functions/tagcloud.js @@ -0,0 +1,74 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { i18n } from '@kbn/i18n'; + +export const tagcloud = () => ({ + name: 'tagcloud', + type: 'render', + context: { + types: [ + 'kibana_table' + ], + }, + help: i18n.translate('common.core_plugins.interpreter.public.functions.tagcloud.help', { + defaultMessage: 'Tagcloud visualization' + }), + args: { + bucket: { + types: ['string'], + default: '0', + }, + metric: { + types: ['string'], + default: '1', + }, + visConfig: { + types: ['string', 'null'], + default: '"{}"', + }, + }, + fn(context, args) { + const visConfigParams = JSON.parse(args.visConfig); + const metricColumn = context.columns.find((column, i) => + column.id === args.metric || column.name === args.metric || i === parseInt(args.metric) + ); + const bucketColumn = context.columns.find((column, i) => + column.id === args.bucket || column.name === args.bucket || i === parseInt(args.bucket) + ); + + metricColumn.aggConfig.schema = 'metric'; + bucketColumn.aggConfig.schema = 'segment'; + + return { + type: 'render', + as: 'visualization', + value: { + visData: context, + visConfig: { + type: 'tag_cloud', + params: visConfigParams, + }, + params: { + listenOnChange: true, + } + }, + }; + }, +}); diff --git a/src/legacy/core_plugins/interpreter/public/functions/tilemap.js b/src/legacy/core_plugins/interpreter/public/functions/tilemap.js new file mode 100644 index 0000000000000..6015a8e2626e7 --- /dev/null +++ b/src/legacy/core_plugins/interpreter/public/functions/tilemap.js @@ -0,0 +1,79 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { makeGeoJsonResponseHandler } from 'plugins/tile_map/coordinatemap_response_handler'; +import { i18n } from '@kbn/i18n'; + +const responseHandler = makeGeoJsonResponseHandler(); + +export const tilemap = () => ({ + name: 'tilemap', + type: 'render', + context: { + types: [ + 'kibana_table' + ], + }, + help: i18n.translate('common.core_plugins.interpreter.public.functions.tilemap.help', { + defaultMessage: 'Tilemap visualization' + }), + args: { + bucket: { + types: ['string'], + default: '0', + }, + metric: { + types: ['string'], + default: '1', + }, + visConfig: { + types: ['string', 'null'], + default: '"{}"', + }, + }, + fn(context, args) { + const visConfigParams = JSON.parse(args.visConfig); + const metricColumn = context.columns.find((column, i) => + column.id === args.metric || column.name === args.metric || i === parseInt(args.metric) + ); + const bucketColumn = context.columns.find((column, i) => + column.id === args.bucket || column.name === args.bucket || i === parseInt(args.bucket) + ); + + metricColumn.aggConfig.schema = 'metric'; + bucketColumn.aggConfig.schema = 'segment'; + + const convertedData = responseHandler(context); + + return { + type: 'render', + as: 'visualization', + value: { + visData: convertedData, + visConfig: { + type: 'tile_map', + params: visConfigParams, + }, + params: { + listenOnChange: true, + } + }, + }; + }, +}); diff --git a/src/legacy/core_plugins/interpreter/public/functions/timelion_vis.js b/src/legacy/core_plugins/interpreter/public/functions/timelion_vis.js new file mode 100644 index 0000000000000..f45f7038cbb22 --- /dev/null +++ b/src/legacy/core_plugins/interpreter/public/functions/timelion_vis.js @@ -0,0 +1,69 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { get } from 'lodash'; +import { i18n } from '@kbn/i18n'; +import { TimelionRequestHandlerProvider } from 'plugins/timelion/vis/timelion_request_handler'; + + +import chrome from 'ui/chrome'; + +export const timelionVis = () => ({ + name: 'timelion_vis', + type: 'render', + context: { + types: [ + 'kibana_context', + 'null', + ], + }, + help: i18n.translate('common.core_plugins.interpreter.public.functions.timelion.help', { + defaultMessage: 'Timelion visualization' + }), + args: { + expression: { + types: ['string'], + aliases: ['_'], + default: '".es(*)"', + }, + interval: { + types: ['string', 'null'], + default: 'auto', + } + }, + async fn(context, args) { + const $injector = await chrome.dangerouslyGetActiveInjector(); + const Private = $injector.get('Private'); + const timelionRequestHandler = Private(TimelionRequestHandlerProvider).handler; + + const response = await timelionRequestHandler({ + timeRange: get(context, 'timeRange', null), + query: get(context, 'query', null), + filters: get(context, 'filters', null), + forceFetch: true, + visParams: { expression: args.expression, interval: args.interval } + }); + + return { + type: 'render', + as: 'visualization', + value: response, + }; + }, +}); diff --git a/src/legacy/core_plugins/interpreter/public/functions/tsvb.js b/src/legacy/core_plugins/interpreter/public/functions/tsvb.js new file mode 100644 index 0000000000000..ce83dfcadb62d --- /dev/null +++ b/src/legacy/core_plugins/interpreter/public/functions/tsvb.js @@ -0,0 +1,73 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { get } from 'lodash'; +import { i18n } from '@kbn/i18n'; +import { MetricsRequestHandlerProvider } from 'plugins/metrics/kbn_vis_types/request_handler'; +import { PersistedState } from 'ui/persisted_state'; + +import chrome from 'ui/chrome'; + + +export const tsvb = () => ({ + name: 'tsvb', + type: 'render', + context: { + types: [ + 'kibana_context', + 'null', + ], + }, + help: i18n.translate('common.core_plugins.interpreter.public.functions.tsvb.help', { + defaultMessage: 'TSVB visualization' + }), + args: { + params: { + types: ['string'], + default: '"{}"', + }, + uiState: { + types: ['string'], + default: '"{}"', + } + }, + async fn(context, args) { + const $injector = await chrome.dangerouslyGetActiveInjector(); + const Private = $injector.get('Private'); + const metricsRequestHandler = Private(MetricsRequestHandlerProvider).handler; + + const params = JSON.parse(args.params); + const uiStateParams = JSON.parse(args.uiState); + const uiState = new PersistedState(uiStateParams); + + const response = await metricsRequestHandler({ + timeRange: get(context, 'timeRange', null), + query: get(context, 'query', null), + filters: get(context, 'filters', null), + visParams: params, + uiState: uiState, + }); + + return { + type: 'render', + as: 'visualization', + value: response, + }; + }, +}); diff --git a/src/legacy/core_plugins/interpreter/public/functions/vega.js b/src/legacy/core_plugins/interpreter/public/functions/vega.js new file mode 100644 index 0000000000000..52439e607c89e --- /dev/null +++ b/src/legacy/core_plugins/interpreter/public/functions/vega.js @@ -0,0 +1,70 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { get } from 'lodash'; +import { i18n } from '@kbn/i18n'; +import chrome from 'ui/chrome'; +import { VegaRequestHandlerProvider } from 'plugins/vega/vega_request_handler'; + +export const vega = () => ({ + name: 'vega', + type: 'render', + context: { + types: [ + 'kibana_context', + 'null', + ], + }, + help: i18n.translate('common.core_plugins.interpreter.public.functions.vega.help', { + defaultMessage: 'Vega visualization' + }), + args: { + spec: { + types: ['string'], + default: '', + }, + }, + async fn(context, args) { + const $injector = await chrome.dangerouslyGetActiveInjector(); + const Private = $injector.get('Private'); + const vegaRequestHandler = Private(VegaRequestHandlerProvider).handler; + + const response = await vegaRequestHandler({ + timeRange: get(context, 'timeRange', null), + query: get(context, 'q', null), + filters: get(context, 'filters', null), + visParams: { spec: args.spec }, + forceFetch: true + }); + + return { + type: 'render', + as: 'visualization', + value: { + visData: response, + visConfig: { + type: 'vega', + params: { + spec: args.spec + } + }, + } + }; + } +}); diff --git a/src/legacy/core_plugins/interpreter/public/functions/vislib.js b/src/legacy/core_plugins/interpreter/public/functions/vislib.js new file mode 100644 index 0000000000000..3ff0c6f0389d1 --- /dev/null +++ b/src/legacy/core_plugins/interpreter/public/functions/vislib.js @@ -0,0 +1,93 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { i18n } from '@kbn/i18n'; +import { VisTypesRegistryProvider } from 'ui/registry/vis_types'; +import { VislibSeriesResponseHandlerProvider } from 'ui/vis/response_handlers/vislib'; +import chrome from 'ui/chrome'; + +export const vislib = () => ({ + name: 'vislib', + type: 'render', + context: { + types: [ + 'kibana_table', 'null' + ], + }, + help: i18n.translate('common.core_plugins.interpreter.public.functions.vislib.help', { + defaultMessage: 'Vislib visualization' + }), + args: { + type: { + types: ['string'], + default: 'metric', + }, + schemas: { + types: ['string'], + default: '"{}"', + }, + visConfig: { + types: ['string', 'null'], + default: '"{}"', + }, + }, + async fn(context, args) { + const $injector = await chrome.dangerouslyGetActiveInjector(); + const Private = $injector.get('Private'); + const responseHandler = Private(VislibSeriesResponseHandlerProvider).handler; + const visTypes = Private(VisTypesRegistryProvider); + const visConfigParams = JSON.parse(args.visConfig); + const schemas = JSON.parse(args.schemas); + const visType = visTypes.byName[args.type || 'histogram']; + + if (context.columns) { + // assign schemas to aggConfigs + context.columns.forEach(column => { + column.aggConfig.aggConfigs.schemas = visType.schemas.all; + }); + + Object.keys(schemas).forEach(key => { + schemas[key].forEach(i => { + const schema = key.split('_'); + context.columns[i].aggConfig.schema = schema[0]; + if (schema[1] === 'row') { + context.columns[i].aggConfig.params.row = true; + } + }); + }); + } + + const convertedData = await responseHandler(context); + + return { + type: 'render', + as: 'visualization', + value: { + visData: convertedData, + visConfig: { + type: args.type, + params: visConfigParams, + }, + params: { + listenOnChange: true, + } + }, + }; + }, +}); diff --git a/src/legacy/core_plugins/interpreter/public/functions/visualization.js b/src/legacy/core_plugins/interpreter/public/functions/visualization.js new file mode 100644 index 0000000000000..2e37871c9750e --- /dev/null +++ b/src/legacy/core_plugins/interpreter/public/functions/visualization.js @@ -0,0 +1,147 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { get } from 'lodash'; +import { i18n } from '@kbn/i18n'; +import chrome from 'ui/chrome'; +import { VisRequestHandlersRegistryProvider as RequestHandlersProvider } from 'ui/registry/vis_request_handlers'; +import { VisResponseHandlersRegistryProvider as ResponseHandlerProvider } from 'ui/registry/vis_response_handlers'; +import { VisTypesRegistryProvider } from 'ui/registry/vis_types'; +import { IndexPatternsProvider } from 'ui/index_patterns'; +import { FilterBarQueryFilterProvider } from 'ui/filter_bar/query_filter'; +import { PersistedState } from 'ui/persisted_state'; + +function getHandler(from, type) { + if (typeof type === 'function') { + return type; + } + if (type === 'courier' || type === 'none') { + return null; + } + const handlerDesc = from.find(handler => handler.name === type); + if (!handlerDesc) { + throw new Error(`Could not find handler "${type}".`); + } + return handlerDesc.handler; +} + +export const visualization = () => ({ + name: 'visualization', + type: 'render', + context: { + types: [], + }, + help: i18n.translate('common.core_plugins.interpreter.public.functions.visualization.help', { + defaultMessage: 'A simple visualization' + }), + args: { + index: { + types: ['string', 'null'], + default: null, + }, + metricsAtAllLevels: { + types: ['boolean'], + default: false, + }, + partialRows: { + types: ['boolean'], + default: false, + }, + type: { + types: ['string'], + default: '', + }, + schemas: { + types: ['string'], + default: '"{}"', + }, + visConfig: { + types: ['string'], + default: '"{}"', + }, + uiState: { + types: ['string'], + default: '"{}"', + } + }, + async fn(context, args, handlers) { + const $injector = await chrome.dangerouslyGetActiveInjector(); + const Private = $injector.get('Private'); + const requestHandlers = Private(RequestHandlersProvider); + const responseHandlers = Private(ResponseHandlerProvider); + const visTypes = Private(VisTypesRegistryProvider); + const indexPatterns = Private(IndexPatternsProvider); + const queryFilter = Private(FilterBarQueryFilterProvider); + + const visConfigParams = JSON.parse(args.visConfig); + const schemas = JSON.parse(args.schemas); + const visType = visTypes.byName[args.type || 'histogram']; + const requestHandler = getHandler(requestHandlers, visType.requestHandler); + const responseHandler = getHandler(responseHandlers, visType.responseHandler); + const indexPattern = args.index ? await indexPatterns.get(args.index) : null; + + const uiStateParams = JSON.parse(args.uiState); + const uiState = new PersistedState(uiStateParams); + + if (requestHandler) { + context = await requestHandler({ + partialRows: args.partialRows, + metricsAtAllLevels: args.metricsAtAllLevels, + index: indexPattern, + visParams: visConfigParams, + timeRange: get(context, 'timeRange', null), + query: get(context, 'query', null), + filters: get(context, 'filters', null), + uiState: uiState, + inspectorAdapters: handlers.inspectorAdapters, + queryFilter, + forceFetch: true, + }); + } + + if (responseHandler) { + if (context.columns) { + // assign schemas to aggConfigs + context.columns.forEach(column => { + column.aggConfig.aggConfigs.schemas = visType.schemas.all; + }); + + Object.keys(schemas).forEach(key => { + schemas[key].forEach(i => { + context.columns[i].aggConfig.schema = key; + }); + }); + } + + context = await responseHandler(context); + } + + return { + type: 'render', + as: 'visualization', + value: { + visData: context, + visConfig: { + type: args.type, + params: visConfigParams + }, + } + }; + } +}); diff --git a/src/legacy/core_plugins/interpreter/public/load_browser_plugins.js b/src/legacy/core_plugins/interpreter/public/load_browser_plugins.js index de550f5c6a351..1025d283bf515 100644 --- a/src/legacy/core_plugins/interpreter/public/load_browser_plugins.js +++ b/src/legacy/core_plugins/interpreter/public/load_browser_plugins.js @@ -18,8 +18,11 @@ */ import chrome from 'ui/chrome'; -import { populateBrowserRegistries } from '@kbn/interpreter/public'; +import { populateBrowserRegistries, createSocket, initializeInterpreter } from '@kbn/interpreter/public'; import { typesRegistry, functionsRegistry } from '@kbn/interpreter/common'; +import { functions } from './functions'; + +const basePath = chrome.getBasePath(); const types = { commonFunctions: functionsRegistry, @@ -27,4 +30,13 @@ const types = { types: typesRegistry }; -populateBrowserRegistries(types, chrome.getBasePath()); +function addFunction(fnDef) { + functionsRegistry.register(fnDef); +} + +functions.forEach(addFunction); + +createSocket(basePath).then(async () => { + await populateBrowserRegistries(types, basePath); + await initializeInterpreter(); +}); diff --git a/src/legacy/core_plugins/kibana/public/discover/controllers/discover.js b/src/legacy/core_plugins/kibana/public/discover/controllers/discover.js index e8b16737af445..aceed75ee15cb 100644 --- a/src/legacy/core_plugins/kibana/public/discover/controllers/discover.js +++ b/src/legacy/core_plugins/kibana/public/discover/controllers/discover.js @@ -756,7 +756,7 @@ function discoverController( Promise .resolve(responseHandler(tabifiedData)) .then(resp => { - visualizeHandler.render(resp); + visualizeHandler.render({ value: resp }); }); } diff --git a/src/ui/public/vis/index.d.ts b/src/ui/public/vis/index.d.ts index a16588c89e708..4b8295367a322 100644 --- a/src/ui/public/vis/index.d.ts +++ b/src/ui/public/vis/index.d.ts @@ -18,7 +18,7 @@ */ export { AggConfig } from './agg_config'; -export { Vis, VisProvider } from './vis'; +export { Vis, VisProvider, VisState } from './vis'; export { VisualizationController, VisType } from './vis_types/vis_type'; export * from './request_handlers'; export * from './response_handlers'; diff --git a/src/ui/public/vis/response_handlers/legacy.js b/src/ui/public/vis/response_handlers/legacy.js index c91d562f1dc72..d90e426b9fa71 100644 --- a/src/ui/public/vis/response_handlers/legacy.js +++ b/src/ui/public/vis/response_handlers/legacy.js @@ -21,6 +21,14 @@ import _ from 'lodash'; import AggConfigResult from '../../vis/agg_config_result'; import { VisResponseHandlersRegistryProvider } from '../../registry/vis_response_handlers'; +const getSchema = column => { + return _.get(column, 'aggConfig.schema.name') || _.get(column, 'aggConfig.schema'); +}; + +const getType = column => { + return _.get(column, 'aggConfig.type.type') || _.get(column, 'aggConfig.type'); +}; + const LegacyResponseHandlerProvider = function () { return { @@ -30,12 +38,12 @@ const LegacyResponseHandlerProvider = function () { const converted = { tables: [] }; // check if there are buckets after the first metric - const metricsAtAllLevels = table.columns.findIndex(column => _.get(column, 'aggConfig.type.type') === 'metrics') < - _.findLastIndex(table.columns, column => _.get(column, 'aggConfig.type.type') === 'buckets'); + const metricsAtAllLevels = table.columns.findIndex(column => getType(column) === 'metrics') < + _.findLastIndex(table.columns, column => getType(column) === 'buckets'); - const splitColumn = table.columns.find(column => _.get(column, 'aggConfig.schema.name') === 'split'); - const numberOfMetrics = table.columns.filter(column => _.get(column, 'aggConfig.type.type') === 'metrics').length; - const numberOfBuckets = table.columns.filter(column => _.get(column, 'aggConfig.type.type') === 'buckets').length; + const splitColumn = table.columns.find(column => getSchema(column) === 'split'); + const numberOfMetrics = table.columns.filter(column => getType(column) === 'metrics').length; + const numberOfBuckets = table.columns.filter(column => getType(column) === 'buckets').length; const metricsPerBucket = numberOfMetrics / numberOfBuckets; if (splitColumn) { @@ -84,7 +92,7 @@ const LegacyResponseHandlerProvider = function () { column: table.columns.findIndex(c => c.id === column.id), row: rowIndex, }; - if (column.aggConfig.type.type === 'buckets') { + if (getType(column) === 'buckets') { previousSplitAgg = aggConfigResult; } return aggConfigResult; @@ -106,7 +114,7 @@ const LegacyResponseHandlerProvider = function () { column: columnIndex, row: rowIndex, }; - if (column.aggConfig.type.type === 'buckets') { + if (getType(column) === 'buckets') { previousSplitAgg = aggConfigResult; } return aggConfigResult; diff --git a/src/ui/public/vis/vis.d.ts b/src/ui/public/vis/vis.d.ts index ef2ac096f27f0..b5fb5390bf86c 100644 --- a/src/ui/public/vis/vis.d.ts +++ b/src/ui/public/vis/vis.d.ts @@ -30,3 +30,10 @@ export interface Vis { } export type VisProvider = (...dependencies: any[]) => Vis; + +export interface VisState { + title: string; + type: VisType; + params: any; + aggs: any[]; +} diff --git a/src/ui/public/visualize/loader/__tests__/visualize_data_loader.js b/src/ui/public/visualize/loader/__tests__/visualize_data_loader.js index fcd2b4b930618..4c2e31a46d7cb 100644 --- a/src/ui/public/visualize/loader/__tests__/visualize_data_loader.js +++ b/src/ui/public/visualize/loader/__tests__/visualize_data_loader.js @@ -60,14 +60,6 @@ describe('visualize data loader', () => { })); setupAndTeardownInjectorStub(); - it('should have a requestHandler', () => { - expect(visualizeDataLoader.requestHandler).to.be.a('function'); - }); - - it('should have a responseHandler', () => { - expect(visualizeDataLoader.responseHandler).to.be.a('function'); - }); - describe('fetch', () => { it('should be a function', () => { expect(visualizeDataLoader.fetch).to.be.a('function'); diff --git a/src/ui/public/visualize/loader/__tests__/visualize_loader.js b/src/ui/public/visualize/loader/__tests__/visualize_loader.js index 3f870e94d65e9..6f73ac872c539 100644 --- a/src/ui/public/visualize/loader/__tests__/visualize_loader.js +++ b/src/ui/public/visualize/loader/__tests__/visualize_loader.js @@ -32,7 +32,7 @@ import { getVisualizeLoader } from '../visualize_loader'; import { EmbeddedVisualizeHandler } from '../embedded_visualize_handler'; import { Inspector } from '../../../inspector/inspector'; import { dispatchRenderComplete } from '../../../render_complete'; -import { VisualizeDataLoader } from '../visualize_data_loader'; +import { PipelineDataLoader } from '../pipeline_data_loader'; import { PersistedState } from '../../../persisted_state'; import { DataAdapter } from '../../../inspector/adapters/data'; import { RequestAdapter } from '../../../inspector/adapters/request'; @@ -420,7 +420,7 @@ describe('visualize loader', () => { }); it('should allow updating the time range of the visualization', async () => { - const spy = sandbox.spy(VisualizeDataLoader.prototype, 'fetch'); + const spy = sandbox.spy(PipelineDataLoader.prototype, 'fetch'); const handler = loader.embedVisualizationWithSavedObject(newContainer()[0], createSavedObject(), { timeRange: { from: 'now-7d', to: 'now' } @@ -442,7 +442,7 @@ describe('visualize loader', () => { }); it('should not set forceFetch on uiState change', async () => { - const spy = sandbox.spy(VisualizeDataLoader.prototype, 'fetch'); + const spy = sandbox.spy(PipelineDataLoader.prototype, 'fetch'); const uiState = new PersistedState(); loader.embedVisualizationWithSavedObject(newContainer()[0], createSavedObject(), { diff --git a/src/ui/public/visualize/loader/embedded_visualize_handler.ts b/src/ui/public/visualize/loader/embedded_visualize_handler.ts index 39d19d12592a7..a78a1376efb74 100644 --- a/src/ui/public/visualize/loader/embedded_visualize_handler.ts +++ b/src/ui/public/visualize/loader/embedded_visualize_handler.ts @@ -29,8 +29,9 @@ import { RenderCompleteHelper } from '../../render_complete'; import { AppState } from '../../state_management/app_state'; import { timefilter } from '../../timefilter'; import { RequestHandlerParams, Vis } from '../../vis'; +// import { VisualizeDataLoader } from './visualize_data_loader'; +import { PipelineDataLoader } from './pipeline_data_loader'; import { visualizationLoader } from './visualization_loader'; -import { VisualizeDataLoader } from './visualize_data_loader'; import { DataAdapter, RequestAdapter } from '../../inspector/adapters'; @@ -80,7 +81,7 @@ export class EmbeddedVisualizeHandler { private dataLoaderParams: RequestHandlerParams; private readonly appState?: AppState; private uiState: PersistedState; - private dataLoader: VisualizeDataLoader; + private dataLoader: PipelineDataLoader; private dataSubject: Rx.Subject; private actions: any = {}; private events$: Rx.Observable; @@ -93,16 +94,7 @@ export class EmbeddedVisualizeHandler { ) { const { searchSource, vis } = savedObject; - const { - appState, - uiState, - queryFilter, - timeRange, - filters, - query, - Private, - autoFetch, - } = params; + const { appState, uiState, queryFilter, timeRange, filters, query, autoFetch } = params; this.dataLoaderParams = { searchSource, @@ -137,7 +129,7 @@ export class EmbeddedVisualizeHandler { this.uiState.on('change', this.onUiStateChange); timefilter.on('autoRefreshFetch', this.reload); - this.dataLoader = new VisualizeDataLoader(vis, Private); + this.dataLoader = new PipelineDataLoader(vis); this.renderCompleteHelper = new RenderCompleteHelper(element); this.inspectorAdapters = this.getActiveInspectorAdapters(); this.vis.openInspector = this.openInspector; @@ -235,7 +227,14 @@ export class EmbeddedVisualizeHandler { * renders visualization with provided data * @param visData: visualization data */ - public render = (visData: any = null) => { + public render = (pipelineResponse: any = null) => { + let visData; + if (pipelineResponse) { + if (!pipelineResponse.value) { + throw new Error(pipelineResponse.error); + } + visData = pipelineResponse.value.visData || pipelineResponse.value; + } return visualizationLoader .render(this.element, this.vis, visData, this.uiState, { listenOnChange: false, @@ -378,6 +377,8 @@ export class EmbeddedVisualizeHandler { this.dataLoaderParams.forceFetch = forceFetch; this.dataLoaderParams.inspectorAdapters = this.inspectorAdapters; + this.vis.filters = { timeRange: this.dataLoaderParams.timeRange }; + return this.dataLoader.fetch(this.dataLoaderParams).then(data => { this.dataSubject.next(data); return data; diff --git a/src/ui/public/visualize/loader/pipeline_data_loader.ts b/src/ui/public/visualize/loader/pipeline_data_loader.ts new file mode 100644 index 0000000000000..ac5c7c0a09bbb --- /dev/null +++ b/src/ui/public/visualize/loader/pipeline_data_loader.ts @@ -0,0 +1,46 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { RequestHandlerParams, Vis } from '../../vis'; +import { buildPipeline, runPipeline } from './pipeline_helpers'; + +export class PipelineDataLoader { + constructor(private readonly vis: Vis) {} + + public async fetch(params: RequestHandlerParams): Promise { + this.vis.requestError = undefined; + this.vis.showRequestError = false; + this.vis.pipelineExpression = buildPipeline(this.vis, params); + + return await runPipeline( + this.vis.pipelineExpression, + {}, + { + getInitialContext: () => ({ + query: params.query, + timeRange: params.timeRange, + filters: params.filters + ? params.filters.filter(filter => !filter.meta.disabled) + : undefined, + }), + inspectorAdapters: params.inspectorAdapters, + } + ); + } +} diff --git a/src/ui/public/visualize/loader/pipeline_helpers/__snapshots__/build_pipeline.test.js.snap b/src/ui/public/visualize/loader/pipeline_helpers/__snapshots__/build_pipeline.test.js.snap new file mode 100644 index 0000000000000..41998b84691b6 --- /dev/null +++ b/src/ui/public/visualize/loader/pipeline_helpers/__snapshots__/build_pipeline.test.js.snap @@ -0,0 +1,31 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`visualize loader pipeline helpers: build pipeline buildPipelineVisFunction handles input_control_vis function 1`] = `"input_control_vis visConfig='{\\"some\\":\\"nested\\",\\"data\\":{\\"here\\":true}}' "`; + +exports[`visualize loader pipeline helpers: build pipeline buildPipelineVisFunction handles markdown function 1`] = `"kibana_markdown expression='## hello _markdown_' visConfig='{\\"markdown\\":\\"## hello _markdown_\\",\\"foo\\":\\"bar\\"}' "`; + +exports[`visualize loader pipeline helpers: build pipeline buildPipelineVisFunction handles metric function with buckets 1`] = `"kibana_metric visConfig='{\\"foo\\":\\"bar\\"}' bucket='2' metric='0,1' "`; + +exports[`visualize loader pipeline helpers: build pipeline buildPipelineVisFunction handles metric function without buckets 1`] = `"kibana_metric visConfig='{\\"foo\\":\\"bar\\"}' metric='0,1' "`; + +exports[`visualize loader pipeline helpers: build pipeline buildPipelineVisFunction handles metrics/tsvb function 1`] = `"tsvb params='{\\"foo\\":\\"bar\\"}' "`; + +exports[`visualize loader pipeline helpers: build pipeline buildPipelineVisFunction handles pie function 1`] = `"kibana_pie visConfig='{\\"foo\\":\\"bar\\"}' schemas='{\\"baz\\":\\"qux\\"}' "`; + +exports[`visualize loader pipeline helpers: build pipeline buildPipelineVisFunction handles region_map function with metrics and buckets 1`] = `"regionmap visConfig='{\\"foo\\":\\"bar\\"}' bucket='1,2' metric='0' "`; + +exports[`visualize loader pipeline helpers: build pipeline buildPipelineVisFunction handles table function with splits 1`] = `"kibana_table visConfig='{\\"foo\\":\\"bar\\"}' splitRow='1,2' metric='0' "`; + +exports[`visualize loader pipeline helpers: build pipeline buildPipelineVisFunction handles table function with splits and buckets 1`] = `"kibana_table visConfig='{\\"foo\\":\\"bar\\"}' splitRow='2,4' bucket='3' metric='0,1' "`; + +exports[`visualize loader pipeline helpers: build pipeline buildPipelineVisFunction handles table function without splits or buckets 1`] = `"kibana_table visConfig='{\\"foo\\":\\"bar\\"}' metric='0,1' "`; + +exports[`visualize loader pipeline helpers: build pipeline buildPipelineVisFunction handles tagcloud function with metrics and buckets 1`] = `"tagcloud visConfig='{\\"foo\\":\\"bar\\"}' bucket='1,2' metric='0' "`; + +exports[`visualize loader pipeline helpers: build pipeline buildPipelineVisFunction handles tile_map function with metrics and buckets 1`] = `"tilemap visConfig='{\\"foo\\":\\"bar\\"}' bucket='1,2' metric='0' "`; + +exports[`visualize loader pipeline helpers: build pipeline buildPipelineVisFunction handles tile_map function without buckets 1`] = `"tilemap visConfig='{\\"foo\\":\\"bar\\"}' metric='0' "`; + +exports[`visualize loader pipeline helpers: build pipeline buildPipelineVisFunction handles timelion function 1`] = `"timelion_vis expression='foo' interval='bar' "`; + +exports[`visualize loader pipeline helpers: build pipeline buildPipelineVisFunction handles vega function 1`] = `"vega spec='this is a test' "`; diff --git a/src/ui/public/visualize/loader/pipeline_helpers/build_pipeline.test.js b/src/ui/public/visualize/loader/pipeline_helpers/build_pipeline.test.js new file mode 100644 index 0000000000000..9290706545d99 --- /dev/null +++ b/src/ui/public/visualize/loader/pipeline_helpers/build_pipeline.test.js @@ -0,0 +1,202 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { prepareJson, prepareString, buildPipelineVisFunction } from './build_pipeline'; + +describe('visualize loader pipeline helpers: build pipeline', () => { + describe('prepareJson', () => { + it('returns a correctly formatted key/value string', () => { + const expected = `foo='{}' `; // trailing space is expected + const actual = prepareJson('foo', {}); + expect(actual).toBe(expected); + }); + + it('stringifies provided data', () => { + const expected = `foo='{\"well\":\"hello\",\"there\":{\"friend\":true}}' `; + const actual = prepareJson('foo', { well: 'hello', there: { friend: true } }); + expect(actual).toBe(expected); + }); + + it('escapes single quotes', () => { + const expected = `foo='{\"well\":\"hello \\'hi\\'\",\"there\":{\"friend\":true}}' `; + const actual = prepareJson('foo', { well: `hello 'hi'`, there: { friend: true } }); + expect(actual).toBe(expected); + }); + }); + + describe('prepareString', () => { + it('returns a correctly formatted key/value string', () => { + const expected = `foo='bar' `; // trailing space is expected + const actual = prepareString('foo', 'bar'); + expect(actual).toBe(expected); + }); + + it('escapes single quotes', () => { + const expected = `foo='\\'bar\\'' `; + const actual = prepareString('foo', `'bar'`); + expect(actual).toBe(expected); + }); + }); + + describe('buildPipelineVisFunction', () => { + it('handles vega function', () => { + const params = { spec: 'this is a test' }; + const actual = buildPipelineVisFunction.vega({ params }); + expect(actual).toMatchSnapshot(); + }); + + it('handles input_control_vis function', () => { + const params = { + some: 'nested', + data: { + here: true + } + }; + const actual = buildPipelineVisFunction.input_control_vis({ params }); + expect(actual).toMatchSnapshot(); + }); + + it('handles metrics/tsvb function', () => { + const params = { foo: 'bar' }; + const actual = buildPipelineVisFunction.metrics({ params }); + expect(actual).toMatchSnapshot(); + }); + + it('handles timelion function', () => { + const params = { expression: 'foo', interval: 'bar' }; + const actual = buildPipelineVisFunction.timelion({ params }); + expect(actual).toMatchSnapshot(); + }); + + it('handles markdown function', () => { + const params = { markdown: '## hello _markdown_', foo: 'bar' }; + const actual = buildPipelineVisFunction.markdown({ params }); + expect(actual).toMatchSnapshot(); + }); + + describe('handles table function', () => { + const params = { foo: 'bar' }; + it('without splits or buckets', () => { + const schemas = { metric: [0, 1] }; + const actual = buildPipelineVisFunction.table({ params }, schemas); + expect(actual).toMatchSnapshot(); + }); + + it('with splits', () => { + const schemas = { + metric: [0], + split_row: [1, 2], + }; + const actual = buildPipelineVisFunction.table({ params }, schemas); + expect(actual).toMatchSnapshot(); + }); + + it('with splits and buckets', () => { + const schemas = { + metric: [0, 1], + split_row: [2, 4], + bucket: [3] + }; + const actual = buildPipelineVisFunction.table({ params }, schemas); + expect(actual).toMatchSnapshot(); + }); + }); + + describe('handles metric function', () => { + const params = { foo: 'bar' }; + it('without buckets', () => { + const schemas = { metric: [0, 1] }; + const actual = buildPipelineVisFunction.metric({ params }, schemas); + expect(actual).toMatchSnapshot(); + }); + + it('with buckets', () => { + const schemas = { + metric: [0, 1], + bucket: [2] + }; + const actual = buildPipelineVisFunction.metric({ params }, schemas); + expect(actual).toMatchSnapshot(); + }); + }); + + describe('handles tagcloud function', () => { + const params = { foo: 'bar' }; + it('with metrics and buckets', () => { + const schemas = { + metric: [0], + segment: [1, 2] + }; + const actual = buildPipelineVisFunction.tagcloud({ params }, schemas); + expect(actual).toMatchSnapshot(); + }); + + it('throws without bucket', () => { + const schemas = { metric: [0] }; + expect(() => { + buildPipelineVisFunction.tagcloud({ params }, schemas); + }).toThrow(TypeError); + }); + }); + + describe('handles region_map function', () => { + const params = { foo: 'bar' }; + it('with metrics and buckets', () => { + const schemas = { + metric: [0], + segment: [1, 2] + }; + const actual = buildPipelineVisFunction.region_map({ params }, schemas); + expect(actual).toMatchSnapshot(); + }); + + it('throws without bucket', () => { + const schemas = { metric: [0] }; + expect(() => { + buildPipelineVisFunction.region_map({ params }, schemas); + }).toThrow(TypeError); + }); + }); + + describe('handles tile_map function', () => { + const params = { foo: 'bar' }; + it('with metrics and buckets', () => { + const schemas = { + metric: [0], + segment: [1, 2] + }; + const actual = buildPipelineVisFunction.tile_map({ params }, schemas); + expect(actual).toMatchSnapshot(); + }); + + it('without buckets', () => { + const schemas = { metric: [0] }; + const actual = buildPipelineVisFunction.tile_map({ params }, schemas); + expect(actual).toMatchSnapshot(); + }); + }); + + it('handles pie function', () => { + const params = { foo: 'bar' }; + const schemas = { baz: 'qux' }; + const actual = buildPipelineVisFunction.pie({ params }, schemas); + expect(actual).toMatchSnapshot(); + }); + }); +}); diff --git a/src/ui/public/visualize/loader/pipeline_helpers/build_pipeline.ts b/src/ui/public/visualize/loader/pipeline_helpers/build_pipeline.ts new file mode 100644 index 0000000000000..20a6b27febec4 --- /dev/null +++ b/src/ui/public/visualize/loader/pipeline_helpers/build_pipeline.ts @@ -0,0 +1,207 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { SearchSource } from 'ui/courier'; +import { AggConfig, Vis, VisState } from 'ui/vis'; + +interface Schemas { + metric: number[]; + [key: string]: number[]; +} + +type buildVisFunction = (visState: VisState, schemas: Schemas) => string; + +interface BuildPipelineVisFunction { + [key: string]: buildVisFunction; +} + +const vislibCharts: string[] = [ + 'area', + 'gauge', + 'goal', + 'heatmap', + 'histogram', + 'horizontal_bar', + 'line', +]; + +export const getSchemas = (vis: Vis): Schemas => { + let cnt = 0; + const schemas: Schemas = { + metric: [], + }; + const responseAggs = vis.aggs.getResponseAggs(); + const isHierarchical = vis.isHierarchical(); + const metrics = responseAggs.filter((agg: AggConfig) => agg.type.type === 'metrics'); + responseAggs.forEach((agg: AggConfig) => { + if (!agg.enabled) { + return; + } + let schemaName = agg.schema ? agg.schema.name || agg.schema : null; + if (typeof schemaName === 'object') { + schemaName = null; + } + if (!schemaName) { + return; + } + if (schemaName === 'split') { + schemaName = `split_${agg.params.row ? 'row' : 'column'}`; + } + if (!schemas[schemaName]) { + schemas[schemaName] = []; + } + if (!isHierarchical || agg.type.type !== 'metrics') { + schemas[schemaName].push(cnt++); + } + if (isHierarchical && agg.type.type !== 'metrics') { + metrics.forEach(() => { + schemas.metric.push(cnt++); + }); + } + }); + return schemas; +}; + +export const prepareJson = (variable: string, data: object): string => { + return `${variable}='${JSON.stringify(data) + .replace(/\\/g, `\\\\`) + .replace(/'/g, `\\'`)}' `; +}; + +export const prepareString = (variable: string, data: string): string => { + return `${variable}='${data.replace(/\\/g, `\\\\`).replace(/'/g, `\\'`)}' `; +}; + +export const buildPipelineVisFunction: BuildPipelineVisFunction = { + vega: visState => { + return `vega ${prepareString('spec', visState.params.spec)}`; + }, + input_control_vis: visState => { + return `input_control_vis ${prepareJson('visConfig', visState.params)}`; + }, + metrics: visState => { + return `tsvb ${prepareJson('params', visState.params)}`; + }, + timelion: visState => { + const expression = prepareString('expression', visState.params.expression); + const interval = prepareString('interval', visState.params.interval); + return `timelion_vis ${expression}${interval}`; + }, + markdown: visState => { + const expression = prepareString('expression', visState.params.markdown); + const visConfig = prepareJson('visConfig', visState.params); + return `kibana_markdown ${expression}${visConfig}`; + }, + table: (visState, schemas) => { + let pipeline = `kibana_table ${prepareJson('visConfig', visState.params)}`; + if (schemas.split_row) { + pipeline += `splitRow='${schemas.split_row.join(',')}' `; + } + if (schemas.split_column) { + pipeline += `splitColumn='${schemas.split_column.join(',')}' `; + } + if (schemas.bucket) { + pipeline += `bucket='${schemas.bucket.join(',')}' `; + } + pipeline += `metric='${schemas.metric.join(',')}' `; + return pipeline; + }, + metric: (visState, schemas) => { + let pipeline = `kibana_metric ${prepareJson('visConfig', visState.params)}`; + if (schemas.bucket) { + pipeline += `bucket='${schemas.bucket.join(',')}' `; + } + pipeline += `metric='${schemas.metric.join(',')}' `; + return pipeline; + }, + tagcloud: (visState, schemas) => { + let pipeline = `tagcloud ${prepareJson('visConfig', visState.params)}`; + pipeline += `bucket='${schemas.segment.join(',')}' `; + pipeline += `metric='${schemas.metric.join(',')}' `; + return pipeline; + }, + region_map: (visState, schemas) => { + let pipeline = `regionmap ${prepareJson('visConfig', visState.params)}`; + pipeline += `bucket='${schemas.segment.join(',')}' `; + pipeline += `metric='${schemas.metric.join(',')}' `; + return pipeline; + }, + tile_map: (visState, schemas) => { + let pipeline = `tilemap ${prepareJson('visConfig', visState.params)}`; + if (schemas.segment) { + pipeline += `bucket='${schemas.segment.join(',')}' `; + } + pipeline += `metric='${schemas.metric.join(',')}' `; + return pipeline; + }, + pie: (visState, schemas) => { + const visConfig = prepareJson('visConfig', visState.params); + const visSchemas = prepareJson('schemas', schemas); + return `kibana_pie ${visConfig}${visSchemas}`; + }, +}; + +export const buildPipeline = (vis: Vis, params: { searchSource: SearchSource }) => { + const { searchSource } = params; + const { indexPattern } = vis; + const query = searchSource.getField('query'); + const filters = searchSource.getField('filter'); + const visState = vis.getCurrentState(); + + // context + let pipeline = `kibana | kibana_context `; + if (query) { + pipeline += prepareJson('query', query); + } + if (filters) { + pipeline += prepareJson('filters', filters); + } + if (vis.savedSearchId) { + pipeline += prepareString('savedSearchId', vis.savedSearchId); + } + pipeline += '| '; + + // request handler + if (vis.type.requestHandler === 'courier') { + pipeline += `esaggs + ${prepareString('index', indexPattern.id)} + metricsAtAllLevels=${vis.isHierarchical()} + partialRows=${vis.params.showPartialRows || vis.type.requiresPartialRows || false} + ${prepareJson('aggConfigs', visState.aggs)} | `; + } + + const schemas = getSchemas(vis); + if (buildPipelineVisFunction[vis.type.name]) { + pipeline += buildPipelineVisFunction[vis.type.name](visState, schemas); + } else if (vislibCharts.includes(vis.type.name)) { + pipeline += `vislib type='${vis.type.name}' + ${prepareJson('visConfig', visState.params)} + ${prepareJson('schemas', schemas)}`; + } else { + pipeline += `visualization type='${vis.type.name}' + ${prepareJson('visConfig', visState.params)} + metricsAtAllLevels=${vis.isHierarchical()} + partialRows=${vis.params.showPartialRows || vis.type.name === 'tile_map'} `; + if (indexPattern) { + pipeline += `${prepareString('index', indexPattern.id)}`; + } + } + + return pipeline; +}; diff --git a/src/ui/public/visualize/loader/pipeline_helpers/index.ts b/src/ui/public/visualize/loader/pipeline_helpers/index.ts new file mode 100644 index 0000000000000..69c29339a8713 --- /dev/null +++ b/src/ui/public/visualize/loader/pipeline_helpers/index.ts @@ -0,0 +1,21 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export { buildPipeline } from './build_pipeline'; +export { runPipeline } from './run_pipeline'; diff --git a/src/ui/public/visualize/loader/pipeline_helpers/run_pipeline.ts b/src/ui/public/visualize/loader/pipeline_helpers/run_pipeline.ts new file mode 100644 index 0000000000000..a3b98570c870f --- /dev/null +++ b/src/ui/public/visualize/loader/pipeline_helpers/run_pipeline.ts @@ -0,0 +1,29 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +// @ts-ignore +import { fromExpression } from '@kbn/interpreter/common'; +// @ts-ignore +import { interpretAst } from '@kbn/interpreter/public'; + +export const runPipeline = async (expression: string, context: any, handlers: any) => { + const ast = fromExpression(expression); + const pipelineResponse = await interpretAst(ast, context, handlers); + return pipelineResponse; +}; diff --git a/test/functional/apps/visualize/_data_table.js b/test/functional/apps/visualize/_data_table.js index 5cd9b280c5550..0c3d200cf8000 100644 --- a/test/functional/apps/visualize/_data_table.js +++ b/test/functional/apps/visualize/_data_table.js @@ -392,9 +392,9 @@ export default function ({ getService, getPageObjects }) { ]); }); - it('should allow nesting multiple splits', async () => { + it.skip('should allow nesting multiple splits', async () => { // This test can be removed as soon as we remove the nested split table - // feature (https://github.com/elastic/kibana/issues/24560). + // feature (https://github.com/elastic/kibana/issues/24560). (7.0) await PageObjects.visualize.clickData(); await PageObjects.visualize.clickAddBucket(); await PageObjects.visualize.clickBucket('Split Table'); diff --git a/test/plugin_functional/test_suites/embedding_visualizations/embed_by_id.js b/test/plugin_functional/test_suites/embedding_visualizations/embed_by_id.js index e068627e5e80e..bd0866882c1fc 100644 --- a/test/plugin_functional/test_suites/embedding_visualizations/embed_by_id.js +++ b/test/plugin_functional/test_suites/embedding_visualizations/embed_by_id.js @@ -18,6 +18,7 @@ */ import expect from 'expect.js'; +import { delay } from 'bluebird'; export default function ({ getService }) { const testSubjects = getService('testSubjects'); @@ -36,6 +37,7 @@ export default function ({ getService }) { await retry.try(async () => { await testSubjects.waitForDeleted('visLoadingIndicator'); }); + await delay(1000); } async function getTableData() { diff --git a/x-pack/plugins/canvas/public/components/app/index.js b/x-pack/plugins/canvas/public/components/app/index.js index f5fc65e029f36..b3a9fcc79036e 100644 --- a/x-pack/plugins/canvas/public/components/app/index.js +++ b/x-pack/plugins/canvas/public/components/app/index.js @@ -4,11 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { - createSocket, - initializeInterpreter, - populateBrowserRegistries, -} from '@kbn/interpreter/public'; +import { populateBrowserRegistries, getInitializedFunctions } from '@kbn/interpreter/public'; import { connect } from 'react-redux'; import { compose, withProps } from 'recompose'; import { getAppReady, getBasePath } from '../../state/selectors/app'; @@ -51,10 +47,9 @@ const mapDispatchToProps = dispatch => ({ setAppReady: basePath => async () => { try { // initialize the socket and interpreter - await createSocket(basePath); loadPrivateBrowserFunctions(); await populateBrowserRegistries(types, basePath); - await initializeInterpreter(); + await getInitializedFunctions(); // set app state to ready dispatch(appReady()); From f6c306be2cf44dadf49c63653287f245621abf4e Mon Sep 17 00:00:00 2001 From: Tiago Costa Date: Mon, 10 Dec 2018 17:41:51 +0000 Subject: [PATCH 32/85] Upgrade to NodeJS 10 (#25157) * feat(NA): upgrade node js version on file configs. * chore(NA): migrate configs and 3rd party dependencies to work on node js 10.x * fix(NA): add missing async function declaration. * chore(NA): updated elastic/good package to work with node10 * chore(NA): update lockfiles. * fix(NA): add missing dep. * fix(NA): types for node 10. * test(NA): fix error return type for node10. * fix(NA): kbn-pm webpack config to unlazy a require using lazy-cache. fix(NA): build to work with node 10. * test(NA): jest integration test for kbn-pluin-helpers. * test(NA): fix jest tests for kbn-es. * fix(NA): use ostmpdir instead of a tmp folder inside the fixtures. * fix(NA): change afterEach on kbn es decompress test. * fix(NA): change afterEach on kbn es decompress test. * fix(NA): readd mock-fs for the tests that still use it on kbn-es and that works on node10. * fix(NA): readd mock-fs for the tests that still use it on kbn-es and that works on node10. * refact(NA): rewrite tests using mock-fs and completely remove this dependency. * fix(NA): failing test implementation using jest mock in order to replace mock-fs. * fix(NA): update jest snapshots to match new ones generated one node 10. * fix(NA): cli/cluster mock to spyOn off method instead off spyOn removeListener as this was changed on Node 10. * fix(NA): tests for cluster_manager to also spyOn off and on instead of addListener and removeListener * test(NA): fix management advance settings image field test flow. * fix(NA): apply missing types for src/core/server/plugins/discovery/plugins_discovery.ts. * test(NA): updated 2 missing snapshots for KuiCodeEditor on kbn-ui-framework. * refact(NA): fix eslint errors. * refact(NA): fix ts code with tslint fix. chore(NA): update jest snapshots. * chore(NA): migrate kbn config schema peer dependency to last used joi version to avoid warning on bootstrap. * fix(NA): tslint errors. * chore(NA): upgrade types node to the last version. * fix(NA): missing utf8 input format encoding when reading a file. * chore(NA): upgrade to node 10.14.1 * fix(NA): Buffer api usage to avoid deprecation warnings. --- .node-version | 2 +- .nvmrc | 2 +- package.json | 21 +- packages/kbn-babel-code-parser/package.json | 4 +- packages/kbn-config-schema/package.json | 2 +- packages/kbn-dev-utils/package.json | 2 +- packages/kbn-es/package.json | 8 +- packages/kbn-es/src/utils/decompress.test.js | 36 +- .../src/utils/extract_config_files.test.js | 24 +- .../utils/find_most_recently_changed.test.js | 47 +- .../src/__snapshots__/loader.test.ts.snap | 2 +- packages/kbn-plugin-generator/package.json | 2 +- packages/kbn-plugin-helpers/package.json | 2 +- .../integration_tests/create_build.test.js | 4 +- packages/kbn-pm/dist/index.js | 52147 ++++++++++++---- packages/kbn-pm/package.json | 9 +- packages/kbn-pm/webpack.config.js | 15 + packages/kbn-ui-framework/package.json | 2 +- src/cli/cluster/__mocks__/cluster.js | 2 +- src/cli/cluster/cluster_manager.test.js | 36 +- src/cli/cluster/worker.test.js | 5 +- src/cli_keystore/add.test.js | 34 +- src/cli_keystore/create.test.js | 34 +- src/cli_keystore/list.test.js | 34 +- src/cli_keystore/remove.test.js | 28 +- src/cli_plugin/install/kibana.test.js | 20 +- .../public/injected_metadata/deep_freeze.ts | 4 +- src/core/server/config/config_service.ts | 4 +- src/core/server/http/http_tools.ts | 2 +- .../plugins/discovery/plugins_discovery.ts | 2 +- src/dev/build/lib/scan_delete.ts | 2 +- .../data/__snapshots__/data_view.test.js.snap | 2 - .../public/dashboard/actions/embeddables.ts | 6 +- .../settings/components/field/field.test.js | 4 + .../wizard/type_selection/vis_type_icon.tsx | 7 +- .../plugin_spec/__tests__/plugin_spec.js | 2 +- src/server/keystore/keystore.js | 2 +- src/server/keystore/keystore.test.js | 59 +- src/server/logging/index.js | 4 +- .../migrations/core/build_active_mappings.ts | 2 +- .../migrations/core/document_migrator.ts | 6 +- .../migrations/core/migration_coordinator.ts | 2 +- src/test_utils/kbn_server.ts | 2 +- src/ui/public/crypto/sha256.js | 6 +- src/ui/public/share/share_action.ts | 2 +- src/ui/public/state_management/state.d.ts | 4 +- .../ui_render/bootstrap/app_bootstrap.test.js | 18 +- x-pack/package.json | 26 +- .../waterfall_helpers.test.ts | 5 +- .../waterfall_helpers/waterfall_helpers.ts | 5 +- .../app/TransactionOverview/view.js | 7 +- .../shared/Stacktrace/LibraryFrames.tsx | 23 +- .../charts/CustomPlot/InteractivePlot.js | 7 +- .../components/autocomplete_field/index.tsx | 12 +- .../public/components/table/table.tsx | 17 +- .../containers/with_kuery_autocompletion.tsx | 21 +- .../adapters/beats/memory_beats_adapter.ts | 66 +- .../public/pages/beat/index.tsx | 39 +- .../adapters/beats/memory_beats_adapter.ts | 54 +- .../datetime_quick_list.js | 21 +- .../components/arg_form/advanced_failure.js | 11 +- .../arg_types/series_style/simple_template.js | 19 +- .../canvas/public/lib/aeroelastic/gestures.js | 9 +- .../canvas/public/lib/aeroelastic/layout.js | 155 +- .../infra/common/graphql/typed_resolvers.ts | 8 +- .../autocomplete_field/autocomplete_field.tsx | 12 +- .../containers/logs/with_stream_items.ts | 4 +- .../containers/with_kuery_autocompletion.tsx | 21 +- .../store/local/waffle_time/selectors.ts | 13 +- .../remote_state/remote_graphql_state.ts | 40 +- .../plugins/infra/public/utils/typed_redux.ts | 4 +- .../server/lib/get_document_payload.js | 2 +- .../reporting/server/routes/jobs.test.js | 2 +- .../lib/authentication/providers/basic.js | 2 +- .../apis/security/basic_login.js | 8 +- .../fixtures/saml_tools.js | 6 +- yarn.lock | 2054 +- 77 files changed, 40427 insertions(+), 14912 deletions(-) diff --git a/.node-version b/.node-version index 2a5dd0d63896a..fd79f9e982b6a 100644 --- a/.node-version +++ b/.node-version @@ -1 +1 @@ -8.14.0 +10.14.1 diff --git a/.nvmrc b/.nvmrc index 2a5dd0d63896a..fd79f9e982b6a 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -8.14.0 +10.14.1 diff --git a/package.json b/package.json index 89ec90dfd0f4e..c668cce2bc510 100644 --- a/package.json +++ b/package.json @@ -72,7 +72,7 @@ "url": "https://github.com/elastic/kibana.git" }, "resolutions": { - "**/@types/node": "8.10.38", + "**/@types/node": "10.12.12", "@types/react": "16.3.14" }, "workspaces": { @@ -95,7 +95,7 @@ "@elastic/datemath": "5.0.1", "@elastic/eui": "5.3.0", "@elastic/filesaver": "1.1.2", - "@elastic/good": "8.1.1-kibana1", + "@elastic/good": "8.1.1-kibana2", "@elastic/numeral": "2.3.2", "@elastic/ui-ace": "0.2.3", "@kbn/babel-code-parser": "1.0.0", @@ -137,7 +137,7 @@ "elasticsearch": "^15.2.0", "elasticsearch-browser": "^15.2.0", "encode-uri-query": "1.0.0", - "execa": "^0.10.0", + "execa": "^1.0.0", "expiry-js": "0.1.7", "file-loader": "2.0.0", "font-awesome": "4.4.0", @@ -285,7 +285,7 @@ "@types/minimatch": "^2.0.29", "@types/moment-timezone": "^0.5.8", "@types/mustache": "^0.8.31", - "@types/node": "^8.10.38", + "@types/node": "^10.12.12", "@types/opn": "^5.1.0", "@types/podium": "^1.0.0", "@types/prop-types": "^15.5.3", @@ -308,7 +308,7 @@ "angular-mocks": "1.4.7", "archiver": "^3.0.0", "babel-eslint": "^9.0.0", - "babel-jest": "^23.4.2", + "babel-jest": "^23.6.0", "backport": "4.4.1", "chai": "3.5.0", "chance": "1.0.10", @@ -325,7 +325,7 @@ "eslint-config-prettier": "^3.1.0", "eslint-plugin-babel": "^5.2.0", "eslint-plugin-import": "^2.14.0", - "eslint-plugin-jest": "^21.22.1", + "eslint-plugin-jest": "^21.26.2", "eslint-plugin-jsx-a11y": "^6.1.2", "eslint-plugin-mocha": "^5.2.0", "eslint-plugin-no-unsanitized": "^3.0.2", @@ -345,13 +345,13 @@ "grunt-peg": "^2.0.1", "grunt-run": "0.7.0", "gulp-babel": "^7.0.1", - "gulp-sourcemaps": "1.7.3", + "gulp-sourcemaps": "2.6.4", "has-ansi": "^3.0.0", "image-diff": "1.6.0", "intl-messageformat-parser": "^1.4.0", "istanbul-instrumenter-loader": "3.0.1", - "jest": "^23.5.0", - "jest-cli": "^23.5.0", + "jest": "^23.6.0", + "jest-cli": "^23.6.0", "jest-raw-loader": "^1.0.1", "jimp": "0.2.28", "json5": "^1.0.1", @@ -369,7 +369,6 @@ "load-grunt-config": "0.19.2", "makelogs": "^4.3.0", "mocha": "3.3.0", - "mock-fs": "^4.4.2", "murmurhash3js": "3.0.1", "mutation-observer": "^1.0.3", "nock": "8.0.0", @@ -400,7 +399,7 @@ "zlib": "^1.0.5" }, "engines": { - "node": "8.14.0", + "node": "10.14.1", "yarn": "^1.10.1" } } diff --git a/packages/kbn-babel-code-parser/package.json b/packages/kbn-babel-code-parser/package.json index 5ef9c94194797..7a9374e7216c9 100755 --- a/packages/kbn-babel-code-parser/package.json +++ b/packages/kbn-babel-code-parser/package.json @@ -10,8 +10,8 @@ "url": "https://github.com/elastic/kibana/tree/master/packages/kbn-babel-code-parser" }, "scripts": { - "build": "babel src --out-dir target --quiet", - "kbn:bootstrap": "yarn build", + "build": "babel src --out-dir target", + "kbn:bootstrap": "yarn build --quiet", "kbn:watch": "yarn build --watch" }, "devDependencies": { diff --git a/packages/kbn-config-schema/package.json b/packages/kbn-config-schema/package.json index 4d8a017716ac4..7b664a6e4a76b 100644 --- a/packages/kbn-config-schema/package.json +++ b/packages/kbn-config-schema/package.json @@ -13,7 +13,7 @@ "typescript": "^3.0.3" }, "peerDependencies": { - "joi": "10.4.1", + "joi": "^13.5.2", "moment": "^2.20.1", "type-detect": "^4.0.8" } diff --git a/packages/kbn-dev-utils/package.json b/packages/kbn-dev-utils/package.json index deb3c120df373..3775cc06d3b11 100644 --- a/packages/kbn-dev-utils/package.json +++ b/packages/kbn-dev-utils/package.json @@ -12,7 +12,7 @@ }, "dependencies": { "chalk": "^2.4.1", - "execa": "^0.10.0", + "execa": "^1.0.0", "moment": "^2.20.1", "rxjs": "^6.2.1", "tree-kill": "^1.2.0", diff --git a/packages/kbn-es/package.json b/packages/kbn-es/package.json index 8a59bff9cea58..dbef8e001fc03 100644 --- a/packages/kbn-es/package.json +++ b/packages/kbn-es/package.json @@ -9,16 +9,14 @@ "chalk": "^2.4.1", "dedent": "^0.7.0", "del": "^3.0.0", - "execa": "^0.10.0", + "execa": "^1.0.0", "getopts": "^2.0.6", "glob": "^7.1.2", "mkdirp": "^0.5.1", - "mock-fs": "^4.5.0", "node-fetch": "^2.0.0", "simple-git": "^1.91.0", - "tar-fs": "^1.16.0", + "tar-fs": "^1.16.3", "tree-kill": "^1.1.0", - "yauzl": "^2.10.0", - "zlib": "^1.0.5" + "yauzl": "^2.10.0" } } diff --git a/packages/kbn-es/src/utils/decompress.test.js b/packages/kbn-es/src/utils/decompress.test.js index 870fa815db34c..ff36e95212576 100644 --- a/packages/kbn-es/src/utils/decompress.test.js +++ b/packages/kbn-es/src/utils/decompress.test.js @@ -18,30 +18,40 @@ */ const { decompress } = require('./decompress'); -const mockFs = require('mock-fs'); const fs = require('fs'); const path = require('path'); +const mkdirp = require('mkdirp'); +const del = require('del'); +const os = require('os'); + +const fixturesFolder = path.resolve(__dirname, '__fixtures__'); +const randomDir = Math.random().toString(36); +const tmpFolder = path.resolve(os.tmpdir(), randomDir); +const dataFolder = path.resolve(tmpFolder, 'data'); +const esFolder = path.resolve(tmpFolder, '.es'); + +const zipSnapshot = path.resolve(dataFolder, 'snapshot.zip'); +const tarGzSnapshot = path.resolve(dataFolder, 'snapshot.tar.gz'); beforeEach(() => { - mockFs({ - '/data': { - 'snapshot.zip': fs.readFileSync(path.resolve(__dirname, '__fixtures__/snapshot.zip')), - 'snapshot.tar.gz': fs.readFileSync(path.resolve(__dirname, '__fixtures__/snapshot.tar.gz')), - }, - '/.es': {}, - }); + mkdirp.sync(tmpFolder); + mkdirp.sync(dataFolder); + mkdirp.sync(esFolder); + + fs.copyFileSync(path.resolve(fixturesFolder, 'snapshot.zip'), zipSnapshot); + fs.copyFileSync(path.resolve(fixturesFolder, 'snapshot.tar.gz'), tarGzSnapshot); }); afterEach(() => { - mockFs.restore(); + del.sync(tmpFolder, { force: true }); }); test('zip strips root directory', async () => { - await decompress('/data/snapshot.zip', '/.es/foo'); - expect(fs.readdirSync('/.es/foo/bin')).toContain('elasticsearch.bat'); + await decompress(zipSnapshot, path.resolve(esFolder, 'foo')); + expect(fs.readdirSync(path.resolve(esFolder, 'foo/bin'))).toContain('elasticsearch.bat'); }); test('tar strips root directory', async () => { - await decompress('/data/snapshot.tar.gz', '/.es/foo'); - expect(fs.readdirSync('/.es/foo/bin')).toContain('elasticsearch'); + await decompress(tarGzSnapshot, path.resolve(esFolder, 'foo')); + expect(fs.readdirSync(path.resolve(esFolder, 'foo/bin'))).toContain('elasticsearch'); }); diff --git a/packages/kbn-es/src/utils/extract_config_files.test.js b/packages/kbn-es/src/utils/extract_config_files.test.js index 3bf461e11c861..0c417536878db 100644 --- a/packages/kbn-es/src/utils/extract_config_files.test.js +++ b/packages/kbn-es/src/utils/extract_config_files.test.js @@ -17,21 +17,21 @@ * under the License. */ +jest.mock('fs', () => ({ + readFileSync: jest.fn(), + existsSync: jest.fn().mockImplementation(() => true), + writeFileSync: jest.fn(), +})); + const { extractConfigFiles } = require('./extract_config_files'); -const mockFs = require('mock-fs'); const fs = require('fs'); -beforeEach(() => { - mockFs({ - '/data': { - 'foo.yml': '', - }, - '/es': {}, - }); +afterEach(() => { + jest.clearAllMocks(); }); -afterEach(() => { - mockFs.restore(); +afterAll(() => { + jest.restoreAllMocks(); }); test('returns config with local paths', () => { @@ -43,8 +43,8 @@ test('returns config with local paths', () => { test('copies file', () => { extractConfigFiles(['path=/data/foo.yml'], '/es'); - expect(fs.existsSync('/es/config/foo.yml')).toBe(true); - expect(fs.existsSync('/data/foo.yml')).toBe(true); + expect(fs.readFileSync.mock.calls[0][0]).toEqual('/data/foo.yml'); + expect(fs.writeFileSync.mock.calls[0][0]).toEqual('/es/config/foo.yml'); }); test('ignores non-paths', () => { diff --git a/packages/kbn-es/src/utils/find_most_recently_changed.test.js b/packages/kbn-es/src/utils/find_most_recently_changed.test.js index 6ceb9a9f08c4e..ed90576990c72 100644 --- a/packages/kbn-es/src/utils/find_most_recently_changed.test.js +++ b/packages/kbn-es/src/utils/find_most_recently_changed.test.js @@ -17,33 +17,38 @@ * under the License. */ -const mockFs = require('mock-fs'); -const { findMostRecentlyChanged } = require('./find_most_recently_changed'); - -beforeEach(() => { - mockFs({ - '/data': { - 'oldest.yml': mockFs.file({ - content: 'foo', +jest.mock('fs', () => ({ + statSync: jest.fn().mockImplementation(path => { + if (path.includes('oldest')) { + return { ctime: new Date(2018, 2, 1), - }), - 'newest.yml': mockFs.file({ - content: 'bar', + }; + } + + if (path.includes('newest')) { + return { ctime: new Date(2018, 2, 3), - }), - 'middle.yml': mockFs.file({ - content: 'baz', + }; + } + + if (path.includes('middle')) { + return { ctime: new Date(2018, 2, 2), - }), - }, - }); -}); + }; + } + }), + readdirSync: jest.fn().mockImplementation(() => { + return ['oldest.yml', 'newest.yml', 'middle.yml']; + }), +})); -afterEach(() => { - mockFs.restore(); -}); +const { findMostRecentlyChanged } = require('./find_most_recently_changed'); test('returns newest file', () => { const file = findMostRecentlyChanged('/data/*.yml'); expect(file).toEqual('/data/newest.yml'); }); + +afterAll(() => { + jest.restoreAllMocks(); +}); diff --git a/packages/kbn-i18n/src/__snapshots__/loader.test.ts.snap b/packages/kbn-i18n/src/__snapshots__/loader.test.ts.snap index 37209d29367a2..05b3fd17a6740 100644 --- a/packages/kbn-i18n/src/__snapshots__/loader.test.ts.snap +++ b/packages/kbn-i18n/src/__snapshots__/loader.test.ts.snap @@ -2,4 +2,4 @@ exports[`I18n loader registerTranslationFile should throw error if path to translation file is not an absolute 1`] = `"Paths to translation files must be absolute. Got relative path: \\"./en.json\\""`; -exports[`I18n loader registerTranslationFile should throw error if path to translation file is not specified 1`] = `"Path must be a string. Received undefined"`; +exports[`I18n loader registerTranslationFile should throw error if path to translation file is not specified 1`] = `"The \\"path\\" argument must be of type string. Received type undefined"`; diff --git a/packages/kbn-plugin-generator/package.json b/packages/kbn-plugin-generator/package.json index f846747203ca9..3cb2fbda69ef3 100644 --- a/packages/kbn-plugin-generator/package.json +++ b/packages/kbn-plugin-generator/package.json @@ -6,7 +6,7 @@ "dependencies": { "chalk": "^2.4.1", "dedent": "^0.7.0", - "execa": "^0.9.0", + "execa": "^1.0.0", "getopts": "^2.0.0", "lodash.camelcase": "^4.3.0", "lodash.kebabcase": "^4.1.1", diff --git a/packages/kbn-plugin-helpers/package.json b/packages/kbn-plugin-helpers/package.json index d73368338292a..ec445a4524884 100644 --- a/packages/kbn-plugin-helpers/package.json +++ b/packages/kbn-plugin-helpers/package.json @@ -13,7 +13,7 @@ "argv-split": "^2.0.1", "commander": "^2.9.0", "del": "^2.2.2", - "execa": "^0.10.0", + "execa": "^1.0.0", "gulp-rename": "1.2.2", "gulp-zip": "^4.1.0", "inquirer": "^1.2.2", diff --git a/packages/kbn-plugin-helpers/tasks/build/integration_tests/create_build.test.js b/packages/kbn-plugin-helpers/tasks/build/integration_tests/create_build.test.js index 659cb42e82380..12aba777361a8 100644 --- a/packages/kbn-plugin-helpers/tasks/build/integration_tests/create_build.test.js +++ b/packages/kbn-plugin-helpers/tasks/build/integration_tests/create_build.test.js @@ -18,7 +18,7 @@ */ const { resolve } = require('path'); -const { readdirSync, existsSync, unlink } = require('fs'); +const { readdirSync, existsSync, unlinkSync } = require('fs'); const del = require('del'); const createBuild = require('../create_build'); @@ -96,7 +96,7 @@ describe('creating the build', () => { afterEach(() => { PLUGIN.skipInstallDependencies = false; PLUGIN.styleSheetToCompile = undefined; - unlink(cssPath); + unlinkSync(cssPath); }); it('produces CSS', async () => { diff --git a/packages/kbn-pm/dist/index.js b/packages/kbn-pm/dist/index.js index 8d62848f49d06..5db0bc9b63068 100644 --- a/packages/kbn-pm/dist/index.js +++ b/packages/kbn-pm/dist/index.js @@ -82,7 +82,7 @@ module.exports = /******/ /******/ /******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 119); +/******/ return __webpack_require__(__webpack_require__.s = 161); /******/ }) /************************************************************************/ /******/ ([ @@ -125,9 +125,12 @@ and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ -var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; function __extends(d, b) { extendStatics(d, b); @@ -135,12 +138,15 @@ function __extends(d, b) { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } -var __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; +var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; } - return t; + return __assign.apply(this, arguments); } function __rest(s, e) { @@ -184,8 +190,8 @@ function __generator(thisArg, body) { function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { - if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [0, t.value]; + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; @@ -253,7 +259,7 @@ function __asyncGenerator(thisArg, _arguments, generator) { return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } @@ -262,13 +268,15 @@ function __asyncGenerator(thisArg, _arguments, generator) { function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator]; - return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { @@ -296,12 +304,12 @@ function __importDefault(mod) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Subscriber; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); -/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(29); -/* harmony import */ var _Observer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(55); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5); -/* harmony import */ var _internal_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(38); -/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(18); -/* harmony import */ var _util_hostReportError__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(37); +/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(33); +/* harmony import */ var _Observer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(60); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6); +/* harmony import */ var _internal_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(42); +/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(19); +/* harmony import */ var _util_hostReportError__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(41); /** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */ @@ -552,10 +560,10 @@ function isTrustedSubscriber(obj) { var Subscriber = __webpack_require__(1); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/symbol/rxSubscriber.js -var rxSubscriber = __webpack_require__(38); +var rxSubscriber = __webpack_require__(42); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/Observer.js -var Observer = __webpack_require__(55); +var Observer = __webpack_require__(60); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/toSubscriber.js /** PURE_IMPORTS_START _Subscriber,_symbol_rxSubscriber,_Observer PURE_IMPORTS_END */ @@ -579,13 +587,13 @@ function toSubscriber(nextOrObserver, error, complete) { //# sourceMappingURL=toSubscriber.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/symbol/observable.js -var observable = __webpack_require__(24); +var observable = __webpack_require__(27); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/pipe.js -var pipe = __webpack_require__(39); +var pipe = __webpack_require__(45); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/config.js -var config = __webpack_require__(18); +var config = __webpack_require__(19); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/Observable.js /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Observable_Observable; }); @@ -707,7 +715,7 @@ function getPromiseCtor(promiseCtor) { "use strict"; -// EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/node_modules/tslib/tslib.es6.js +// EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/tslib/tslib.es6.js var tslib_es6 = __webpack_require__(0); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/Subscriber.js @@ -744,7 +752,7 @@ var InnerSubscriber_InnerSubscriber = /*@__PURE__*/ (function (_super) { //# sourceMappingURL=InnerSubscriber.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/subscribeTo.js -var subscribeTo = __webpack_require__(76); +var subscribeTo = __webpack_require__(92); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/subscribeToResult.js /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return subscribeToResult; }); @@ -791,16 +799,22 @@ var OuterSubscriber = /*@__PURE__*/ (function (_super) { /***/ }), /* 5 */ +/***/ (function(module, exports) { + +module.exports = require("path"); + +/***/ }), +/* 6 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Subscription; }); /* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(11); -/* harmony import */ var _util_isObject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(73); -/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(29); -/* harmony import */ var _util_tryCatch__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(14); -/* harmony import */ var _util_errorObject__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(6); -/* harmony import */ var _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(40); +/* harmony import */ var _util_isObject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(89); +/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(33); +/* harmony import */ var _util_tryCatch__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(16); +/* harmony import */ var _util_errorObject__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7); +/* harmony import */ var _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(46); /** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_tryCatch,_util_errorObject,_util_UnsubscriptionError PURE_IMPORTS_END */ @@ -936,7 +950,7 @@ function flattenUnsubscriptionErrors(errors) { /***/ }), -/* 6 */ +/* 7 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -946,12 +960,6 @@ var errorObject = { e: {} }; //# sourceMappingURL=errorObject.js.map -/***/ }), -/* 7 */ -/***/ (function(module, exports) { - -module.exports = require("path"); - /***/ }), /* 8 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { @@ -963,10 +971,10 @@ module.exports = require("path"); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); /* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2); /* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5); -/* harmony import */ var _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(25); -/* harmony import */ var _SubjectSubscription__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(74); -/* harmony import */ var _internal_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(38); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6); +/* harmony import */ var _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(28); +/* harmony import */ var _SubjectSubscription__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(90); +/* harmony import */ var _internal_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(42); /** PURE_IMPORTS_START tslib,_Observable,_Subscriber,_Subscription,_util_ObjectUnsubscribedError,_SubjectSubscription,_internal_symbol_rxSubscriber PURE_IMPORTS_END */ @@ -1154,8 +1162,8 @@ function emptyScheduled(scheduler) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return async; }); -/* harmony import */ var _AsyncAction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(34); -/* harmony import */ var _AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32); +/* harmony import */ var _AsyncAction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(37); +/* harmony import */ var _AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(35); /** PURE_IMPORTS_START _AsyncAction,_AsyncScheduler PURE_IMPORTS_END */ @@ -1189,6 +1197,18 @@ function isScheduler(value) { /***/ }), /* 13 */ +/***/ (function(module, exports) { + +module.exports = require("fs"); + +/***/ }), +/* 14 */ +/***/ (function(module, exports) { + +module.exports = require("util"); + +/***/ }), +/* 15 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -1244,12 +1264,12 @@ var MapSubscriber = /*@__PURE__*/ (function (_super) { /***/ }), -/* 14 */ +/* 16 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return tryCatch; }); -/* harmony import */ var _errorObject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6); +/* harmony import */ var _errorObject__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7); /** PURE_IMPORTS_START _errorObject PURE_IMPORTS_END */ var tryCatchTarget; @@ -1270,7 +1290,7 @@ function tryCatch(fn) { /***/ }), -/* 15 */ +/* 17 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -1279,13 +1299,13 @@ function tryCatch(fn) { var Observable = __webpack_require__(2); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/isPromise.js -var isPromise = __webpack_require__(79); +var isPromise = __webpack_require__(95); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/isArrayLike.js -var isArrayLike = __webpack_require__(78); +var isArrayLike = __webpack_require__(94); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/symbol/observable.js -var symbol_observable = __webpack_require__(24); +var symbol_observable = __webpack_require__(27); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/isInteropObservable.js /** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */ @@ -1296,7 +1316,7 @@ function isInteropObservable(input) { //# sourceMappingURL=isInteropObservable.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/symbol/iterator.js -var symbol_iterator = __webpack_require__(23); +var symbol_iterator = __webpack_require__(25); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/isIterable.js /** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */ @@ -1307,13 +1327,13 @@ function isIterable(input) { //# sourceMappingURL=isIterable.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/fromArray.js -var fromArray = __webpack_require__(17); +var fromArray = __webpack_require__(18); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/Subscription.js -var Subscription = __webpack_require__(5); +var Subscription = __webpack_require__(6); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/subscribeToPromise.js -var subscribeToPromise = __webpack_require__(80); +var subscribeToPromise = __webpack_require__(96); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/fromPromise.js /** PURE_IMPORTS_START _Observable,_Subscription,_util_subscribeToPromise PURE_IMPORTS_END */ @@ -1344,7 +1364,7 @@ function fromPromise(input, scheduler) { //# sourceMappingURL=fromPromise.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/subscribeToIterable.js -var subscribeToIterable = __webpack_require__(81); +var subscribeToIterable = __webpack_require__(97); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/fromIterable.js /** PURE_IMPORTS_START _Observable,_Subscription,_symbol_iterator,_util_subscribeToIterable PURE_IMPORTS_END */ @@ -1401,7 +1421,7 @@ function fromIterable(input, scheduler) { //# sourceMappingURL=fromIterable.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/subscribeToObservable.js -var subscribeToObservable = __webpack_require__(77); +var subscribeToObservable = __webpack_require__(93); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/fromObservable.js /** PURE_IMPORTS_START _Observable,_Subscription,_symbol_observable,_util_subscribeToObservable PURE_IMPORTS_END */ @@ -1431,7 +1451,7 @@ function fromObservable(input, scheduler) { //# sourceMappingURL=fromObservable.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/subscribeTo.js -var subscribeTo = __webpack_require__(76); +var subscribeTo = __webpack_require__(92); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/from.js /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return from; }); @@ -1473,20 +1493,14 @@ function from(input, scheduler) { /***/ }), -/* 16 */ -/***/ (function(module, exports) { - -module.exports = require("fs"); - -/***/ }), -/* 17 */ +/* 18 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return fromArray; }); /* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5); -/* harmony import */ var _util_subscribeToArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(75); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6); +/* harmony import */ var _util_subscribeToArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(91); /** PURE_IMPORTS_START _Observable,_Subscription,_util_subscribeToArray PURE_IMPORTS_END */ @@ -1517,7 +1531,7 @@ function fromArray(input, scheduler) { /***/ }), -/* 18 */ +/* 19 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -1544,13 +1558,47 @@ var config = { /***/ }), -/* 19 */ -/***/ (function(module, exports) { +/* 20 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var isObject = __webpack_require__(74); + +module.exports = function extend(o/*, objects*/) { + if (!isObject(o)) { o = {}; } + + var len = arguments.length; + for (var i = 1; i < len; i++) { + var obj = arguments[i]; + + if (isObject(obj)) { + assign(o, obj); + } + } + return o; +}; + +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } +} + +/** + * Returns true if the given `key` is an own property of `obj`. + */ + +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} -module.exports = require("util"); /***/ }), -/* 20 */ +/* 21 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -1561,7 +1609,34 @@ function noop() { } /***/ }), -/* 21 */ +/* 22 */ +/***/ (function(module, exports) { + +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +module.exports = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) +} + +function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) +} + + +/***/ }), +/* 23 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -1574,14 +1649,14 @@ function identity(x) { /***/ }), -/* 22 */ +/* 24 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Notification; }); /* harmony import */ var _observable_empty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9); -/* harmony import */ var _observable_of__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(47); -/* harmony import */ var _observable_throwError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(48); +/* harmony import */ var _observable_of__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(52); +/* harmony import */ var _observable_throwError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(53); /** PURE_IMPORTS_START _observable_empty,_observable_of,_observable_throwError PURE_IMPORTS_END */ @@ -1655,7 +1730,7 @@ var Notification = /*@__PURE__*/ (function () { /***/ }), -/* 23 */ +/* 25 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -1674,225 +1749,17 @@ var $$iterator = iterator; //# sourceMappingURL=iterator.js.map -/***/ }), -/* 24 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return observable; }); -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var observable = typeof Symbol === 'function' && Symbol.observable || '@@observable'; -//# sourceMappingURL=observable.js.map - - -/***/ }), -/* 25 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ObjectUnsubscribedError; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); -/** PURE_IMPORTS_START tslib PURE_IMPORTS_END */ - -var ObjectUnsubscribedError = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](ObjectUnsubscribedError, _super); - function ObjectUnsubscribedError() { - var _this = _super.call(this, 'object unsubscribed') || this; - _this.name = 'ObjectUnsubscribedError'; - Object.setPrototypeOf(_this, ObjectUnsubscribedError.prototype); - return _this; - } - return ObjectUnsubscribedError; -}(Error)); - -//# sourceMappingURL=ObjectUnsubscribedError.js.map - - /***/ }), /* 26 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return concat; }); -/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(12); -/* harmony import */ var _of__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(47); -/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(15); -/* harmony import */ var _operators_concatAll__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(68); -/** PURE_IMPORTS_START _util_isScheduler,_of,_from,_operators_concatAll PURE_IMPORTS_END */ - - - - -function concat() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i] = arguments[_i]; - } - if (observables.length === 1 || (observables.length === 2 && Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_0__[/* isScheduler */ "a"])(observables[1]))) { - return Object(_from__WEBPACK_IMPORTED_MODULE_2__[/* from */ "a"])(observables[0]); - } - return Object(_operators_concatAll__WEBPACK_IMPORTED_MODULE_3__[/* concatAll */ "a"])()(_of__WEBPACK_IMPORTED_MODULE_1__[/* of */ "a"].apply(void 0, observables)); -} -//# sourceMappingURL=concat.js.map - - -/***/ }), -/* 27 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return mergeMap; }); -/* unused harmony export MergeMapOperator */ -/* unused harmony export MergeMapSubscriber */ -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); -/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); -/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4); -/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(13); -/* harmony import */ var _observable_from__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(15); -/** PURE_IMPORTS_START tslib,_util_subscribeToResult,_OuterSubscriber,_map,_observable_from PURE_IMPORTS_END */ - - - - - -function mergeMap(project, resultSelector, concurrent) { - if (concurrent === void 0) { - concurrent = Number.POSITIVE_INFINITY; - } - if (typeof resultSelector === 'function') { - return function (source) { return source.pipe(mergeMap(function (a, i) { return Object(_observable_from__WEBPACK_IMPORTED_MODULE_4__[/* from */ "a"])(project(a, i)).pipe(Object(_map__WEBPACK_IMPORTED_MODULE_3__[/* map */ "a"])(function (b, ii) { return resultSelector(a, b, i, ii); })); }, concurrent)); }; - } - else if (typeof resultSelector === 'number') { - concurrent = resultSelector; - } - return function (source) { return source.lift(new MergeMapOperator(project, concurrent)); }; -} -var MergeMapOperator = /*@__PURE__*/ (function () { - function MergeMapOperator(project, concurrent) { - if (concurrent === void 0) { - concurrent = Number.POSITIVE_INFINITY; - } - this.project = project; - this.concurrent = concurrent; - } - MergeMapOperator.prototype.call = function (observer, source) { - return source.subscribe(new MergeMapSubscriber(observer, this.project, this.concurrent)); - }; - return MergeMapOperator; -}()); - -var MergeMapSubscriber = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](MergeMapSubscriber, _super); - function MergeMapSubscriber(destination, project, concurrent) { - if (concurrent === void 0) { - concurrent = Number.POSITIVE_INFINITY; - } - var _this = _super.call(this, destination) || this; - _this.project = project; - _this.concurrent = concurrent; - _this.hasCompleted = false; - _this.buffer = []; - _this.active = 0; - _this.index = 0; - return _this; - } - MergeMapSubscriber.prototype._next = function (value) { - if (this.active < this.concurrent) { - this._tryNext(value); - } - else { - this.buffer.push(value); - } - }; - MergeMapSubscriber.prototype._tryNext = function (value) { - var result; - var index = this.index++; - try { - result = this.project(value, index); - } - catch (err) { - this.destination.error(err); - return; - } - this.active++; - this._innerSub(result, value, index); - }; - MergeMapSubscriber.prototype._innerSub = function (ish, value, index) { - this.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__[/* subscribeToResult */ "a"])(this, ish, value, index)); - }; - MergeMapSubscriber.prototype._complete = function () { - this.hasCompleted = true; - if (this.active === 0 && this.buffer.length === 0) { - this.destination.complete(); - } - }; - MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.destination.next(innerValue); - }; - MergeMapSubscriber.prototype.notifyComplete = function (innerSub) { - var buffer = this.buffer; - this.remove(innerSub); - this.active--; - if (buffer.length > 0) { - this._next(buffer.shift()); - } - else if (this.active === 0 && this.hasCompleted) { - this.destination.complete(); - } - }; - return MergeMapSubscriber; -}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__[/* OuterSubscriber */ "a"])); - -//# sourceMappingURL=mergeMap.js.map - - -/***/ }), -/* 28 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ArgumentOutOfRangeError; }); -/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); -/** PURE_IMPORTS_START tslib PURE_IMPORTS_END */ - -var ArgumentOutOfRangeError = /*@__PURE__*/ (function (_super) { - tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](ArgumentOutOfRangeError, _super); - function ArgumentOutOfRangeError() { - var _this = _super.call(this, 'argument out of range') || this; - _this.name = 'ArgumentOutOfRangeError'; - Object.setPrototypeOf(_this, ArgumentOutOfRangeError.prototype); - return _this; - } - return ArgumentOutOfRangeError; -}(Error)); - -//# sourceMappingURL=ArgumentOutOfRangeError.js.map - - -/***/ }), -/* 29 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return isFunction; }); -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function isFunction(x) { - return typeof x === 'function'; -} -//# sourceMappingURL=isFunction.js.map - - -/***/ }), -/* 30 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const escapeStringRegexp = __webpack_require__(82); -const ansiStyles = __webpack_require__(121); -const stdoutColor = __webpack_require__(124).stdout; +const escapeStringRegexp = __webpack_require__(163); +const ansiStyles = __webpack_require__(164); +const stdoutColor = __webpack_require__(168).stdout; -const template = __webpack_require__(125); +const template = __webpack_require__(170); const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); @@ -2117,10 +1984,237 @@ module.exports.supportsColor = stdoutColor; module.exports.default = module.exports; // For TypeScript +/***/ }), +/* 27 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return observable; }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var observable = typeof Symbol === 'function' && Symbol.observable || '@@observable'; +//# sourceMappingURL=observable.js.map + + +/***/ }), +/* 28 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ObjectUnsubscribedError; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); +/** PURE_IMPORTS_START tslib PURE_IMPORTS_END */ + +var ObjectUnsubscribedError = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](ObjectUnsubscribedError, _super); + function ObjectUnsubscribedError() { + var _this = _super.call(this, 'object unsubscribed') || this; + _this.name = 'ObjectUnsubscribedError'; + Object.setPrototypeOf(_this, ObjectUnsubscribedError.prototype); + return _this; + } + return ObjectUnsubscribedError; +}(Error)); + +//# sourceMappingURL=ObjectUnsubscribedError.js.map + + +/***/ }), +/* 29 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return concat; }); +/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(12); +/* harmony import */ var _of__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(52); +/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(17); +/* harmony import */ var _operators_concatAll__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(84); +/** PURE_IMPORTS_START _util_isScheduler,_of,_from,_operators_concatAll PURE_IMPORTS_END */ + + + + +function concat() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i] = arguments[_i]; + } + if (observables.length === 1 || (observables.length === 2 && Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_0__[/* isScheduler */ "a"])(observables[1]))) { + return Object(_from__WEBPACK_IMPORTED_MODULE_2__[/* from */ "a"])(observables[0]); + } + return Object(_operators_concatAll__WEBPACK_IMPORTED_MODULE_3__[/* concatAll */ "a"])()(_of__WEBPACK_IMPORTED_MODULE_1__[/* of */ "a"].apply(void 0, observables)); +} +//# sourceMappingURL=concat.js.map + + +/***/ }), +/* 30 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * isobject + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +module.exports = function isObject(val) { + return val != null && typeof val === 'object' && Array.isArray(val) === false; +}; + + /***/ }), /* 31 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return mergeMap; }); +/* unused harmony export MergeMapOperator */ +/* unused harmony export MergeMapSubscriber */ +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); +/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); +/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4); +/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(15); +/* harmony import */ var _observable_from__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(17); +/** PURE_IMPORTS_START tslib,_util_subscribeToResult,_OuterSubscriber,_map,_observable_from PURE_IMPORTS_END */ + + + + + +function mergeMap(project, resultSelector, concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + if (typeof resultSelector === 'function') { + return function (source) { return source.pipe(mergeMap(function (a, i) { return Object(_observable_from__WEBPACK_IMPORTED_MODULE_4__[/* from */ "a"])(project(a, i)).pipe(Object(_map__WEBPACK_IMPORTED_MODULE_3__[/* map */ "a"])(function (b, ii) { return resultSelector(a, b, i, ii); })); }, concurrent)); }; + } + else if (typeof resultSelector === 'number') { + concurrent = resultSelector; + } + return function (source) { return source.lift(new MergeMapOperator(project, concurrent)); }; +} +var MergeMapOperator = /*@__PURE__*/ (function () { + function MergeMapOperator(project, concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + this.project = project; + this.concurrent = concurrent; + } + MergeMapOperator.prototype.call = function (observer, source) { + return source.subscribe(new MergeMapSubscriber(observer, this.project, this.concurrent)); + }; + return MergeMapOperator; +}()); + +var MergeMapSubscriber = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](MergeMapSubscriber, _super); + function MergeMapSubscriber(destination, project, concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + var _this = _super.call(this, destination) || this; + _this.project = project; + _this.concurrent = concurrent; + _this.hasCompleted = false; + _this.buffer = []; + _this.active = 0; + _this.index = 0; + return _this; + } + MergeMapSubscriber.prototype._next = function (value) { + if (this.active < this.concurrent) { + this._tryNext(value); + } + else { + this.buffer.push(value); + } + }; + MergeMapSubscriber.prototype._tryNext = function (value) { + var result; + var index = this.index++; + try { + result = this.project(value, index); + } + catch (err) { + this.destination.error(err); + return; + } + this.active++; + this._innerSub(result, value, index); + }; + MergeMapSubscriber.prototype._innerSub = function (ish, value, index) { + this.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__[/* subscribeToResult */ "a"])(this, ish, value, index)); + }; + MergeMapSubscriber.prototype._complete = function () { + this.hasCompleted = true; + if (this.active === 0 && this.buffer.length === 0) { + this.destination.complete(); + } + }; + MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.destination.next(innerValue); + }; + MergeMapSubscriber.prototype.notifyComplete = function (innerSub) { + var buffer = this.buffer; + this.remove(innerSub); + this.active--; + if (buffer.length > 0) { + this._next(buffer.shift()); + } + else if (this.active === 0 && this.hasCompleted) { + this.destination.complete(); + } + }; + return MergeMapSubscriber; +}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__[/* OuterSubscriber */ "a"])); + +//# sourceMappingURL=mergeMap.js.map + + +/***/ }), +/* 32 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ArgumentOutOfRangeError; }); +/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); +/** PURE_IMPORTS_START tslib PURE_IMPORTS_END */ + +var ArgumentOutOfRangeError = /*@__PURE__*/ (function (_super) { + tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](ArgumentOutOfRangeError, _super); + function ArgumentOutOfRangeError() { + var _this = _super.call(this, 'argument out of range') || this; + _this.name = 'ArgumentOutOfRangeError'; + Object.setPrototypeOf(_this, ArgumentOutOfRangeError.prototype); + return _this; + } + return ArgumentOutOfRangeError; +}(Error)); + +//# sourceMappingURL=ArgumentOutOfRangeError.js.map + + +/***/ }), +/* 33 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return isFunction; }); +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +function isFunction(x) { + return typeof x === 'function'; +} +//# sourceMappingURL=isFunction.js.map + + +/***/ }), +/* 34 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return EmptyError; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); @@ -2141,13 +2235,13 @@ var EmptyError = /*@__PURE__*/ (function (_super) { /***/ }), -/* 32 */ +/* 35 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AsyncScheduler; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); -/* harmony import */ var _Scheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(58); +/* harmony import */ var _Scheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(69); /** PURE_IMPORTS_START tslib,_Scheduler PURE_IMPORTS_END */ @@ -2209,14 +2303,14 @@ var AsyncScheduler = /*@__PURE__*/ (function (_super) { /***/ }), -/* 33 */ +/* 36 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AsyncSubject; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); /* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6); /** PURE_IMPORTS_START tslib,_Subject,_Subscription PURE_IMPORTS_END */ @@ -2267,16 +2361,16 @@ var AsyncSubject = /*@__PURE__*/ (function (_super) { /***/ }), -/* 34 */ +/* 37 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; -// EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/node_modules/tslib/tslib.es6.js +// EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/tslib/tslib.es6.js var tslib_es6 = __webpack_require__(0); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/Subscription.js -var Subscription = __webpack_require__(5); +var Subscription = __webpack_require__(6); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/scheduler/Action.js /** PURE_IMPORTS_START tslib,_Subscription PURE_IMPORTS_END */ @@ -2397,7 +2491,7 @@ var AsyncAction_AsyncAction = /*@__PURE__*/ (function (_super) { /***/ }), -/* 35 */ +/* 38 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -2412,7 +2506,13 @@ function isNumeric(val) { /***/ }), -/* 36 */ +/* 39 */ +/***/ (function(module, exports) { + +module.exports = require("stream"); + +/***/ }), +/* 40 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -2452,7 +2552,7 @@ const log = exports.log = { }; /***/ }), -/* 37 */ +/* 41 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -2465,7 +2565,7 @@ function hostReportError(err) { /***/ }), -/* 38 */ +/* 42 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -2480,13 +2580,206 @@ var $$rxSubscriber = rxSubscriber; /***/ }), -/* 39 */ +/* 43 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var define = __webpack_require__(307); +var extend = __webpack_require__(20); +var not = __webpack_require__(64); +var MAX_LENGTH = 1024 * 64; + +/** + * Session cache + */ + +var cache = {}; + +/** + * Create a regular expression from the given `pattern` string. + * + * @param {String|RegExp} `pattern` Pattern can be a string or regular expression. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ + +module.exports = function(patterns, options) { + if (!Array.isArray(patterns)) { + return makeRe(patterns, options); + } + return makeRe(patterns.join('|'), options); +}; + +/** + * Create a regular expression from the given `pattern` string. + * + * @param {String|RegExp} `pattern` Pattern can be a string or regular expression. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ + +function makeRe(pattern, options) { + if (pattern instanceof RegExp) { + return pattern; + } + + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } + + if (pattern.length > MAX_LENGTH) { + throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); + } + + var key = pattern; + // do this before shallow cloning options, it's a lot faster + if (!options || (options && options.cache !== false)) { + key = createKey(pattern, options); + + if (cache.hasOwnProperty(key)) { + return cache[key]; + } + } + + var opts = extend({}, options); + if (opts.contains === true) { + if (opts.negate === true) { + opts.strictNegate = false; + } else { + opts.strict = false; + } + } + + if (opts.strict === false) { + opts.strictOpen = false; + opts.strictClose = false; + } + + var open = opts.strictOpen !== false ? '^' : ''; + var close = opts.strictClose !== false ? '$' : ''; + var flags = opts.flags || ''; + var regex; + + if (opts.nocase === true && !/i/.test(flags)) { + flags += 'i'; + } + + try { + if (opts.negate || typeof opts.strictNegate === 'boolean') { + pattern = not.create(pattern, opts); + } + var str = open + '(?:' + pattern + ')' + close; + regex = new RegExp(str, flags); + } catch (err) { + if (opts.strictErrors === true) { + err.key = key; + err.pattern = pattern; + err.originalOptions = options; + err.createdOptions = opts; + throw err; + } + + try { + regex = new RegExp('^' + pattern.replace(/(\W)/g, '\\$1') + '$'); + } catch (err) { + regex = /.^/; //<= match nothing + } + } + + if (opts.cache !== false) { + cacheRegex(regex, key, pattern, opts); + } + return regex; +} + +/** + * Cache generated regex. This can result in dramatic speed improvements + * and simplify debugging by adding options and pattern to the regex. It can be + * disabled by passing setting `options.cache` to false. + */ + +function cacheRegex(regex, key, pattern, options) { + define(regex, 'cached', true); + define(regex, 'pattern', pattern); + define(regex, 'options', options); + define(regex, 'key', key); + cache[key] = regex; +} + +/** + * Create the key to use for memoization. The key is generated + * by iterating over the options and concatenating key-value pairs + * to the pattern string. + */ + +function createKey(pattern, options) { + if (!options) return pattern; + var key = pattern; + for (var prop in options) { + if (options.hasOwnProperty(prop)) { + key += ';' + prop + '=' + String(options[prop]); + } + } + return key; +} + +/** + * Expose `makeRe` + */ + +module.exports.makeRe = makeRe; + + +/***/ }), +/* 44 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * define-property + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isDescriptor = __webpack_require__(314); + +module.exports = function defineProperty(obj, prop, val) { + if (typeof obj !== 'object' && typeof obj !== 'function') { + throw new TypeError('expected an object or function.'); + } + + if (typeof prop !== 'string') { + throw new TypeError('expected `prop` to be a string.'); + } + + if (isDescriptor(val) && ('set' in val || 'get' in val)) { + return Object.defineProperty(obj, prop, val); + } + + return Object.defineProperty(obj, prop, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); +}; + + +/***/ }), +/* 45 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return pipe; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return pipeFromArray; }); -/* harmony import */ var _noop__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(20); +/* harmony import */ var _noop__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21); /** PURE_IMPORTS_START _noop PURE_IMPORTS_END */ function pipe() { @@ -2511,7 +2804,7 @@ function pipeFromArray(fns) { /***/ }), -/* 40 */ +/* 46 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -2536,13 +2829,7 @@ var UnsubscriptionError = /*@__PURE__*/ (function (_super) { /***/ }), -/* 41 */ -/***/ (function(module, exports) { - -module.exports = require("stream"); - -/***/ }), -/* 42 */ +/* 47 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -2591,21 +2878,21 @@ exports.buildProjectGraph = buildProjectGraph; exports.topologicallyBatchProjects = topologicallyBatchProjects; exports.includeTransitiveProjects = includeTransitiveProjects; -var _glob = __webpack_require__(43); +var _glob = __webpack_require__(48); var _glob2 = _interopRequireDefault(_glob); -var _path = __webpack_require__(7); +var _path = __webpack_require__(5); var _path2 = _interopRequireDefault(_path); -var _util = __webpack_require__(19); +var _util = __webpack_require__(14); -var _errors = __webpack_require__(88); +var _errors = __webpack_require__(101); -var _project = __webpack_require__(101); +var _project = __webpack_require__(121); -var _workspaces = __webpack_require__(112); +var _workspaces = __webpack_require__(130); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -2732,7 +3019,7 @@ function includeTransitiveProjects(subsetOfProjects, allProjects, { onlyProducti } /***/ }), -/* 43 */ +/* 48 */ /***/ (function(module, exports, __webpack_require__) { // Approach: @@ -2777,27 +3064,27 @@ function includeTransitiveProjects(subsetOfProjects, allProjects, { onlyProducti module.exports = glob -var fs = __webpack_require__(16) -var rp = __webpack_require__(96) -var minimatch = __webpack_require__(86) +var fs = __webpack_require__(13) +var rp = __webpack_require__(117) +var minimatch = __webpack_require__(99) var Minimatch = minimatch.Minimatch -var inherits = __webpack_require__(97) -var EE = __webpack_require__(61).EventEmitter -var path = __webpack_require__(7) -var assert = __webpack_require__(57) -var isAbsolute = __webpack_require__(87) -var globSync = __webpack_require__(141) -var common = __webpack_require__(98) +var inherits = __webpack_require__(118) +var EE = __webpack_require__(63).EventEmitter +var path = __webpack_require__(5) +var assert = __webpack_require__(62) +var isAbsolute = __webpack_require__(100) +var globSync = __webpack_require__(186) +var common = __webpack_require__(119) var alphasort = common.alphasort var alphasorti = common.alphasorti var setopts = common.setopts var ownProp = common.ownProp -var inflight = __webpack_require__(142) -var util = __webpack_require__(19) +var inflight = __webpack_require__(187) +var util = __webpack_require__(14) var childrenIgnored = common.childrenIgnored var isIgnored = common.isIgnored -var once = __webpack_require__(100) +var once = __webpack_require__(71) function glob (pattern, options, cb) { if (typeof options === 'function') cb = options, options = {} @@ -3528,98 +3815,129 @@ Glob.prototype._stat2 = function (f, abs, er, stat, cb) { /***/ }), -/* 44 */ +/* 49 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - - -const processFn = (fn, opts) => function () { - const P = opts.promiseModule; - const args = new Array(arguments.length); - - for (let i = 0; i < arguments.length; i++) { - args[i] = arguments[i]; - } - - return new P((resolve, reject) => { - if (opts.errorFirst) { - args.push(function (err, result) { - if (opts.multiArgs) { - const results = new Array(arguments.length - 1); +var isBuffer = __webpack_require__(22); +var toString = Object.prototype.toString; - for (let i = 1; i < arguments.length; i++) { - results[i - 1] = arguments[i]; - } +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ - if (err) { - results.unshift(err); - reject(results); - } else { - resolve(results); - } - } else if (err) { - reject(err); - } else { - resolve(result); - } - }); - } else { - args.push(function (result) { - if (opts.multiArgs) { - const results = new Array(arguments.length - 1); +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; + } - for (let i = 0; i < arguments.length; i++) { - results[i] = arguments[i]; - } + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; + } - resolve(results); - } else { - resolve(result); - } - }); - } + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } - fn.apply(this, args); - }); -}; + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } -module.exports = (obj, opts) => { - opts = Object.assign({ - exclude: [/.+(Sync|Stream)$/], - errorFirst: true, - promiseModule: Promise - }, opts); + // other objects + var type = toString.call(val); - const filter = key => { - const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key); - return opts.include ? opts.include.some(match) : !opts.exclude.some(match); - }; + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } - let ret; - if (typeof obj === 'function') { - ret = function () { - if (opts.excludeMain) { - return obj.apply(this, arguments); - } + // buffer + if (isBuffer(val)) { + return 'buffer'; + } - return processFn(obj, opts).apply(this, arguments); - }; - } else { - ret = Object.create(Object.getPrototypeOf(obj)); - } + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } - for (const key in obj) { // eslint-disable-line guard-for-in - const x = obj[key]; - ret[key] = typeof x === 'function' && filter(key) ? processFn(x, opts) : x; - } + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } - return ret; + // must be a plain object + return 'object'; }; /***/ }), -/* 45 */ +/* 50 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -3687,18 +4005,18 @@ var RefCountSubscriber = /*@__PURE__*/ (function (_super) { /***/ }), -/* 46 */ +/* 51 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ReplaySubject; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); /* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8); -/* harmony import */ var _scheduler_queue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(72); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5); -/* harmony import */ var _operators_observeOn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(66); -/* harmony import */ var _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(25); -/* harmony import */ var _SubjectSubscription__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(74); +/* harmony import */ var _scheduler_queue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(88); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6); +/* harmony import */ var _operators_observeOn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(82); +/* harmony import */ var _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(28); +/* harmony import */ var _SubjectSubscription__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(90); /** PURE_IMPORTS_START tslib,_Subject,_scheduler_queue,_Subscription,_operators_observeOn,_util_ObjectUnsubscribedError,_SubjectSubscription PURE_IMPORTS_END */ @@ -3819,15 +4137,15 @@ var ReplayEvent = /*@__PURE__*/ (function () { /***/ }), -/* 47 */ +/* 52 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return of; }); /* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(12); -/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17); +/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(18); /* harmony import */ var _empty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9); -/* harmony import */ var _scalar__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(53); +/* harmony import */ var _scalar__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(58); /** PURE_IMPORTS_START _util_isScheduler,_fromArray,_empty,_scalar PURE_IMPORTS_END */ @@ -3858,7 +4176,7 @@ function of() { /***/ }), -/* 48 */ +/* 53 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -3882,7 +4200,7 @@ function dispatch(_a) { /***/ }), -/* 49 */ +/* 54 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -3894,7 +4212,7 @@ function dispatch(_a) { /* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(11); /* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4); /* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(3); -/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(17); +/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(18); /** PURE_IMPORTS_START tslib,_util_isScheduler,_util_isArray,_OuterSubscriber,_util_subscribeToResult,_fromArray PURE_IMPORTS_END */ @@ -3999,13 +4317,13 @@ var CombineLatestSubscriber = /*@__PURE__*/ (function (_super) { /***/ }), -/* 50 */ +/* 55 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return mergeAll; }); -/* harmony import */ var _mergeMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(27); -/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(21); +/* harmony import */ var _mergeMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(31); +/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(23); /** PURE_IMPORTS_START _mergeMap,_util_identity PURE_IMPORTS_END */ @@ -4019,13 +4337,13 @@ function mergeAll(concurrent) { /***/ }), -/* 51 */ +/* 56 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return defer; }); /* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); -/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(15); +/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17); /* harmony import */ var _empty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9); /** PURE_IMPORTS_START _Observable,_from,_empty PURE_IMPORTS_END */ @@ -4049,7 +4367,7 @@ function defer(observableFactory) { /***/ }), -/* 52 */ +/* 57 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -4057,12 +4375,12 @@ function defer(observableFactory) { /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ZipOperator; }); /* unused harmony export ZipSubscriber */ /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); -/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17); +/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(18); /* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(11); /* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1); /* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4); /* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(3); -/* harmony import */ var _internal_symbol_iterator__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(23); +/* harmony import */ var _internal_symbol_iterator__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(25); /** PURE_IMPORTS_START tslib,_fromArray,_util_isArray,_Subscriber,_OuterSubscriber,_util_subscribeToResult,_.._internal_symbol_iterator PURE_IMPORTS_END */ @@ -4282,7 +4600,7 @@ var ZipBufferIterator = /*@__PURE__*/ (function (_super) { /***/ }), -/* 53 */ +/* 58 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -4303,12 +4621,12 @@ function scalar(value) { /***/ }), -/* 54 */ +/* 59 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; -// EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/node_modules/tslib/tslib.es6.js +// EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/tslib/tslib.es6.js var tslib_es6 = __webpack_require__(0); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/Immediate.js @@ -4335,7 +4653,7 @@ var Immediate = { //# sourceMappingURL=Immediate.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/scheduler/AsyncAction.js + 1 modules -var AsyncAction = __webpack_require__(34); +var AsyncAction = __webpack_require__(37); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/scheduler/AsapAction.js /** PURE_IMPORTS_START tslib,_util_Immediate,_AsyncAction PURE_IMPORTS_END */ @@ -4379,7 +4697,7 @@ var AsapAction_AsapAction = /*@__PURE__*/ (function (_super) { //# sourceMappingURL=AsapAction.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/scheduler/AsyncScheduler.js -var AsyncScheduler = __webpack_require__(32); +var AsyncScheduler = __webpack_require__(35); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/scheduler/AsapScheduler.js /** PURE_IMPORTS_START tslib,_AsyncScheduler PURE_IMPORTS_END */ @@ -4426,13 +4744,13 @@ var asap = /*@__PURE__*/ new AsapScheduler_AsapScheduler(AsapAction_AsapAction); /***/ }), -/* 55 */ +/* 60 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return empty; }); -/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(18); -/* harmony import */ var _util_hostReportError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(37); +/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(19); +/* harmony import */ var _util_hostReportError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(41); /** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */ @@ -4453,15 +4771,15 @@ var empty = { /***/ }), -/* 56 */ +/* 61 */ /***/ (function(module, exports, __webpack_require__) { -var fs = __webpack_require__(16) -var polyfills = __webpack_require__(132) -var legacy = __webpack_require__(134) +var fs = __webpack_require__(13) +var polyfills = __webpack_require__(177) +var legacy = __webpack_require__(179) var queue = [] -var util = __webpack_require__(19) +var util = __webpack_require__(14) function noop () {} @@ -4478,11 +4796,11 @@ else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { process.on('exit', function() { debug(queue) - __webpack_require__(57).equal(queue.length, 0) + __webpack_require__(62).equal(queue.length, 0) }) } -module.exports = patch(__webpack_require__(94)) +module.exports = patch(__webpack_require__(115)) if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH) { module.exports = patch(fs) } @@ -4721,13 +5039,784 @@ function retry () { /***/ }), -/* 57 */ +/* 62 */ /***/ (function(module, exports) { module.exports = require("assert"); /***/ }), -/* 58 */ +/* 63 */ +/***/ (function(module, exports) { + +module.exports = require("events"); + +/***/ }), +/* 64 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var extend = __webpack_require__(20); + +/** + * The main export is a function that takes a `pattern` string and an `options` object. + * + * ```js + & var not = require('regex-not'); + & console.log(not('foo')); + & //=> /^(?:(?!^(?:foo)$).)*$/ + * ``` + * + * @param {String} `pattern` + * @param {Object} `options` + * @return {RegExp} Converts the given `pattern` to a regex using the specified `options`. + * @api public + */ + +function toRegex(pattern, options) { + return new RegExp(toRegex.create(pattern, options)); +} + +/** + * Create a regex-compatible string from the given `pattern` and `options`. + * + * ```js + & var not = require('regex-not'); + & console.log(not.create('foo')); + & //=> '^(?:(?!^(?:foo)$).)*$' + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {String} + * @api public + */ + +toRegex.create = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } + + var opts = extend({}, options); + if (opts && opts.contains === true) { + opts.strictNegate = false; + } + + var open = opts.strictOpen !== false ? '^' : ''; + var close = opts.strictClose !== false ? '$' : ''; + var endChar = opts.endChar ? opts.endChar : '+'; + var str = pattern; + + if (opts && opts.strictNegate === false) { + str = '(?:(?!(?:' + pattern + ')).)' + endChar; + } else { + str = '(?:(?!^(?:' + pattern + ')$).)' + endChar; + } + + return open + str + close; +}; + +/** + * Expose `toRegex` + */ + +module.exports = toRegex; + + +/***/ }), +/* 65 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * array-unique + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +module.exports = function unique(arr) { + if (!Array.isArray(arr)) { + throw new TypeError('array-unique expects an array.'); + } + + var len = arr.length; + var i = -1; + + while (i++ < len) { + var j = i + 1; + + for (; j < arr.length; ++j) { + if (arr[i] === arr[j]) { + arr.splice(j--, 1); + } + } + } + return arr; +}; + +module.exports.immutable = function uniqueImmutable(arr) { + if (!Array.isArray(arr)) { + throw new TypeError('array-unique expects an array.'); + } + + var arrLen = arr.length; + var newArr = new Array(arrLen); + + for (var i = 0; i < arrLen; i++) { + newArr[i] = arr[i]; + } + + return module.exports(newArr); +}; + + +/***/ }), +/* 66 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var Base = __webpack_require__(330); +var define = __webpack_require__(67); +var Compiler = __webpack_require__(379); +var Parser = __webpack_require__(408); +var utils = __webpack_require__(79); +var regexCache = {}; +var cache = {}; + +/** + * Create a new instance of `Snapdragon` with the given `options`. + * + * ```js + * var snapdragon = new Snapdragon(); + * ``` + * + * @param {Object} `options` + * @api public + */ + +function Snapdragon(options) { + Base.call(this, null, options); + this.options = utils.extend({source: 'string'}, this.options); + this.compiler = new Compiler(this.options); + this.parser = new Parser(this.options); + + Object.defineProperty(this, 'compilers', { + get: function() { + return this.compiler.compilers; + } + }); + + Object.defineProperty(this, 'parsers', { + get: function() { + return this.parser.parsers; + } + }); + + Object.defineProperty(this, 'regex', { + get: function() { + return this.parser.regex; + } + }); +} + +/** + * Inherit Base + */ + +Base.extend(Snapdragon); + +/** + * Add a parser to `snapdragon.parsers` for capturing the given `type` using + * the specified regex or parser function. A function is useful if you need + * to customize how the token is created and/or have access to the parser + * instance to check options, etc. + * + * ```js + * snapdragon + * .capture('slash', /^\//) + * .capture('dot', function() { + * var pos = this.position(); + * var m = this.match(/^\./); + * if (!m) return; + * return pos({ + * type: 'dot', + * val: m[0] + * }); + * }); + * ``` + * @param {String} `type` + * @param {RegExp|Function} `regex` + * @return {Object} Returns the parser instance for chaining + * @api public + */ + +Snapdragon.prototype.capture = function() { + return this.parser.capture.apply(this.parser, arguments); +}; + +/** + * Register a plugin `fn`. + * + * ```js + * var snapdragon = new Snapdgragon([options]); + * snapdragon.use(function() { + * console.log(this); //<= snapdragon instance + * console.log(this.parser); //<= parser instance + * console.log(this.compiler); //<= compiler instance + * }); + * ``` + * @param {Object} `fn` + * @api public + */ + +Snapdragon.prototype.use = function(fn) { + fn.call(this, this); + return this; +}; + +/** + * Parse the given `str`. + * + * ```js + * var snapdragon = new Snapdgragon([options]); + * // register parsers + * snapdragon.parser.use(function() {}); + * + * // parse + * var ast = snapdragon.parse('foo/bar'); + * console.log(ast); + * ``` + * @param {String} `str` + * @param {Object} `options` Set `options.sourcemap` to true to enable source maps. + * @return {Object} Returns an AST. + * @api public + */ + +Snapdragon.prototype.parse = function(str, options) { + this.options = utils.extend({}, this.options, options); + var parsed = this.parser.parse(str, this.options); + + // add non-enumerable parser reference + define(parsed, 'parser', this.parser); + return parsed; +}; + +/** + * Compile the given `AST`. + * + * ```js + * var snapdragon = new Snapdgragon([options]); + * // register plugins + * snapdragon.use(function() {}); + * // register parser plugins + * snapdragon.parser.use(function() {}); + * // register compiler plugins + * snapdragon.compiler.use(function() {}); + * + * // parse + * var ast = snapdragon.parse('foo/bar'); + * + * // compile + * var res = snapdragon.compile(ast); + * console.log(res.output); + * ``` + * @param {Object} `ast` + * @param {Object} `options` + * @return {Object} Returns an object with an `output` property with the rendered string. + * @api public + */ + +Snapdragon.prototype.compile = function(ast, options) { + this.options = utils.extend({}, this.options, options); + var compiled = this.compiler.compile(ast, this.options); + + // add non-enumerable compiler reference + define(compiled, 'compiler', this.compiler); + return compiled; +}; + +/** + * Expose `Snapdragon` + */ + +module.exports = Snapdragon; + +/** + * Expose `Parser` and `Compiler` + */ + +module.exports.Compiler = Compiler; +module.exports.Parser = Parser; + + +/***/ }), +/* 67 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * define-property + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +var isDescriptor = __webpack_require__(373); + +module.exports = function defineProperty(obj, prop, val) { + if (typeof obj !== 'object' && typeof obj !== 'function') { + throw new TypeError('expected an object or function.'); + } + + if (typeof prop !== 'string') { + throw new TypeError('expected `prop` to be a string.'); + } + + if (isDescriptor(val) && ('set' in val || 'get' in val)) { + return Object.defineProperty(obj, prop, val); + } + + return Object.defineProperty(obj, prop, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); +}; + + +/***/ }), +/* 68 */ +/***/ (function(module, exports) { + +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ +function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } +} +exports.getArg = getArg; + +var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; +var dataUrlRegexp = /^data:.+\,.+$/; + +function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; +} +exports.urlParse = urlParse; + +function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; +} +exports.urlGenerate = urlGenerate; + +/** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ +function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; +} +exports.normalize = normalize; + +/** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ +function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; +} +exports.join = join; + +exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); +}; + +/** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ +function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); +} +exports.relative = relative; + +var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); +}()); + +function identity (s) { + return s; +} + +/** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ +function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; +} +exports.toSetString = supportsNullProto ? identity : toSetString; + +function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; +} +exports.fromSetString = supportsNullProto ? identity : fromSetString; + +function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; +} + +/** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ +function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = mappingA.source - mappingB.source; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return mappingA.name - mappingB.name; +} +exports.compareByOriginalPositions = compareByOriginalPositions; + +/** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ +function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = mappingA.source - mappingB.source; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return mappingA.name - mappingB.name; +} +exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + +function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; +} + +/** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ +function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + + +/***/ }), +/* 69 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -4754,35 +5843,7 @@ var Scheduler = /*@__PURE__*/ (function () { /***/ }), -/* 59 */ -/***/ (function(module, exports) { - -module.exports = function(module) { - if (!module.webpackPolyfill) { - module.deprecate = function() {}; - module.paths = []; - // module.parent = undefined by default - if (!module.children) module.children = []; - Object.defineProperty(module, "loaded", { - enumerable: true, - get: function() { - return module.l; - } - }); - Object.defineProperty(module, "id", { - enumerable: true, - get: function() { - return module.i; - } - }); - module.webpackPolyfill = 1; - } - return module; -}; - - -/***/ }), -/* 60 */ +/* 70 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -4893,23 +5954,23 @@ let forceCreate = (() => { }; })(); -var _cmdShim = __webpack_require__(131); +var _cmdShim = __webpack_require__(176); var _cmdShim2 = _interopRequireDefault(_cmdShim); -var _fs = __webpack_require__(16); +var _fs = __webpack_require__(13); var _fs2 = _interopRequireDefault(_fs); -var _mkdirp = __webpack_require__(95); +var _mkdirp = __webpack_require__(116); var _mkdirp2 = _interopRequireDefault(_mkdirp); -var _ncp = __webpack_require__(135); +var _ncp = __webpack_require__(180); -var _path = __webpack_require__(7); +var _path = __webpack_require__(5); -var _util = __webpack_require__(19); +var _util = __webpack_require__(14); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -4946,13 +6007,55 @@ exports.readFile = readFile; exports.mkdirp = mkdirp; /***/ }), -/* 61 */ -/***/ (function(module, exports) { +/* 71 */ +/***/ (function(module, exports, __webpack_require__) { + +var wrappy = __webpack_require__(120) +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) + +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) + +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} + +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} -module.exports = require("events"); /***/ }), -/* 62 */ +/* 72 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -4965,11 +6068,11 @@ exports.isLinkDependency = undefined; exports.readPackageJson = readPackageJson; exports.writePackageJson = writePackageJson; -var _readPkg = __webpack_require__(143); +var _readPkg = __webpack_require__(188); var _readPkg2 = _interopRequireDefault(_readPkg); -var _writePkg = __webpack_require__(166); +var _writePkg = __webpack_require__(212); var _writePkg2 = _interopRequireDefault(_writePkg); @@ -5002,7 +6105,7 @@ function writePackageJson(path, json) { const isLinkDependency = exports.isLinkDependency = depVersion => depVersion.startsWith('link:'); /***/ }), -/* 63 */ +/* 73 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -5010,7 +6113,7 @@ const isLinkDependency = exports.isLinkDependency = depVersion => depVersion.sta /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return GroupedObservable; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); /* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6); /* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2); /* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(8); /** PURE_IMPORTS_START tslib,_Subscriber,_Subscription,_Observable,_Subject PURE_IMPORTS_END */ @@ -5198,7 +6301,553 @@ var InnerRefCountSubscription = /*@__PURE__*/ (function (_super) { /***/ }), -/* 64 */ +/* 74 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +module.exports = function isExtendable(val) { + return typeof val !== 'undefined' && val !== null + && (typeof val === 'object' || typeof val === 'function'); +}; + + +/***/ }), +/* 75 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var splitString = __webpack_require__(136); +var utils = module.exports; + +/** + * Module dependencies + */ + +utils.define = __webpack_require__(44); +utils.extend = __webpack_require__(20); +utils.flatten = __webpack_require__(323); +utils.isObject = __webpack_require__(30); +utils.fillRange = __webpack_require__(324); +utils.repeat = __webpack_require__(326); +utils.unique = __webpack_require__(65); + +/** + * Returns true if the given string contains only empty brace sets. + */ + +utils.isEmptySets = function(str) { + return /^(?:\{,\})+$/.test(str); +}; + +/** + * Returns true if the given string contains only empty brace sets. + */ + +utils.isQuotedString = function(str) { + var open = str.charAt(0); + if (open === '\'' || open === '"' || open === '`') { + return str.slice(-1) === open; + } + return false; +}; + +/** + * Create the key to use for memoization. The unique key is generated + * by iterating over the options and concatenating key-value pairs + * to the pattern string. + */ + +utils.createKey = function(pattern, options) { + var id = pattern; + if (typeof options === 'undefined') { + return id; + } + var keys = Object.keys(options); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + id += ';' + key + '=' + String(options[key]); + } + return id; +}; + +/** + * Normalize options + */ + +utils.createOptions = function(options) { + var opts = utils.extend.apply(null, arguments); + if (typeof opts.expand === 'boolean') { + opts.optimize = !opts.expand; + } + if (typeof opts.optimize === 'boolean') { + opts.expand = !opts.optimize; + } + if (opts.optimize === true) { + opts.makeRe = true; + } + return opts; +}; + +/** + * Join patterns in `a` to patterns in `b` + */ + +utils.join = function(a, b, options) { + options = options || {}; + a = utils.arrayify(a); + b = utils.arrayify(b); + + if (!a.length) return b; + if (!b.length) return a; + + var len = a.length; + var idx = -1; + var arr = []; + + while (++idx < len) { + var val = a[idx]; + if (Array.isArray(val)) { + for (var i = 0; i < val.length; i++) { + val[i] = utils.join(val[i], b, options); + } + arr.push(val); + continue; + } + + for (var j = 0; j < b.length; j++) { + var bval = b[j]; + + if (Array.isArray(bval)) { + arr.push(utils.join(val, bval, options)); + } else { + arr.push(val + bval); + } + } + } + return arr; +}; + +/** + * Split the given string on `,` if not escaped. + */ + +utils.split = function(str, options) { + var opts = utils.extend({sep: ','}, options); + if (typeof opts.keepQuotes !== 'boolean') { + opts.keepQuotes = true; + } + if (opts.unescape === false) { + opts.keepEscaping = true; + } + return splitString(str, opts, utils.escapeBrackets(opts)); +}; + +/** + * Expand ranges or sets in the given `pattern`. + * + * @param {String} `str` + * @param {Object} `options` + * @return {Object} + */ + +utils.expand = function(str, options) { + var opts = utils.extend({rangeLimit: 10000}, options); + var segs = utils.split(str, opts); + var tok = { segs: segs }; + + if (utils.isQuotedString(str)) { + return tok; + } + + if (opts.rangeLimit === true) { + opts.rangeLimit = 10000; + } + + if (segs.length > 1) { + if (opts.optimize === false) { + tok.val = segs[0]; + return tok; + } + + tok.segs = utils.stringifyArray(tok.segs); + } else if (segs.length === 1) { + var arr = str.split('..'); + + if (arr.length === 1) { + tok.val = tok.segs[tok.segs.length - 1] || tok.val || str; + tok.segs = []; + return tok; + } + + if (arr.length === 2 && arr[0] === arr[1]) { + tok.escaped = true; + tok.val = arr[0]; + tok.segs = []; + return tok; + } + + if (arr.length > 1) { + if (opts.optimize !== false) { + opts.optimize = true; + delete opts.expand; + } + + if (opts.optimize !== true) { + var min = Math.min(arr[0], arr[1]); + var max = Math.max(arr[0], arr[1]); + var step = arr[2] || 1; + + if (opts.rangeLimit !== false && ((max - min) / step >= opts.rangeLimit)) { + throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); + } + } + + arr.push(opts); + tok.segs = utils.fillRange.apply(null, arr); + + if (!tok.segs.length) { + tok.escaped = true; + tok.val = str; + return tok; + } + + if (opts.optimize === true) { + tok.segs = utils.stringifyArray(tok.segs); + } + + if (tok.segs === '') { + tok.val = str; + } else { + tok.val = tok.segs[0]; + } + return tok; + } + } else { + tok.val = str; + } + return tok; +}; + +/** + * Ensure commas inside brackets and parens are not split. + * @param {Object} `tok` Token from the `split-string` module + * @return {undefined} + */ + +utils.escapeBrackets = function(options) { + return function(tok) { + if (tok.escaped && tok.val === 'b') { + tok.val = '\\b'; + return; + } + + if (tok.val !== '(' && tok.val !== '[') return; + var opts = utils.extend({}, options); + var brackets = []; + var parens = []; + var stack = []; + var val = tok.val; + var str = tok.str; + var i = tok.idx - 1; + + while (++i < str.length) { + var ch = str[i]; + + if (ch === '\\') { + val += (opts.keepEscaping === false ? '' : ch) + str[++i]; + continue; + } + + if (ch === '(') { + parens.push(ch); + stack.push(ch); + } + + if (ch === '[') { + brackets.push(ch); + stack.push(ch); + } + + if (ch === ')') { + parens.pop(); + stack.pop(); + if (!stack.length) { + val += ch; + break; + } + } + + if (ch === ']') { + brackets.pop(); + stack.pop(); + if (!stack.length) { + val += ch; + break; + } + } + val += ch; + } + + tok.split = false; + tok.val = val.slice(1); + tok.idx = i; + }; +}; + +/** + * Returns true if the given string looks like a regex quantifier + * @return {Boolean} + */ + +utils.isQuantifier = function(str) { + return /^(?:[0-9]?,[0-9]|[0-9],)$/.test(str); +}; + +/** + * Cast `val` to an array. + * @param {*} `val` + */ + +utils.stringifyArray = function(arr) { + return [utils.arrayify(arr).join('|')]; +}; + +/** + * Cast `val` to an array. + * @param {*} `val` + */ + +utils.arrayify = function(arr) { + if (typeof arr === 'undefined') { + return []; + } + if (typeof arr === 'string') { + return [arr]; + } + return arr; +}; + +/** + * Returns true if the given `str` is a non-empty string + * @return {Boolean} + */ + +utils.isString = function(str) { + return str != null && typeof str === 'string'; +}; + +/** + * Get the last element from `array` + * @param {Array} `array` + * @return {*} + */ + +utils.last = function(arr, n) { + return arr[arr.length - (n || 1)]; +}; + +utils.escapeRegex = function(str) { + return str.replace(/\\?([!^*?()\[\]{}+?/])/g, '\\$1'); +}; + + +/***/ }), +/* 76 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * is-plain-object + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isObject = __webpack_require__(30); + +function isObjectObject(o) { + return isObject(o) === true + && Object.prototype.toString.call(o) === '[object Object]'; +} + +module.exports = function isPlainObject(o) { + var ctor,prot; + + if (isObjectObject(o) === false) return false; + + // If has modified constructor + ctor = o.constructor; + if (typeof ctor !== 'function') return false; + + // If has modified prototype + prot = ctor.prototype; + if (isObjectObject(prot) === false) return false; + + // If constructor does not have an Object-specific method + if (prot.hasOwnProperty('isPrototypeOf') === false) { + return false; + } + + // Most likely a plain Object + return true; +}; + + +/***/ }), +/* 77 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * is-number + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +var typeOf = __webpack_require__(49); + +module.exports = function isNumber(num) { + var type = typeOf(num); + + if (type === 'string') { + if (!num.trim()) return false; + } else if (type !== 'number') { + return false; + } + + return (num - num + 1) >= 0; +}; + + +/***/ }), +/* 78 */ +/***/ (function(module, exports) { + +/*! + * get-value + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + +module.exports = function(obj, prop, a, b, c) { + if (!isObject(obj) || !prop) { + return obj; + } + + prop = toString(prop); + + // allowing for multiple properties to be passed as + // a string or array, but much faster (3-4x) than doing + // `[].slice.call(arguments)` + if (a) prop += '.' + toString(a); + if (b) prop += '.' + toString(b); + if (c) prop += '.' + toString(c); + + if (prop in obj) { + return obj[prop]; + } + + var segs = prop.split('.'); + var len = segs.length; + var i = -1; + + while (obj && (++i < len)) { + var key = segs[i]; + while (key[key.length - 1] === '\\') { + key = key.slice(0, -1) + '.' + segs[++i]; + } + obj = obj[key]; + } + return obj; +}; + +function isObject(val) { + return val !== null && (typeof val === 'object' || typeof val === 'function'); +} + +function toString(val) { + if (!val) return ''; + if (Array.isArray(val)) { + return val.join('.'); + } + return val; +} + + +/***/ }), +/* 79 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Module dependencies + */ + +exports.extend = __webpack_require__(20); +exports.SourceMap = __webpack_require__(393); +exports.sourceMapResolve = __webpack_require__(400); + +/** + * Convert backslash in the given string to forward slashes + */ + +exports.unixify = function(fp) { + return fp.split(/\\+/).join('/'); +}; + +/** + * Return true if `val` is a non-empty string + * + * @param {String} `str` + * @return {Boolean} + */ + +exports.isString = function(str) { + return str && typeof str === 'string'; +}; + +/** + * Cast `val` to an array + * @return {Array} + */ + +exports.arrayify = function(val) { + if (typeof val === 'string') return [val]; + return val ? (Array.isArray(val) ? val : [val]) : []; +}; + +/** + * Get the last `n` element from the given `array` + * @param {Array} `array` + * @return {*} + */ + +exports.last = function(arr, n) { + return arr[arr.length - (n || 1)]; +}; + + +/***/ }), +/* 80 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -5208,8 +6857,8 @@ var InnerRefCountSubscription = /*@__PURE__*/ (function (_super) { /* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8); /* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2); /* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(5); -/* harmony import */ var _operators_refCount__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(45); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(6); +/* harmony import */ var _operators_refCount__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(50); /** PURE_IMPORTS_START tslib,_Subject,_Observable,_Subscriber,_Subscription,_operators_refCount PURE_IMPORTS_END */ @@ -5356,14 +7005,14 @@ var RefCountSubscriber = /*@__PURE__*/ (function (_super) { /***/ }), -/* 65 */ +/* 81 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return BehaviorSubject; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); /* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8); -/* harmony import */ var _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(25); +/* harmony import */ var _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(28); /** PURE_IMPORTS_START tslib,_Subject,_util_ObjectUnsubscribedError PURE_IMPORTS_END */ @@ -5410,7 +7059,7 @@ var BehaviorSubject = /*@__PURE__*/ (function (_super) { /***/ }), -/* 66 */ +/* 82 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -5420,7 +7069,7 @@ var BehaviorSubject = /*@__PURE__*/ (function (_super) { /* unused harmony export ObserveOnMessage */ /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); /* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1); -/* harmony import */ var _Notification__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(22); +/* harmony import */ var _Notification__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(24); /** PURE_IMPORTS_START tslib,_Subscriber,_Notification PURE_IMPORTS_END */ @@ -5490,7 +7139,7 @@ var ObserveOnMessage = /*@__PURE__*/ (function () { /***/ }), -/* 67 */ +/* 83 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -5513,12 +7162,12 @@ var TimeoutError = /*@__PURE__*/ (function (_super) { /***/ }), -/* 68 */ +/* 84 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return concatAll; }); -/* harmony import */ var _mergeAll__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(50); +/* harmony import */ var _mergeAll__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(55); /** PURE_IMPORTS_START _mergeAll PURE_IMPORTS_END */ function concatAll() { @@ -5528,15 +7177,15 @@ function concatAll() { /***/ }), -/* 69 */ +/* 85 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return merge; }); /* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); /* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(12); -/* harmony import */ var _operators_mergeAll__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(50); -/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(17); +/* harmony import */ var _operators_mergeAll__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(55); +/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(18); /** PURE_IMPORTS_START _Observable,_util_isScheduler,_operators_mergeAll,_fromArray PURE_IMPORTS_END */ @@ -5568,7 +7217,7 @@ function merge() { /***/ }), -/* 70 */ +/* 86 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -5577,7 +7226,7 @@ function merge() { /* unused harmony export RaceSubscriber */ /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); /* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(11); -/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(17); +/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(18); /* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4); /* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(3); /** PURE_IMPORTS_START tslib,_util_isArray,_fromArray,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ @@ -5661,14 +7310,14 @@ var RaceSubscriber = /*@__PURE__*/ (function (_super) { /***/ }), -/* 71 */ +/* 87 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return timer; }); /* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); /* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(10); -/* harmony import */ var _util_isNumeric__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(35); +/* harmony import */ var _util_isNumeric__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(38); /* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(12); /** PURE_IMPORTS_START _Observable,_scheduler_async,_util_isNumeric,_util_isScheduler PURE_IMPORTS_END */ @@ -5714,16 +7363,16 @@ function dispatch(state) { /***/ }), -/* 72 */ +/* 88 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; -// EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/node_modules/tslib/tslib.es6.js +// EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/tslib/tslib.es6.js var tslib_es6 = __webpack_require__(0); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/scheduler/AsyncAction.js + 1 modules -var AsyncAction = __webpack_require__(34); +var AsyncAction = __webpack_require__(37); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/scheduler/QueueAction.js /** PURE_IMPORTS_START tslib,_AsyncAction PURE_IMPORTS_END */ @@ -5769,7 +7418,7 @@ var QueueAction_QueueAction = /*@__PURE__*/ (function (_super) { //# sourceMappingURL=QueueAction.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/scheduler/AsyncScheduler.js -var AsyncScheduler = __webpack_require__(32); +var AsyncScheduler = __webpack_require__(35); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/scheduler/QueueScheduler.js /** PURE_IMPORTS_START tslib,_AsyncScheduler PURE_IMPORTS_END */ @@ -5795,7 +7444,7 @@ var queue = /*@__PURE__*/ new QueueScheduler_QueueScheduler(QueueAction_QueueAct /***/ }), -/* 73 */ +/* 89 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -5808,13 +7457,13 @@ function isObject(x) { /***/ }), -/* 74 */ +/* 90 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return SubjectSubscription; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); -/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5); +/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6); /** PURE_IMPORTS_START tslib,_Subscription PURE_IMPORTS_END */ @@ -5850,7 +7499,7 @@ var SubjectSubscription = /*@__PURE__*/ (function (_super) { /***/ }), -/* 75 */ +/* 91 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -5870,21 +7519,21 @@ var subscribeToArray = function (array) { /***/ }), -/* 76 */ +/* 92 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return subscribeTo; }); /* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); -/* harmony import */ var _subscribeToArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(75); -/* harmony import */ var _subscribeToPromise__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(80); -/* harmony import */ var _subscribeToIterable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(81); -/* harmony import */ var _subscribeToObservable__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(77); -/* harmony import */ var _isArrayLike__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(78); -/* harmony import */ var _isPromise__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(79); -/* harmony import */ var _isObject__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(73); -/* harmony import */ var _symbol_iterator__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(23); -/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(24); +/* harmony import */ var _subscribeToArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(91); +/* harmony import */ var _subscribeToPromise__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(96); +/* harmony import */ var _subscribeToIterable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(97); +/* harmony import */ var _subscribeToObservable__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(93); +/* harmony import */ var _isArrayLike__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(94); +/* harmony import */ var _isPromise__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(95); +/* harmony import */ var _isObject__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(89); +/* harmony import */ var _symbol_iterator__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(25); +/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(27); /** PURE_IMPORTS_START _Observable,_subscribeToArray,_subscribeToPromise,_subscribeToIterable,_subscribeToObservable,_isArrayLike,_isPromise,_isObject,_symbol_iterator,_symbol_observable PURE_IMPORTS_END */ @@ -5932,12 +7581,12 @@ var subscribeTo = function (result) { /***/ }), -/* 77 */ +/* 93 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return subscribeToObservable; }); -/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(24); +/* harmony import */ var _symbol_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(27); /** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */ var subscribeToObservable = function (obj) { @@ -5955,7 +7604,7 @@ var subscribeToObservable = function (obj) { /***/ }), -/* 78 */ +/* 94 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -5966,7 +7615,7 @@ var isArrayLike = (function (x) { return x && typeof x.length === 'number' && ty /***/ }), -/* 79 */ +/* 95 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -5979,12 +7628,12 @@ function isPromise(value) { /***/ }), -/* 80 */ +/* 96 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return subscribeToPromise; }); -/* harmony import */ var _hostReportError__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(37); +/* harmony import */ var _hostReportError__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(41); /** PURE_IMPORTS_START _hostReportError PURE_IMPORTS_END */ var subscribeToPromise = function (promise) { @@ -6003,12 +7652,12 @@ var subscribeToPromise = function (promise) { /***/ }), -/* 81 */ +/* 97 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return subscribeToIterable; }); -/* harmony import */ var _symbol_iterator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(23); +/* harmony import */ var _symbol_iterator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(25); /** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */ var subscribeToIterable = function (iterable) { @@ -6039,115 +7688,7 @@ var subscribeToIterable = function (iterable) { /***/ }), -/* 82 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; - -module.exports = function (str) { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); - } - - return str.replace(matchOperatorsRe, '\\$&'); -}; - - -/***/ }), -/* 83 */ -/***/ (function(module, exports, __webpack_require__) { - -var conversions = __webpack_require__(92); -var route = __webpack_require__(123); - -var convert = {}; - -var models = Object.keys(conversions); - -function wrapRaw(fn) { - var wrappedFn = function (args) { - if (args === undefined || args === null) { - return args; - } - - if (arguments.length > 1) { - args = Array.prototype.slice.call(arguments); - } - - return fn(args); - }; - - // preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } - - return wrappedFn; -} - -function wrapRounded(fn) { - var wrappedFn = function (args) { - if (args === undefined || args === null) { - return args; - } - - if (arguments.length > 1) { - args = Array.prototype.slice.call(arguments); - } - - var result = fn(args); - - // we're assuming the result is an array here. - // see notice in conversions.js; don't use box types - // in conversion functions. - if (typeof result === 'object') { - for (var len = result.length, i = 0; i < len; i++) { - result[i] = Math.round(result[i]); - } - } - - return result; - }; - - // preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } - - return wrappedFn; -} - -models.forEach(function (fromModel) { - convert[fromModel] = {}; - - Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); - Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); - - var routes = route(fromModel); - var routeModels = Object.keys(routes); - - routeModels.forEach(function (toModel) { - var fn = routes[toModel]; - - convert[fromModel][toModel] = wrapRounded(fn); - convert[fromModel][toModel].raw = wrapRaw(fn); - }); -}); - -module.exports = convert; - - -/***/ }), -/* 84 */ -/***/ (function(module, exports) { - -module.exports = require("os"); - -/***/ }), -/* 85 */ +/* 98 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -6234,7 +7775,7 @@ let parallelize = exports.parallelize = (() => { function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /***/ }), -/* 86 */ +/* 99 */ /***/ (function(module, exports, __webpack_require__) { module.exports = minimatch @@ -6242,11 +7783,11 @@ minimatch.Minimatch = Minimatch var path = { sep: '/' } try { - path = __webpack_require__(7) + path = __webpack_require__(5) } catch (er) {} var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} -var expand = __webpack_require__(137) +var expand = __webpack_require__(182) var plTypes = { '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, @@ -7163,7 +8704,7 @@ function regExpEscape (s) { /***/ }), -/* 87 */ +/* 100 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -7190,7 +8731,7 @@ module.exports.win32 = win32; /***/ }), -/* 88 */ +/* 101 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -7226,16 +8767,22 @@ class CliError extends Error { exports.CliError = CliError; /***/ }), -/* 89 */ +/* 102 */ +/***/ (function(module, exports) { + +module.exports = require("url"); + +/***/ }), +/* 103 */ /***/ (function(module, exports, __webpack_require__) { // Note: since nyc uses this module to output coverage, any lines // that are in the direct sync flow of nyc's outputCoverage are // ignored, since we can never get coverage for them. -var assert = __webpack_require__(57) -var signals = __webpack_require__(170) +var assert = __webpack_require__(62) +var signals = __webpack_require__(216) -var EE = __webpack_require__(61) +var EE = __webpack_require__(63) /* istanbul ignore if */ if (typeof EE !== 'function') { EE = EE.EventEmitter @@ -7389,13 +8936,7 @@ function processEmit (ev, arg) { /***/ }), -/* 90 */ -/***/ (function(module, exports) { - -module.exports = require("child_process"); - -/***/ }), -/* 91 */ +/* 104 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -7406,7 +8947,7 @@ Object.defineProperty(exports, "__esModule", { }); exports.getProjectPaths = getProjectPaths; -var _path = __webpack_require__(7); +var _path = __webpack_require__(5); /** * Returns all the paths where plugins are located @@ -7455,275 +8996,1218 @@ function getProjectPaths(rootPath, options) { */ /***/ }), -/* 92 */ +/* 105 */ /***/ (function(module, exports, __webpack_require__) { -/* MIT license */ -var cssKeywords = __webpack_require__(122); - -// NOTE: conversions should only return primitive values (i.e. arrays, or -// values that give correct `typeof` results). -// do not use box values types (i.e. Number(), String(), etc.) - -var reverseKeywords = {}; -for (var key in cssKeywords) { - if (cssKeywords.hasOwnProperty(key)) { - reverseKeywords[cssKeywords[key]] = key; - } -} +"use strict"; -var convert = module.exports = { - rgb: {channels: 3, labels: 'rgb'}, - hsl: {channels: 3, labels: 'hsl'}, - hsv: {channels: 3, labels: 'hsv'}, - hwb: {channels: 3, labels: 'hwb'}, - cmyk: {channels: 4, labels: 'cmyk'}, - xyz: {channels: 3, labels: 'xyz'}, - lab: {channels: 3, labels: 'lab'}, - lch: {channels: 3, labels: 'lch'}, - hex: {channels: 1, labels: ['hex']}, - keyword: {channels: 1, labels: ['keyword']}, - ansi16: {channels: 1, labels: ['ansi16']}, - ansi256: {channels: 1, labels: ['ansi256']}, - hcg: {channels: 3, labels: ['h', 'c', 'g']}, - apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, - gray: {channels: 1, labels: ['gray']} +var __values = (this && this.__values) || function (o) { + var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; + if (m) return m.call(o); + return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; }; +Object.defineProperty(exports, "__esModule", { value: true }); +var globParent = __webpack_require__(301); +var micromatch = __webpack_require__(305); +var GLOBSTAR = '**'; +/** + * Convert a windows «path» to a unix-style «path». + */ +function unixifyPattern(pattern) { + return pattern.replace(/\\/g, '/'); +} +exports.unixifyPattern = unixifyPattern; +/** + * Returns negative pattern as positive pattern. + */ +function convertToPositivePattern(pattern) { + return pattern.slice(1); +} +exports.convertToPositivePattern = convertToPositivePattern; +/** + * Returns positive pattern as negative pattern. + */ +function convertToNegativePattern(pattern) { + return '!' + pattern; +} +exports.convertToNegativePattern = convertToNegativePattern; +/** + * Return true if provided pattern is negative pattern. + */ +function isNegativePattern(pattern) { + return pattern.startsWith('!'); +} +exports.isNegativePattern = isNegativePattern; +/** + * Return true if provided pattern is positive pattern. + */ +function isPositivePattern(pattern) { + return !isNegativePattern(pattern); +} +exports.isPositivePattern = isPositivePattern; +/** + * Extracts negative patterns from array of patterns. + */ +function getNegativePatterns(patterns) { + return patterns.filter(isNegativePattern); +} +exports.getNegativePatterns = getNegativePatterns; +/** + * Extracts positive patterns from array of patterns. + */ +function getPositivePatterns(patterns) { + return patterns.filter(isPositivePattern); +} +exports.getPositivePatterns = getPositivePatterns; +/** + * Extract base directory from provided pattern. + */ +function getBaseDirectory(pattern) { + return globParent(pattern); +} +exports.getBaseDirectory = getBaseDirectory; +/** + * Return true if provided pattern has globstar. + */ +function hasGlobStar(pattern) { + return pattern.indexOf(GLOBSTAR) !== -1; +} +exports.hasGlobStar = hasGlobStar; +/** + * Return true if provided pattern ends with slash and globstar. + */ +function endsWithSlashGlobStar(pattern) { + return pattern.endsWith('/' + GLOBSTAR); +} +exports.endsWithSlashGlobStar = endsWithSlashGlobStar; +/** + * Trim trailing globstar if provided pattern ends with slash and globstar. + */ +function trimTrailingSlashGlobStar(pattern) { + return endsWithSlashGlobStar(pattern) ? pattern.slice(0, -3) : pattern; +} +exports.trimTrailingSlashGlobStar = trimTrailingSlashGlobStar; +/** + * Return naive depth of provided pattern. + */ +function getDepth(pattern) { + return pattern.split('/').length; +} +exports.getDepth = getDepth; +/** + * Make RegExp for provided pattern. + */ +function makeRe(pattern, options) { + return micromatch.makeRe(pattern, options); +} +exports.makeRe = makeRe; +/** + * Convert patterns to regexps. + */ +function convertPatternsToRe(patterns, options) { + return patterns.map(function (pattern) { return makeRe(pattern, options); }); +} +exports.convertPatternsToRe = convertPatternsToRe; +/** + * Returns true if the entry match any of the given RegExp's. + */ +function matchAny(entry, patternsRe) { + try { + for (var patternsRe_1 = __values(patternsRe), patternsRe_1_1 = patternsRe_1.next(); !patternsRe_1_1.done; patternsRe_1_1 = patternsRe_1.next()) { + var regexp = patternsRe_1_1.value; + if (regexp.test(entry)) { + return true; + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (patternsRe_1_1 && !patternsRe_1_1.done && (_a = patternsRe_1.return)) _a.call(patternsRe_1); + } + finally { if (e_1) throw e_1.error; } + } + return false; + var e_1, _a; +} +exports.matchAny = matchAny; +/** + * Returns true if the entry doesn't match any of the given negative RegExp's and match any of the given positive RegExp's. + */ +function match(entry, positiveRe, negativeRe) { + return matchAny(entry, negativeRe) ? false : matchAny(entry, positiveRe); +} +exports.match = match; -// hide .channels and .labels properties -for (var model in convert) { - if (convert.hasOwnProperty(model)) { - if (!('channels' in convert[model])) { - throw new Error('missing channels property: ' + model); - } - if (!('labels' in convert[model])) { - throw new Error('missing channel labels property: ' + model); - } +/***/ }), +/* 106 */ +/***/ (function(module, exports, __webpack_require__) { - if (convert[model].labels.length !== convert[model].channels) { - throw new Error('channel and label counts mismatch: ' + model); - } +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ - var channels = convert[model].channels; - var labels = convert[model].labels; - delete convert[model].channels; - delete convert[model].labels; - Object.defineProperty(convert[model], 'channels', {value: channels}); - Object.defineProperty(convert[model], 'labels', {value: labels}); - } +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = __webpack_require__(388); +} else { + module.exports = __webpack_require__(390); } -convert.rgb.hsl = function (rgb) { - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b = rgb[2] / 255; - var min = Math.min(r, g, b); - var max = Math.max(r, g, b); - var delta = max - min; - var h; - var s; - var l; - - if (max === min) { - h = 0; - } else if (r === max) { - h = (g - b) / delta; - } else if (g === max) { - h = 2 + (b - r) / delta; - } else if (b === max) { - h = 4 + (r - g) / delta; - } - - h = Math.min(h * 60, 360); - if (h < 0) { - h += 360; - } +/***/ }), +/* 107 */ +/***/ (function(module, exports, __webpack_require__) { - l = (min + max) / 2; +"use strict"; +/*! + * fragment-cache + * + * Copyright (c) 2016-2017, Jon Schlinkert. + * Released under the MIT License. + */ - if (max === min) { - s = 0; - } else if (l <= 0.5) { - s = delta / (max + min); - } else { - s = delta / (2 - max - min); - } - return [h, s * 100, l * 100]; -}; -convert.rgb.hsv = function (rgb) { - var r = rgb[0]; - var g = rgb[1]; - var b = rgb[2]; - var min = Math.min(r, g, b); - var max = Math.max(r, g, b); - var delta = max - min; - var h; - var s; - var v; +var MapCache = __webpack_require__(148); - if (max === 0) { - s = 0; - } else { - s = (delta / max * 1000) / 10; - } +/** + * Create a new `FragmentCache` with an optional object to use for `caches`. + * + * ```js + * var fragment = new FragmentCache(); + * ``` + * @name FragmentCache + * @param {String} `cacheName` + * @return {Object} Returns the [map-cache][] instance. + * @api public + */ - if (max === min) { - h = 0; - } else if (r === max) { - h = (g - b) / delta; - } else if (g === max) { - h = 2 + (b - r) / delta; - } else if (b === max) { - h = 4 + (r - g) / delta; - } +function FragmentCache(caches) { + this.caches = caches || {}; +} - h = Math.min(h * 60, 360); +/** + * Prototype + */ - if (h < 0) { - h += 360; - } +FragmentCache.prototype = { - v = ((max / 255) * 1000) / 10; + /** + * Get cache `name` from the `fragment.caches` object. Creates a new + * `MapCache` if it doesn't already exist. + * + * ```js + * var cache = fragment.cache('files'); + * console.log(fragment.caches.hasOwnProperty('files')); + * //=> true + * ``` + * @name .cache + * @param {String} `cacheName` + * @return {Object} Returns the [map-cache][] instance. + * @api public + */ - return [h, s, v]; -}; + cache: function(cacheName) { + return this.caches[cacheName] || (this.caches[cacheName] = new MapCache()); + }, -convert.rgb.hwb = function (rgb) { - var r = rgb[0]; - var g = rgb[1]; - var b = rgb[2]; - var h = convert.rgb.hsl(rgb)[0]; - var w = 1 / 255 * Math.min(r, Math.min(g, b)); + /** + * Set a value for property `key` on cache `name` + * + * ```js + * fragment.set('files', 'somefile.js', new File({path: 'somefile.js'})); + * ``` + * @name .set + * @param {String} `name` + * @param {String} `key` Property name to set + * @param {any} `val` The value of `key` + * @return {Object} The cache instance for chaining + * @api public + */ - b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + set: function(cacheName, key, val) { + var cache = this.cache(cacheName); + cache.set(key, val); + return cache; + }, - return [h, w * 100, b * 100]; -}; + /** + * Returns true if a non-undefined value is set for `key` on fragment cache `name`. + * + * ```js + * var cache = fragment.cache('files'); + * cache.set('somefile.js'); + * + * console.log(cache.has('somefile.js')); + * //=> true + * + * console.log(cache.has('some-other-file.js')); + * //=> false + * ``` + * @name .has + * @param {String} `name` Cache name + * @param {String} `key` Optionally specify a property to check for on cache `name` + * @return {Boolean} + * @api public + */ -convert.rgb.cmyk = function (rgb) { - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b = rgb[2] / 255; - var c; - var m; - var y; - var k; + has: function(cacheName, key) { + return typeof this.get(cacheName, key) !== 'undefined'; + }, - k = Math.min(1 - r, 1 - g, 1 - b); - c = (1 - r - k) / (1 - k) || 0; - m = (1 - g - k) / (1 - k) || 0; - y = (1 - b - k) / (1 - k) || 0; + /** + * Get `name`, or if specified, the value of `key`. Invokes the [cache]() method, + * so that cache `name` will be created it doesn't already exist. If `key` is not passed, + * the entire cache (`name`) is returned. + * + * ```js + * var Vinyl = require('vinyl'); + * var cache = fragment.cache('files'); + * cache.set('somefile.js', new Vinyl({path: 'somefile.js'})); + * console.log(cache.get('somefile.js')); + * //=> + * ``` + * @name .get + * @param {String} `name` + * @return {Object} Returns cache `name`, or the value of `key` if specified + * @api public + */ - return [c * 100, m * 100, y * 100, k * 100]; + get: function(name, key) { + var cache = this.cache(name); + if (typeof key === 'string') { + return cache.get(key); + } + return cache; + } }; /** - * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance - * */ -function comparativeDistance(x, y) { - return ( - Math.pow(x[0] - y[0], 2) + - Math.pow(x[1] - y[1], 2) + - Math.pow(x[2] - y[2], 2) - ); -} - -convert.rgb.keyword = function (rgb) { - var reversed = reverseKeywords[rgb]; - if (reversed) { - return reversed; - } + * Expose `FragmentCache` + */ - var currentClosestDistance = Infinity; - var currentClosestKeyword; +exports = module.exports = FragmentCache; - for (var keyword in cssKeywords) { - if (cssKeywords.hasOwnProperty(keyword)) { - var value = cssKeywords[keyword]; - // Compute comparative distance - var distance = comparativeDistance(rgb, value); +/***/ }), +/* 108 */ +/***/ (function(module, exports, __webpack_require__) { - // Check if its less, if so set as closest - if (distance < currentClosestDistance) { - currentClosestDistance = distance; - currentClosestKeyword = keyword; - } - } - } +"use strict"; - return currentClosestKeyword; -}; -convert.keyword.rgb = function (keyword) { - return cssKeywords[keyword]; -}; +const readdirSync = __webpack_require__(434); +const readdirAsync = __webpack_require__(440); +const readdirStream = __webpack_require__(442); -convert.rgb.xyz = function (rgb) { - var r = rgb[0] / 255; - var g = rgb[1] / 255; - var b = rgb[2] / 255; +module.exports = exports = readdirAsyncPath; +exports.readdir = exports.readdirAsync = exports.async = readdirAsyncPath; +exports.readdirAsyncStat = exports.async.stat = readdirAsyncStat; +exports.readdirStream = exports.stream = readdirStreamPath; +exports.readdirStreamStat = exports.stream.stat = readdirStreamStat; +exports.readdirSync = exports.sync = readdirSyncPath; +exports.readdirSyncStat = exports.sync.stat = readdirSyncStat; - // assume sRGB - r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); - g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); - b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); +/** + * Synchronous readdir that returns an array of string paths. + * + * @param {string} dir + * @param {object} [options] + * @returns {string[]} + */ +function readdirSyncPath (dir, options) { + return readdirSync(dir, options, {}); +} - var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); - var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); - var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); +/** + * Synchronous readdir that returns results as an array of {@link fs.Stats} objects + * + * @param {string} dir + * @param {object} [options] + * @returns {fs.Stats[]} + */ +function readdirSyncStat (dir, options) { + return readdirSync(dir, options, { stats: true }); +} - return [x * 100, y * 100, z * 100]; -}; +/** + * Aynchronous readdir (accepts an error-first callback or returns a {@link Promise}). + * Results are an array of path strings. + * + * @param {string} dir + * @param {object} [options] + * @param {function} [callback] + * @returns {Promise} + */ +function readdirAsyncPath (dir, options, callback) { + return readdirAsync(dir, options, callback, {}); +} -convert.rgb.lab = function (rgb) { - var xyz = convert.rgb.xyz(rgb); - var x = xyz[0]; - var y = xyz[1]; - var z = xyz[2]; - var l; - var a; - var b; +/** + * Aynchronous readdir (accepts an error-first callback or returns a {@link Promise}). + * Results are an array of {@link fs.Stats} objects. + * + * @param {string} dir + * @param {object} [options] + * @param {function} [callback] + * @returns {Promise} + */ +function readdirAsyncStat (dir, options, callback) { + return readdirAsync(dir, options, callback, { stats: true }); +} - x /= 95.047; - y /= 100; - z /= 108.883; +/** + * Aynchronous readdir that returns a {@link stream.Readable} (which is also an {@link EventEmitter}). + * All stream data events ("data", "file", "directory", "symlink") are passed a path string. + * + * @param {string} dir + * @param {object} [options] + * @returns {stream.Readable} + */ +function readdirStreamPath (dir, options) { + return readdirStream(dir, options, {}); +} - x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); - y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); - z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); +/** + * Aynchronous readdir that returns a {@link stream.Readable} (which is also an {@link EventEmitter}) + * All stream data events ("data", "file", "directory", "symlink") are passed an {@link fs.Stats} object. + * + * @param {string} dir + * @param {object} [options] + * @returns {stream.Readable} + */ +function readdirStreamStat (dir, options) { + return readdirStream(dir, options, { stats: true }); +} - l = (116 * y) - 16; - a = 500 * (x - y); - b = 200 * (y - z); - return [l, a, b]; -}; +/***/ }), +/* 109 */ +/***/ (function(module, exports, __webpack_require__) { -convert.hsl.rgb = function (hsl) { - var h = hsl[0] / 360; - var s = hsl[1] / 100; - var l = hsl[2] / 100; - var t1; - var t2; - var t3; - var rgb; - var val; +"use strict"; - if (s === 0) { - val = l * 255; - return [val, val, val]; - } - if (l < 0.5) { - t2 = l * (1 + s); - } else { - t2 = l + s - l * s; - } +const Readable = __webpack_require__(39).Readable; +const EventEmitter = __webpack_require__(63).EventEmitter; +const path = __webpack_require__(5); +const normalizeOptions = __webpack_require__(435); +const stat = __webpack_require__(437); +const call = __webpack_require__(110); + +/** + * Asynchronously reads the contents of a directory and streams the results + * via a {@link stream.Readable}. + */ +class DirectoryReader { + /** + * @param {string} dir - The absolute or relative directory path to read + * @param {object} [options] - User-specified options, if any (see {@link normalizeOptions}) + * @param {object} internalOptions - Internal options that aren't part of the public API + * @class + */ + constructor (dir, options, internalOptions) { + this.options = options = normalizeOptions(options, internalOptions); + + // Indicates whether we should keep reading + // This is set false if stream.Readable.push() returns false. + this.shouldRead = true; + + // The directories to read + // (initialized with the top-level directory) + this.queue = [{ + path: dir, + basePath: options.basePath, + posixBasePath: options.posixBasePath, + depth: 0 + }]; + + // The number of directories that are currently being processed + this.pending = 0; + + // The data that has been read, but not yet emitted + this.buffer = []; + + this.stream = new Readable({ objectMode: true }); + this.stream._read = () => { + // Start (or resume) reading + this.shouldRead = true; + + // If we have data in the buffer, then send the next chunk + if (this.buffer.length > 0) { + this.pushFromBuffer(); + } + + // If we have directories queued, then start processing the next one + if (this.queue.length > 0) { + if (this.options.facade.sync) { + while (this.queue.length > 0) { + this.readNextDirectory(); + } + } + else { + this.readNextDirectory(); + } + } + + this.checkForEOF(); + }; + } + + /** + * Reads the next directory in the queue + */ + readNextDirectory () { + let facade = this.options.facade; + let dir = this.queue.shift(); + this.pending++; + + // Read the directory listing + call.safe(facade.fs.readdir, dir.path, (err, items) => { + if (err) { + // fs.readdir threw an error + this.emit('error', err); + return this.finishedReadingDirectory(); + } + + try { + // Process each item in the directory (simultaneously, if async) + facade.forEach( + items, + this.processItem.bind(this, dir), + this.finishedReadingDirectory.bind(this, dir) + ); + } + catch (err2) { + // facade.forEach threw an error + // (probably because fs.readdir returned an invalid result) + this.emit('error', err2); + this.finishedReadingDirectory(); + } + }); + } + + /** + * This method is called after all items in a directory have been processed. + * + * NOTE: This does not necessarily mean that the reader is finished, since there may still + * be other directories queued or pending. + */ + finishedReadingDirectory () { + this.pending--; + + if (this.shouldRead) { + // If we have directories queued, then start processing the next one + if (this.queue.length > 0 && this.options.facade.async) { + this.readNextDirectory(); + } + + this.checkForEOF(); + } + } + + /** + * Determines whether the reader has finished processing all items in all directories. + * If so, then the "end" event is fired (via {@Readable#push}) + */ + checkForEOF () { + if (this.buffer.length === 0 && // The stuff we've already read + this.pending === 0 && // The stuff we're currently reading + this.queue.length === 0) { // The stuff we haven't read yet + // There's no more stuff! + this.stream.push(null); + } + } + + /** + * Processes a single item in a directory. + * + * If the item is a directory, and `option.deep` is enabled, then the item will be added + * to the directory queue. + * + * If the item meets the filter criteria, then it will be emitted to the reader's stream. + * + * @param {object} dir - A directory object from the queue + * @param {string} item - The name of the item (name only, no path) + * @param {function} done - A callback function that is called after the item has been processed + */ + processItem (dir, item, done) { + let stream = this.stream; + let options = this.options; + + let itemPath = dir.basePath + item; + let posixPath = dir.posixBasePath + item; + let fullPath = path.join(dir.path, item); + + // If `options.deep` is a number, and we've already recursed to the max depth, + // then there's no need to check fs.Stats to know if it's a directory. + // If `options.deep` is a function, then we'll need fs.Stats + let maxDepthReached = dir.depth >= options.recurseDepth; + + // Do we need to call `fs.stat`? + let needStats = + !maxDepthReached || // we need the fs.Stats to know if it's a directory + options.stats || // the user wants fs.Stats objects returned + options.recurseFn || // we need fs.Stats for the recurse function + options.filterFn || // we need fs.Stats for the filter function + EventEmitter.listenerCount(stream, 'file') || // we need the fs.Stats to know if it's a file + EventEmitter.listenerCount(stream, 'directory') || // we need the fs.Stats to know if it's a directory + EventEmitter.listenerCount(stream, 'symlink'); // we need the fs.Stats to know if it's a symlink + + // If we don't need stats, then exit early + if (!needStats) { + if (this.filter(itemPath, posixPath)) { + this.pushOrBuffer({ data: itemPath }); + } + return done(); + } + + // Get the fs.Stats object for this path + stat(options.facade.fs, fullPath, (err, stats) => { + if (err) { + // fs.stat threw an error + this.emit('error', err); + return done(); + } + + try { + // Add the item's path to the fs.Stats object + // The base of this path, and its separators are determined by the options + // (i.e. options.basePath and options.sep) + stats.path = itemPath; + + // Add depth of the path to the fs.Stats object for use this in the filter function + stats.depth = dir.depth; + + if (this.shouldRecurse(stats, posixPath, maxDepthReached)) { + // Add this subdirectory to the queue + this.queue.push({ + path: fullPath, + basePath: itemPath + options.sep, + posixBasePath: posixPath + '/', + depth: dir.depth + 1, + }); + } + + // Determine whether this item matches the filter criteria + if (this.filter(stats, posixPath)) { + this.pushOrBuffer({ + data: options.stats ? stats : itemPath, + file: stats.isFile(), + directory: stats.isDirectory(), + symlink: stats.isSymbolicLink(), + }); + } + + done(); + } + catch (err2) { + // An error occurred while processing the item + // (probably during a user-specified function, such as options.deep, options.filter, etc.) + this.emit('error', err2); + done(); + } + }); + } + + /** + * Pushes the given chunk of data to the stream, or adds it to the buffer, + * depending on the state of the stream. + * + * @param {object} chunk + */ + pushOrBuffer (chunk) { + // Add the chunk to the buffer + this.buffer.push(chunk); + + // If we're still reading, then immediately emit the next chunk in the buffer + // (which may or may not be the chunk that we just added) + if (this.shouldRead) { + this.pushFromBuffer(); + } + } + + /** + * Immediately pushes the next chunk in the buffer to the reader's stream. + * The "data" event will always be fired (via {@link Readable#push}). + * In addition, the "file", "directory", and/or "symlink" events may be fired, + * depending on the type of properties of the chunk. + */ + pushFromBuffer () { + let stream = this.stream; + let chunk = this.buffer.shift(); + + // Stream the data + try { + this.shouldRead = stream.push(chunk.data); + } + catch (err) { + this.emit('error', err); + } + + // Also emit specific events, based on the type of chunk + chunk.file && this.emit('file', chunk.data); + chunk.symlink && this.emit('symlink', chunk.data); + chunk.directory && this.emit('directory', chunk.data); + } + + /** + * Determines whether the given directory meets the user-specified recursion criteria. + * If the user didn't specify recursion criteria, then this function will default to true. + * + * @param {fs.Stats} stats - The directory's {@link fs.Stats} object + * @param {string} posixPath - The item's POSIX path (used for glob matching) + * @param {boolean} maxDepthReached - Whether we've already crawled the user-specified depth + * @returns {boolean} + */ + shouldRecurse (stats, posixPath, maxDepthReached) { + let options = this.options; + + if (maxDepthReached) { + // We've already crawled to the maximum depth. So no more recursion. + return false; + } + else if (!stats.isDirectory()) { + // It's not a directory. So don't try to crawl it. + return false; + } + else if (options.recurseGlob) { + // Glob patterns are always tested against the POSIX path, even on Windows + // https://github.com/isaacs/node-glob#windows + return options.recurseGlob.test(posixPath); + } + else if (options.recurseRegExp) { + // Regular expressions are tested against the normal path + // (based on the OS or options.sep) + return options.recurseRegExp.test(stats.path); + } + else if (options.recurseFn) { + try { + // Run the user-specified recursion criteria + return options.recurseFn.call(null, stats); + } + catch (err) { + // An error occurred in the user's code. + // In Sync and Async modes, this will return an error. + // In Streaming mode, we emit an "error" event, but continue processing + this.emit('error', err); + } + } + else { + // No recursion function was specified, and we're within the maximum depth. + // So crawl this directory. + return true; + } + } + + /** + * Determines whether the given item meets the user-specified filter criteria. + * If the user didn't specify a filter, then this function will always return true. + * + * @param {string|fs.Stats} value - Either the item's path, or the item's {@link fs.Stats} object + * @param {string} posixPath - The item's POSIX path (used for glob matching) + * @returns {boolean} + */ + filter (value, posixPath) { + let options = this.options; + + if (options.filterGlob) { + // Glob patterns are always tested against the POSIX path, even on Windows + // https://github.com/isaacs/node-glob#windows + return options.filterGlob.test(posixPath); + } + else if (options.filterRegExp) { + // Regular expressions are tested against the normal path + // (based on the OS or options.sep) + return options.filterRegExp.test(value.path || value); + } + else if (options.filterFn) { + try { + // Run the user-specified filter function + return options.filterFn.call(null, value); + } + catch (err) { + // An error occurred in the user's code. + // In Sync and Async modes, this will return an error. + // In Streaming mode, we emit an "error" event, but continue processing + this.emit('error', err); + } + } + else { + // No filter was specified, so match everything + return true; + } + } + + /** + * Emits an event. If one of the event listeners throws an error, + * then an "error" event is emitted. + * + * @param {string} eventName + * @param {*} data + */ + emit (eventName, data) { + let stream = this.stream; + + try { + stream.emit(eventName, data); + } + catch (err) { + if (eventName === 'error') { + // Don't recursively emit "error" events. + // If the first one fails, then just throw + throw err; + } + else { + stream.emit('error', err); + } + } + } +} + +module.exports = DirectoryReader; + + +/***/ }), +/* 110 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +let call = module.exports = { + safe: safeCall, + once: callOnce, +}; + +/** + * Calls a function with the given arguments, and ensures that the error-first callback is _always_ + * invoked exactly once, even if the function throws an error. + * + * @param {function} fn - The function to invoke + * @param {...*} args - The arguments to pass to the function. The final argument must be a callback function. + */ +function safeCall (fn, args) { + // Get the function arguments as an array + args = Array.prototype.slice.call(arguments, 1); + + // Replace the callback function with a wrapper that ensures it will only be called once + let callback = call.once(args.pop()); + args.push(callback); + + try { + fn.apply(null, args); + } + catch (err) { + callback(err); + } +} + +/** + * Returns a wrapper function that ensures the given callback function is only called once. + * Subsequent calls are ignored, unless the first argument is an Error, in which case the + * error is thrown. + * + * @param {function} fn - The function that should only be called once + * @returns {function} + */ +function callOnce (fn) { + let fulfilled = false; + + return function onceWrapper (err) { + if (!fulfilled) { + fulfilled = true; + return fn.apply(this, arguments); + } + else if (err) { + // The callback has already been called, but now an error has occurred + // (most likely inside the callback function). So re-throw the error, + // so it gets handled further up the call stack + throw err; + } + }; +} + + +/***/ }), +/* 111 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var path = __webpack_require__(5); +var deep_1 = __webpack_require__(443); +var entry_1 = __webpack_require__(445); +var Reader = /** @class */ (function () { + function Reader(options) { + this.options = options; + this.micromatchOptions = this.getMicromatchOptions(); + this.entryFilter = new entry_1.default(options, this.micromatchOptions); + this.deepFilter = new deep_1.default(options, this.micromatchOptions); + } + /** + * Returns root path to scanner. + */ + Reader.prototype.getRootDirectory = function (task) { + return path.resolve(this.options.cwd, task.base); + }; + /** + * Returns options for reader. + */ + Reader.prototype.getReaderOptions = function (task) { + return { + basePath: task.base === '.' ? '' : task.base, + filter: this.entryFilter.getFilter(task.positive, task.negative), + deep: this.deepFilter.getFilter(task.positive, task.negative), + sep: '/' + }; + }; + /** + * Returns options for micromatch. + */ + Reader.prototype.getMicromatchOptions = function () { + return { + dot: this.options.dot, + nobrace: this.options.nobrace, + noglobstar: this.options.noglobstar, + noext: this.options.noext, + nocase: this.options.nocase, + matchBase: this.options.matchBase + }; + }; + /** + * Returns transformed entry. + */ + Reader.prototype.transform = function (entry) { + if (this.options.markDirectories && entry.isDirectory()) { + entry.path += '/'; + } + if (this.options.absolute && !path.isAbsolute(entry.path)) { + entry.path = path.resolve(this.options.cwd, entry.path); + } + var item = this.options.stats ? entry : entry.path; + if (this.options.transform === null) { + return item; + } + return this.options.transform(item); + }; + /** + * Returns true if error has ENOENT code. + */ + Reader.prototype.isEnoentCodeError = function (err) { + return err.code === 'ENOENT'; + }; + return Reader; +}()); +exports.default = Reader; + + +/***/ }), +/* 112 */ +/***/ (function(module, exports) { + +module.exports = function(module) { + if (!module.webpackPolyfill) { + module.deprecate = function() {}; + module.paths = []; + // module.parent = undefined by default + if (!module.children) module.children = []; + Object.defineProperty(module, "loaded", { + enumerable: true, + get: function() { + return module.l; + } + }); + Object.defineProperty(module, "id", { + enumerable: true, + get: function() { + return module.i; + } + }); + module.webpackPolyfill = 1; + } + return module; +}; + + +/***/ }), +/* 113 */ +/***/ (function(module, exports, __webpack_require__) { + +/* MIT license */ +var cssKeywords = __webpack_require__(166); + +// NOTE: conversions should only return primitive values (i.e. arrays, or +// values that give correct `typeof` results). +// do not use box values types (i.e. Number(), String(), etc.) + +var reverseKeywords = {}; +for (var key in cssKeywords) { + if (cssKeywords.hasOwnProperty(key)) { + reverseKeywords[cssKeywords[key]] = key; + } +} + +var convert = module.exports = { + rgb: {channels: 3, labels: 'rgb'}, + hsl: {channels: 3, labels: 'hsl'}, + hsv: {channels: 3, labels: 'hsv'}, + hwb: {channels: 3, labels: 'hwb'}, + cmyk: {channels: 4, labels: 'cmyk'}, + xyz: {channels: 3, labels: 'xyz'}, + lab: {channels: 3, labels: 'lab'}, + lch: {channels: 3, labels: 'lch'}, + hex: {channels: 1, labels: ['hex']}, + keyword: {channels: 1, labels: ['keyword']}, + ansi16: {channels: 1, labels: ['ansi16']}, + ansi256: {channels: 1, labels: ['ansi256']}, + hcg: {channels: 3, labels: ['h', 'c', 'g']}, + apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, + gray: {channels: 1, labels: ['gray']} +}; + +// hide .channels and .labels properties +for (var model in convert) { + if (convert.hasOwnProperty(model)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + var channels = convert[model].channels; + var labels = convert[model].labels; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', {value: channels}); + Object.defineProperty(convert[model], 'labels', {value: labels}); + } +} + +convert.rgb.hsl = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var l; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + l = (min + max) / 2; + + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + + return [h, s * 100, l * 100]; +}; + +convert.rgb.hsv = function (rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var v; + + if (max === 0) { + s = 0; + } else { + s = (delta / max * 1000) / 10; + } + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + v = ((max / 255) * 1000) / 10; + + return [h, s, v]; +}; + +convert.rgb.hwb = function (rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var h = convert.rgb.hsl(rgb)[0]; + var w = 1 / 255 * Math.min(r, Math.min(g, b)); + + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + + return [h, w * 100, b * 100]; +}; + +convert.rgb.cmyk = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var c; + var m; + var y; + var k; + + k = Math.min(1 - r, 1 - g, 1 - b); + c = (1 - r - k) / (1 - k) || 0; + m = (1 - g - k) / (1 - k) || 0; + y = (1 - b - k) / (1 - k) || 0; + + return [c * 100, m * 100, y * 100, k * 100]; +}; + +/** + * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + * */ +function comparativeDistance(x, y) { + return ( + Math.pow(x[0] - y[0], 2) + + Math.pow(x[1] - y[1], 2) + + Math.pow(x[2] - y[2], 2) + ); +} + +convert.rgb.keyword = function (rgb) { + var reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + + var currentClosestDistance = Infinity; + var currentClosestKeyword; + + for (var keyword in cssKeywords) { + if (cssKeywords.hasOwnProperty(keyword)) { + var value = cssKeywords[keyword]; + + // Compute comparative distance + var distance = comparativeDistance(rgb, value); + + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + } + + return currentClosestKeyword; +}; + +convert.keyword.rgb = function (keyword) { + return cssKeywords[keyword]; +}; + +convert.rgb.xyz = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + + // assume sRGB + r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); + g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); + b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); + + var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); + + return [x * 100, y * 100, z * 100]; +}; + +convert.rgb.lab = function (rgb) { + var xyz = convert.rgb.xyz(rgb); + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; +}; + +convert.hsl.rgb = function (hsl) { + var h = hsl[0] / 360; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var t1; + var t2; + var t3; + var rgb; + var val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } t1 = 2 * l - t2; @@ -8322,28 +10806,19 @@ convert.rgb.gray = function (rgb) { /***/ }), -/* 93 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -module.exports = (flag, argv) => { - argv = argv || process.argv; - const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); - const pos = argv.indexOf(prefix + flag); - const terminatorPos = argv.indexOf('--'); - return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); -}; +/* 114 */ +/***/ (function(module, exports) { +module.exports = require("os"); /***/ }), -/* 94 */ +/* 115 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var fs = __webpack_require__(16) +var fs = __webpack_require__(13) module.exports = clone(fs) @@ -8365,11 +10840,11 @@ function clone (obj) { /***/ }), -/* 95 */ +/* 116 */ /***/ (function(module, exports, __webpack_require__) { -var path = __webpack_require__(7); -var fs = __webpack_require__(16); +var path = __webpack_require__(5); +var fs = __webpack_require__(13); var _0777 = parseInt('0777', 8); module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; @@ -8469,7 +10944,7 @@ mkdirP.sync = function sync (p, opts, made) { /***/ }), -/* 96 */ +/* 117 */ /***/ (function(module, exports, __webpack_require__) { module.exports = realpath @@ -8479,13 +10954,13 @@ realpath.realpathSync = realpathSync realpath.monkeypatch = monkeypatch realpath.unmonkeypatch = unmonkeypatch -var fs = __webpack_require__(16) +var fs = __webpack_require__(13) var origRealpath = fs.realpath var origRealpathSync = fs.realpathSync var version = process.version var ok = /^v[0-5]\./.test(version) -var old = __webpack_require__(136) +var old = __webpack_require__(181) function newError (er) { return er && er.syscall === 'realpath' && ( @@ -8541,20 +11016,20 @@ function unmonkeypatch () { /***/ }), -/* 97 */ +/* 118 */ /***/ (function(module, exports, __webpack_require__) { try { - var util = __webpack_require__(19); + var util = __webpack_require__(14); if (typeof util.inherits !== 'function') throw ''; module.exports = util.inherits; } catch (e) { - module.exports = __webpack_require__(140); + module.exports = __webpack_require__(185); } /***/ }), -/* 98 */ +/* 119 */ /***/ (function(module, exports, __webpack_require__) { exports.alphasort = alphasort @@ -8571,9 +11046,9 @@ function ownProp (obj, field) { return Object.prototype.hasOwnProperty.call(obj, field) } -var path = __webpack_require__(7) -var minimatch = __webpack_require__(86) -var isAbsolute = __webpack_require__(87) +var path = __webpack_require__(5) +var minimatch = __webpack_require__(99) +var isAbsolute = __webpack_require__(100) var Minimatch = minimatch.Minimatch function alphasorti (a, b) { @@ -8800,7 +11275,7 @@ function childrenIgnored (self, path) { /***/ }), -/* 99 */ +/* 120 */ /***/ (function(module, exports) { // Returns a wrapper function that returns a wrapped callback @@ -8839,55 +11314,7 @@ function wrappy (fn, cb) { /***/ }), -/* 100 */ -/***/ (function(module, exports, __webpack_require__) { - -var wrappy = __webpack_require__(99) -module.exports = wrappy(once) -module.exports.strict = wrappy(onceStrict) - -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }) - - Object.defineProperty(Function.prototype, 'onceStrict', { - value: function () { - return onceStrict(this) - }, - configurable: true - }) -}) - -function once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true - return f.value = fn.apply(this, arguments) - } - f.called = false - return f -} - -function onceStrict (fn) { - var f = function () { - if (f.called) - throw new Error(f.onceError) - f.called = true - return f.value = fn.apply(this, arguments) - } - var name = fn.name || 'Function wrapped with `once`' - f.onceError = name + " shouldn't be called more than once" - f.called = false - return f -} - - -/***/ }), -/* 101 */ +/* 121 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -8918,21 +11345,21 @@ var _extends = Object.assign || function (target) { for (var i = 1; i < argument */ -var _chalk = __webpack_require__(30); +var _chalk = __webpack_require__(26); var _chalk2 = _interopRequireDefault(_chalk); -var _path = __webpack_require__(7); +var _path = __webpack_require__(5); -var _util = __webpack_require__(19); +var _util = __webpack_require__(14); -var _errors = __webpack_require__(88); +var _errors = __webpack_require__(101); -var _log = __webpack_require__(36); +var _log = __webpack_require__(40); -var _package_json = __webpack_require__(62); +var _package_json = __webpack_require__(72); -var _scripts = __webpack_require__(173); +var _scripts = __webpack_require__(221); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -9058,15 +11485,64 @@ function normalizePath(path) { } /***/ }), -/* 102 */ +/* 122 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const fs = __webpack_require__(13); +const pify = __webpack_require__(196); + +function type(fn, fn2, fp) { + if (typeof fp !== 'string') { + return Promise.reject(new TypeError(`Expected a string, got ${typeof fp}`)); + } + + return pify(fs[fn])(fp) + .then(stats => stats[fn2]()) + .catch(err => { + if (err.code === 'ENOENT') { + return false; + } + + throw err; + }); +} + +function typeSync(fn, fn2, fp) { + if (typeof fp !== 'string') { + throw new TypeError(`Expected a string, got ${typeof fp}`); + } + + try { + return fs[fn](fp)[fn2](); + } catch (err) { + if (err.code === 'ENOENT') { + return false; + } + + throw err; + } +} + +exports.file = type.bind(null, 'stat', 'isFile'); +exports.dir = type.bind(null, 'stat', 'isDirectory'); +exports.symlink = type.bind(null, 'lstat', 'isSymbolicLink'); +exports.fileSync = typeSync.bind(null, 'statSync', 'isFile'); +exports.dirSync = typeSync.bind(null, 'statSync', 'isDirectory'); +exports.symlinkSync = typeSync.bind(null, 'lstatSync', 'isSymbolicLink'); + + +/***/ }), +/* 123 */ /***/ (function(module, exports, __webpack_require__) { module.exports = normalize -var fixer = __webpack_require__(151) +var fixer = __webpack_require__(197) normalize.fixer = fixer -var makeWarning = __webpack_require__(164) +var makeWarning = __webpack_require__(210) var fieldsToFix = ['name','version','description','repository','modules','scripts' ,'files','bin','man','bugs','keywords','readme','homepage','license'] @@ -9103,13 +11579,7 @@ function ucFirst (string) { /***/ }), -/* 103 */ -/***/ (function(module, exports) { - -module.exports = require("url"); - -/***/ }), -/* 104 */ +/* 124 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -9184,12 +11654,12 @@ Object.keys(gitHosts).forEach(function (name) { /***/ }), -/* 105 */ +/* 125 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const isPlainObj = __webpack_require__(171); +const isPlainObj = __webpack_require__(217); module.exports = (obj, opts) => { if (!isPlainObj(obj)) { @@ -9246,14 +11716,14 @@ module.exports = (obj, opts) => { /***/ }), -/* 106 */ +/* 126 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const fs = __webpack_require__(16); -const path = __webpack_require__(7); -const pify = __webpack_require__(44); +const fs = __webpack_require__(13); +const path = __webpack_require__(5); +const pify = __webpack_require__(218); const defaults = { mode: 0o777 & (~process.umask()), @@ -9338,561 +11808,18 @@ module.exports.sync = (input, opts) => { /***/ }), -/* 107 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var path = __webpack_require__(7); -var which = __webpack_require__(178); -var LRU = __webpack_require__(108); - -var commandCache = new LRU({ max: 50, maxAge: 30 * 1000 }); // Cache just for 30sec - -function resolveCommand(command, noExtension) { - var resolved; - - noExtension = !!noExtension; - resolved = commandCache.get(command + '!' + noExtension); - - // Check if its resolved in the cache - if (commandCache.has(command)) { - return commandCache.get(command); - } - - try { - resolved = !noExtension ? - which.sync(command) : - which.sync(command, { pathExt: path.delimiter + (process.env.PATHEXT || '') }); - } catch (e) { /* empty */ } - - commandCache.set(command + '!' + noExtension, resolved); - - return resolved; -} - -module.exports = resolveCommand; - - -/***/ }), -/* 108 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -module.exports = LRUCache - -// This will be a proper iterable 'Map' in engines that support it, -// or a fakey-fake PseudoMap in older versions. -var Map = __webpack_require__(182) -var util = __webpack_require__(19) - -// A linked list to keep track of recently-used-ness -var Yallist = __webpack_require__(184) - -// use symbols if possible, otherwise just _props -var hasSymbol = typeof Symbol === 'function' -var makeSymbol -if (hasSymbol) { - makeSymbol = function (key) { - return Symbol.for(key) - } -} else { - makeSymbol = function (key) { - return '_' + key - } -} - -var MAX = makeSymbol('max') -var LENGTH = makeSymbol('length') -var LENGTH_CALCULATOR = makeSymbol('lengthCalculator') -var ALLOW_STALE = makeSymbol('allowStale') -var MAX_AGE = makeSymbol('maxAge') -var DISPOSE = makeSymbol('dispose') -var NO_DISPOSE_ON_SET = makeSymbol('noDisposeOnSet') -var LRU_LIST = makeSymbol('lruList') -var CACHE = makeSymbol('cache') - -function naiveLength () { return 1 } - -// lruList is a yallist where the head is the youngest -// item, and the tail is the oldest. the list contains the Hit -// objects as the entries. -// Each Hit object has a reference to its Yallist.Node. This -// never changes. -// -// cache is a Map (or PseudoMap) that matches the keys to -// the Yallist.Node object. -function LRUCache (options) { - if (!(this instanceof LRUCache)) { - return new LRUCache(options) - } - - if (typeof options === 'number') { - options = { max: options } - } - - if (!options) { - options = {} - } - - var max = this[MAX] = options.max - // Kind of weird to have a default max of Infinity, but oh well. - if (!max || - !(typeof max === 'number') || - max <= 0) { - this[MAX] = Infinity - } - - var lc = options.length || naiveLength - if (typeof lc !== 'function') { - lc = naiveLength - } - this[LENGTH_CALCULATOR] = lc - - this[ALLOW_STALE] = options.stale || false - this[MAX_AGE] = options.maxAge || 0 - this[DISPOSE] = options.dispose - this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false - this.reset() -} - -// resize the cache when the max changes. -Object.defineProperty(LRUCache.prototype, 'max', { - set: function (mL) { - if (!mL || !(typeof mL === 'number') || mL <= 0) { - mL = Infinity - } - this[MAX] = mL - trim(this) - }, - get: function () { - return this[MAX] - }, - enumerable: true -}) - -Object.defineProperty(LRUCache.prototype, 'allowStale', { - set: function (allowStale) { - this[ALLOW_STALE] = !!allowStale - }, - get: function () { - return this[ALLOW_STALE] - }, - enumerable: true -}) - -Object.defineProperty(LRUCache.prototype, 'maxAge', { - set: function (mA) { - if (!mA || !(typeof mA === 'number') || mA < 0) { - mA = 0 - } - this[MAX_AGE] = mA - trim(this) - }, - get: function () { - return this[MAX_AGE] - }, - enumerable: true -}) - -// resize the cache when the lengthCalculator changes. -Object.defineProperty(LRUCache.prototype, 'lengthCalculator', { - set: function (lC) { - if (typeof lC !== 'function') { - lC = naiveLength - } - if (lC !== this[LENGTH_CALCULATOR]) { - this[LENGTH_CALCULATOR] = lC - this[LENGTH] = 0 - this[LRU_LIST].forEach(function (hit) { - hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) - this[LENGTH] += hit.length - }, this) - } - trim(this) - }, - get: function () { return this[LENGTH_CALCULATOR] }, - enumerable: true -}) - -Object.defineProperty(LRUCache.prototype, 'length', { - get: function () { return this[LENGTH] }, - enumerable: true -}) - -Object.defineProperty(LRUCache.prototype, 'itemCount', { - get: function () { return this[LRU_LIST].length }, - enumerable: true -}) - -LRUCache.prototype.rforEach = function (fn, thisp) { - thisp = thisp || this - for (var walker = this[LRU_LIST].tail; walker !== null;) { - var prev = walker.prev - forEachStep(this, fn, walker, thisp) - walker = prev - } -} - -function forEachStep (self, fn, node, thisp) { - var hit = node.value - if (isStale(self, hit)) { - del(self, node) - if (!self[ALLOW_STALE]) { - hit = undefined - } - } - if (hit) { - fn.call(thisp, hit.value, hit.key, self) - } -} - -LRUCache.prototype.forEach = function (fn, thisp) { - thisp = thisp || this - for (var walker = this[LRU_LIST].head; walker !== null;) { - var next = walker.next - forEachStep(this, fn, walker, thisp) - walker = next - } -} - -LRUCache.prototype.keys = function () { - return this[LRU_LIST].toArray().map(function (k) { - return k.key - }, this) -} - -LRUCache.prototype.values = function () { - return this[LRU_LIST].toArray().map(function (k) { - return k.value - }, this) -} - -LRUCache.prototype.reset = function () { - if (this[DISPOSE] && - this[LRU_LIST] && - this[LRU_LIST].length) { - this[LRU_LIST].forEach(function (hit) { - this[DISPOSE](hit.key, hit.value) - }, this) - } - - this[CACHE] = new Map() // hash of items by key - this[LRU_LIST] = new Yallist() // list of items in order of use recency - this[LENGTH] = 0 // length of items in the list -} - -LRUCache.prototype.dump = function () { - return this[LRU_LIST].map(function (hit) { - if (!isStale(this, hit)) { - return { - k: hit.key, - v: hit.value, - e: hit.now + (hit.maxAge || 0) - } - } - }, this).toArray().filter(function (h) { - return h - }) -} - -LRUCache.prototype.dumpLru = function () { - return this[LRU_LIST] -} - -LRUCache.prototype.inspect = function (n, opts) { - var str = 'LRUCache {' - var extras = false - - var as = this[ALLOW_STALE] - if (as) { - str += '\n allowStale: true' - extras = true - } - - var max = this[MAX] - if (max && max !== Infinity) { - if (extras) { - str += ',' - } - str += '\n max: ' + util.inspect(max, opts) - extras = true - } - - var maxAge = this[MAX_AGE] - if (maxAge) { - if (extras) { - str += ',' - } - str += '\n maxAge: ' + util.inspect(maxAge, opts) - extras = true - } - - var lc = this[LENGTH_CALCULATOR] - if (lc && lc !== naiveLength) { - if (extras) { - str += ',' - } - str += '\n length: ' + util.inspect(this[LENGTH], opts) - extras = true - } - - var didFirst = false - this[LRU_LIST].forEach(function (item) { - if (didFirst) { - str += ',\n ' - } else { - if (extras) { - str += ',\n' - } - didFirst = true - str += '\n ' - } - var key = util.inspect(item.key).split('\n').join('\n ') - var val = { value: item.value } - if (item.maxAge !== maxAge) { - val.maxAge = item.maxAge - } - if (lc !== naiveLength) { - val.length = item.length - } - if (isStale(this, item)) { - val.stale = true - } - - val = util.inspect(val, opts).split('\n').join('\n ') - str += key + ' => ' + val - }) - - if (didFirst || extras) { - str += '\n' - } - str += '}' - - return str -} - -LRUCache.prototype.set = function (key, value, maxAge) { - maxAge = maxAge || this[MAX_AGE] - - var now = maxAge ? Date.now() : 0 - var len = this[LENGTH_CALCULATOR](value, key) - - if (this[CACHE].has(key)) { - if (len > this[MAX]) { - del(this, this[CACHE].get(key)) - return false - } - - var node = this[CACHE].get(key) - var item = node.value - - // dispose of the old one before overwriting - // split out into 2 ifs for better coverage tracking - if (this[DISPOSE]) { - if (!this[NO_DISPOSE_ON_SET]) { - this[DISPOSE](key, item.value) - } - } - - item.now = now - item.maxAge = maxAge - item.value = value - this[LENGTH] += len - item.length - item.length = len - this.get(key) - trim(this) - return true - } - - var hit = new Entry(key, value, len, now, maxAge) - - // oversized objects fall out of cache automatically. - if (hit.length > this[MAX]) { - if (this[DISPOSE]) { - this[DISPOSE](key, value) - } - return false - } - - this[LENGTH] += hit.length - this[LRU_LIST].unshift(hit) - this[CACHE].set(key, this[LRU_LIST].head) - trim(this) - return true -} - -LRUCache.prototype.has = function (key) { - if (!this[CACHE].has(key)) return false - var hit = this[CACHE].get(key).value - if (isStale(this, hit)) { - return false - } - return true -} - -LRUCache.prototype.get = function (key) { - return get(this, key, true) -} - -LRUCache.prototype.peek = function (key) { - return get(this, key, false) -} - -LRUCache.prototype.pop = function () { - var node = this[LRU_LIST].tail - if (!node) return null - del(this, node) - return node.value -} - -LRUCache.prototype.del = function (key) { - del(this, this[CACHE].get(key)) -} - -LRUCache.prototype.load = function (arr) { - // reset the cache - this.reset() - - var now = Date.now() - // A previous serialized cache has the most recent items first - for (var l = arr.length - 1; l >= 0; l--) { - var hit = arr[l] - var expiresAt = hit.e || 0 - if (expiresAt === 0) { - // the item was created without expiration in a non aged cache - this.set(hit.k, hit.v) - } else { - var maxAge = expiresAt - now - // dont add already expired items - if (maxAge > 0) { - this.set(hit.k, hit.v, maxAge) - } - } - } -} - -LRUCache.prototype.prune = function () { - var self = this - this[CACHE].forEach(function (value, key) { - get(self, key, false) - }) -} - -function get (self, key, doUse) { - var node = self[CACHE].get(key) - if (node) { - var hit = node.value - if (isStale(self, hit)) { - del(self, node) - if (!self[ALLOW_STALE]) hit = undefined - } else { - if (doUse) { - self[LRU_LIST].unshiftNode(node) - } - } - if (hit) hit = hit.value - } - return hit -} - -function isStale (self, hit) { - if (!hit || (!hit.maxAge && !self[MAX_AGE])) { - return false - } - var stale = false - var diff = Date.now() - hit.now - if (hit.maxAge) { - stale = diff > hit.maxAge - } else { - stale = self[MAX_AGE] && (diff > self[MAX_AGE]) - } - return stale -} - -function trim (self) { - if (self[LENGTH] > self[MAX]) { - for (var walker = self[LRU_LIST].tail; - self[LENGTH] > self[MAX] && walker !== null;) { - // We know that we're about to delete this one, and also - // what the next least recently used key will be, so just - // go ahead and set it now. - var prev = walker.prev - del(self, walker) - walker = prev - } - } -} - -function del (self, node) { - if (node) { - var hit = node.value - if (self[DISPOSE]) { - self[DISPOSE](hit.key, hit.value) - } - self[LENGTH] -= hit.length - self[CACHE].delete(hit.key) - self[LRU_LIST].removeNode(node) - } -} - -// classy, since V8 prefers predictable objects. -function Entry (key, value, length, now, maxAge) { - this.key = key - this.value = value - this.length = length - this.now = now - this.maxAge = maxAge || 0 -} - - -/***/ }), -/* 109 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -function escapeArgument(arg, quote) { - // Convert to string - arg = '' + arg; - - // If we are not going to quote the argument, - // escape shell metacharacters, including double and single quotes: - if (!quote) { - arg = arg.replace(/([()%!^<>&|;,"'\s])/g, '^$1'); - } else { - // Sequence of backslashes followed by a double quote: - // double up all the backslashes and escape the double quote - arg = arg.replace(/(\\*)"/g, '$1$1\\"'); - - // Sequence of backslashes followed by the end of the string - // (which will become a double quote later): - // double up all the backslashes - arg = arg.replace(/(\\*)$/, '$1$1'); - - // All other backslashes occur literally - - // Quote the whole thing: - arg = '"' + arg + '"'; - } - - return arg; -} - -module.exports = escapeArgument; +/* 127 */ +/***/ (function(module, exports) { +module.exports = require("child_process"); /***/ }), -/* 110 */ +/* 128 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const chalk = __webpack_require__(201); +const chalk = __webpack_require__(26); const isSupported = process.platform !== 'win32' || process.env.CI || process.env.TERM === 'xterm-256color'; @@ -9914,7 +11841,7 @@ module.exports = isSupported ? main : fallbacks; /***/ }), -/* 111 */ +/* 129 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -9925,13 +11852,13 @@ module.exports = isSupported ? main : fallbacks; -var stream = __webpack_require__(41); -var util = __webpack_require__(19); -var fs = __webpack_require__(16); +var stream = __webpack_require__(39); +var util = __webpack_require__(14); +var fs = __webpack_require__(13); -var byline = __webpack_require__(207); -var through = __webpack_require__(209); -var duplexer = __webpack_require__(210); +var byline = __webpack_require__(251); +var through = __webpack_require__(253); +var duplexer = __webpack_require__(254); module.exports = Logger; @@ -10092,7 +12019,7 @@ function lineMerger(host) { /***/ }), -/* 112 */ +/* 130 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -10165,23 +12092,23 @@ let getWorkspaceProjects = (() => { }; })(); -var _glob = __webpack_require__(43); +var _glob = __webpack_require__(48); var _glob2 = _interopRequireDefault(_glob); -var _path = __webpack_require__(7); +var _path = __webpack_require__(5); var _path2 = _interopRequireDefault(_path); -var _util = __webpack_require__(19); +var _util = __webpack_require__(14); -var _config = __webpack_require__(91); +var _config = __webpack_require__(104); -var _fs = __webpack_require__(60); +var _fs = __webpack_require__(70); -var _package_json = __webpack_require__(62); +var _package_json = __webpack_require__(72); -var _projects = __webpack_require__(42); +var _projects = __webpack_require__(47); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } @@ -10222,18 +12149,18 @@ function packagesFromGlobPattern({ pattern, rootPath }) { } /***/ }), -/* 113 */ +/* 131 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const path = __webpack_require__(7); -const globby = __webpack_require__(215); -const isPathCwd = __webpack_require__(219); -const isPathInCwd = __webpack_require__(220); -const pify = __webpack_require__(44); -const rimraf = __webpack_require__(223); -const pMap = __webpack_require__(224); +const path = __webpack_require__(5); +const globby = __webpack_require__(259); +const isPathCwd = __webpack_require__(265); +const isPathInCwd = __webpack_require__(266); +const pify = __webpack_require__(269); +const rimraf = __webpack_require__(270); +const pMap = __webpack_require__(271); const rimrafP = pify(rimraf); @@ -10299,6434 +12226,10916 @@ module.exports.sync = (patterns, opts) => { /***/ }), -/* 114 */ +/* 132 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +var arrayUniq = __webpack_require__(262); -module.exports = typeof Promise === 'function' ? Promise : __webpack_require__(216); +module.exports = function () { + return arrayUniq([].concat.apply([], arguments)); +}; /***/ }), -/* 115 */ +/* 133 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var arrayUniq = __webpack_require__(217); +module.exports = function (val) { + if (val === null || val === undefined) { + return []; + } -module.exports = function () { - return arrayUniq([].concat.apply([], arguments)); + return Array.isArray(val) ? val : [val]; }; /***/ }), -/* 116 */ +/* 134 */ +/***/ (function(module, exports, __webpack_require__) { + +const pkg = __webpack_require__(296); + +module.exports = pkg.async; +module.exports.default = pkg.async; + +module.exports.async = pkg.async; +module.exports.sync = pkg.sync; +module.exports.stream = pkg.stream; + + +/***/ }), +/* 135 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* -object-assign -(c) Sindre Sorhus -@license MIT -*/ -/* eslint-disable no-unused-vars */ -var getOwnPropertySymbols = Object.getOwnPropertySymbols; -var hasOwnProperty = Object.prototype.hasOwnProperty; -var propIsEnumerable = Object.prototype.propertyIsEnumerable; +var utils = __webpack_require__(75); -function toObject(val) { - if (val === null || val === undefined) { - throw new TypeError('Object.assign cannot be called with null or undefined'); - } +module.exports = function(braces, options) { + braces.compiler - return Object(val); -} + /** + * bos + */ -function shouldUseNative() { - try { - if (!Object.assign) { - return false; - } + .set('bos', function() { + if (this.output) return; + this.ast.queue = isEscaped(this.ast) ? [this.ast.val] : []; + this.ast.count = 1; + }) - // Detect buggy property enumeration order in older V8 versions. + /** + * Square brackets + */ - // https://bugs.chromium.org/p/v8/issues/detail?id=4118 - var test1 = new String('abc'); // eslint-disable-line no-new-wrappers - test1[5] = 'de'; - if (Object.getOwnPropertyNames(test1)[0] === '5') { - return false; - } + .set('bracket', function(node) { + var close = node.close; + var open = !node.escaped ? '[' : '\\['; + var negated = node.negated; + var inner = node.inner; - // https://bugs.chromium.org/p/v8/issues/detail?id=3056 - var test2 = {}; - for (var i = 0; i < 10; i++) { - test2['_' + String.fromCharCode(i)] = i; - } - var order2 = Object.getOwnPropertyNames(test2).map(function (n) { - return test2[n]; - }); - if (order2.join('') !== '0123456789') { - return false; - } + inner = inner.replace(/\\(?=[\\\w]|$)/g, '\\\\'); + if (inner === ']-') { + inner = '\\]\\-'; + } - // https://bugs.chromium.org/p/v8/issues/detail?id=3056 - var test3 = {}; - 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { - test3[letter] = letter; - }); - if (Object.keys(Object.assign({}, test3)).join('') !== - 'abcdefghijklmnopqrst') { - return false; - } + if (negated && inner.indexOf('.') === -1) { + inner += '.'; + } + if (negated && inner.indexOf('/') === -1) { + inner += '/'; + } - return true; - } catch (err) { - // We don't expect any of the above to throw, but better to be safe. - return false; - } -} + var val = open + negated + inner + close; + var queue = node.parent.queue; + var last = utils.arrayify(queue.pop()); -module.exports = shouldUseNative() ? Object.assign : function (target, source) { - var from; - var to = toObject(target); - var symbols; + queue.push(utils.join(last, val)); + queue.push.apply(queue, []); + }) - for (var s = 1; s < arguments.length; s++) { - from = Object(arguments[s]); + /** + * Brace + */ - for (var key in from) { - if (hasOwnProperty.call(from, key)) { - to[key] = from[key]; - } - } + .set('brace', function(node) { + node.queue = isEscaped(node) ? [node.val] : []; + node.count = 1; + return this.mapVisit(node.nodes); + }) - if (getOwnPropertySymbols) { - symbols = getOwnPropertySymbols(from); - for (var i = 0; i < symbols.length; i++) { - if (propIsEnumerable.call(from, symbols[i])) { - to[symbols[i]] = from[symbols[i]]; - } - } - } - } + /** + * Open + */ - return to; -}; + .set('brace.open', function(node) { + node.parent.open = node.val; + }) + /** + * Inner + */ -/***/ }), -/* 117 */ -/***/ (function(module, exports, __webpack_require__) { + .set('text', function(node) { + var queue = node.parent.queue; + var escaped = node.escaped; + var segs = [node.val]; -"use strict"; + if (node.optimize === false) { + options = utils.extend({}, options, {optimize: false}); + } -const NestedError = __webpack_require__(118); + if (node.multiplier > 1) { + node.parent.count *= node.multiplier; + } -class CpFileError extends NestedError { - constructor(message, nested) { - super(message, nested); - Object.assign(this, nested); - this.name = 'CpFileError'; - } -} + if (options.quantifiers === true && utils.isQuantifier(node.val)) { + escaped = true; -module.exports = CpFileError; + } else if (node.val.length > 1) { + if (isType(node.parent, 'brace') && !isEscaped(node)) { + var expanded = utils.expand(node.val, options); + segs = expanded.segs; + if (expanded.isOptimized) { + node.parent.isOptimized = true; + } -/***/ }), -/* 118 */ -/***/ (function(module, exports, __webpack_require__) { + // if nothing was expanded, we probably have a literal brace + if (!segs.length) { + var val = (expanded.val || node.val); + if (options.unescape !== false) { + // unescape unexpanded brace sequence/set separators + val = val.replace(/\\([,.])/g, '$1'); + // strip quotes + val = val.replace(/["'`]/g, ''); + } -var inherits = __webpack_require__(97); + segs = [val]; + escaped = true; + } + } -var NestedError = function (message, nested) { - this.nested = nested; + } else if (node.val === ',') { + if (options.expand) { + node.parent.queue.push(['']); + segs = ['']; + } else { + segs = ['|']; + } + } else { + escaped = true; + } - if (typeof message !== 'undefined') { - Object.defineProperty(this, 'message', { - value: message, - writable: true, - enumerable: false, - configurable: true - }); - } + if (escaped && isType(node.parent, 'brace')) { + if (node.parent.nodes.length <= 4 && node.parent.count === 1) { + node.parent.escaped = true; + } else if (node.parent.length <= 3) { + node.parent.escaped = true; + } + } + + if (!hasQueue(node.parent)) { + node.parent.queue = segs; + return; + } + + var last = utils.arrayify(queue.pop()); + if (node.parent.count > 1 && options.expand) { + last = multiply(last, node.parent.count); + node.parent.count = 1; + } + + queue.push(utils.join(utils.flatten(last), segs.shift())); + queue.push.apply(queue, segs); + }) + + /** + * Close + */ + + .set('brace.close', function(node) { + var queue = node.parent.queue; + var prev = node.parent.parent; + var last = prev.queue.pop(); + var open = node.parent.open; + var close = node.val; + + if (open && close && isOptimized(node, options)) { + open = '('; + close = ')'; + } + + // if a close brace exists, and the previous segment is one character + // don't wrap the result in braces or parens + var ele = utils.last(queue); + if (node.parent.count > 1 && options.expand) { + ele = multiply(queue.pop(), node.parent.count); + node.parent.count = 1; + queue.push(ele); + } + + if (close && typeof ele === 'string' && ele.length === 1) { + open = ''; + close = ''; + } + + if ((isLiteralBrace(node, options) || noInner(node)) && !node.parent.hasEmpty) { + queue.push(utils.join(open, queue.pop() || '')); + queue = utils.flatten(utils.join(queue, close)); + } + + if (typeof last === 'undefined') { + prev.queue = [queue]; + } else { + prev.queue.push(utils.flatten(utils.join(last, queue))); + } + }) + + /** + * eos + */ + + .set('eos', function(node) { + if (this.input) return; + + if (options.optimize !== false) { + this.output = utils.last(utils.flatten(this.ast.queue)); + } else if (Array.isArray(utils.last(this.ast.queue))) { + this.output = utils.flatten(this.ast.queue.pop()); + } else { + this.output = utils.flatten(this.ast.queue); + } + + if (node.parent.count > 1 && options.expand) { + this.output = multiply(this.output, node.parent.count); + } + + this.output = utils.arrayify(this.output); + this.ast.queue = []; + }); - Error.captureStackTrace(this, this.constructor); - var oldStackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack'); - var stackDescriptor = buildStackDescriptor(oldStackDescriptor, nested); - Object.defineProperty(this, 'stack', stackDescriptor); }; -function buildStackDescriptor(oldStackDescriptor, nested) { - if (oldStackDescriptor.get) { - return { - get: function () { - var stack = oldStackDescriptor.get.call(this); - return buildCombinedStacks(stack, this.nested); - } - }; - } else { - var stack = oldStackDescriptor.value; - return { - value: buildCombinedStacks(stack, nested) - }; - } +/** + * Multiply the segments in the current brace level + */ + +function multiply(queue, n, options) { + return utils.flatten(utils.repeat(utils.arrayify(queue), n)); } -function buildCombinedStacks(stack, nested) { - if (nested) { - stack += '\nCaused By: ' + nested.stack; - } - return stack; +/** + * Return true if `node` is escaped + */ + +function isEscaped(node) { + return node.escaped === true; } -inherits(NestedError, Error); -NestedError.prototype.name = 'NestedError'; +/** + * Returns true if regex parens should be used for sets. If the parent `type` + * is not `brace`, then we're on a root node, which means we should never + * expand segments and open/close braces should be `{}` (since this indicates + * a brace is missing from the set) + */ +function isOptimized(node, options) { + if (node.parent.isOptimized) return true; + return isType(node.parent, 'brace') + && !isEscaped(node.parent) + && options.expand !== true; +} -module.exports = NestedError; +/** + * Returns true if the value in `node` should be wrapped in a literal brace. + * @return {Boolean} + */ + +function isLiteralBrace(node, options) { + return isEscaped(node.parent) || options.optimize !== false; +} + +/** + * Returns true if the given `node` does not have an inner value. + * @return {Boolean} + */ + +function noInner(node, type) { + if (node.parent.queue.length === 1) { + return true; + } + var nodes = node.parent.nodes; + return nodes.length === 3 + && isType(nodes[0], 'brace.open') + && !isType(nodes[1], 'text') + && isType(nodes[2], 'brace.close'); +} + +/** + * Returns true if the given `node` is the given `type` + * @return {Boolean} + */ + +function isType(node, type) { + return typeof node !== 'undefined' && node.type === type; +} + +/** + * Returns true if the given `node` has a non-empty queue. + * @return {Boolean} + */ + +function hasQueue(node) { + return Array.isArray(node.queue) && node.queue.length; +} /***/ }), -/* 119 */ +/* 136 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/*! + * split-string + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ -Object.defineProperty(exports, "__esModule", { - value: true -}); -var _cli = __webpack_require__(120); +var extend = __webpack_require__(320); -Object.defineProperty(exports, 'run', { - enumerable: true, - get: function () { - return _cli.run; +module.exports = function(str, options, fn) { + if (typeof str !== 'string') { + throw new TypeError('expected a string'); } -}); - -var _production = __webpack_require__(249); -Object.defineProperty(exports, 'buildProductionProjects', { - enumerable: true, - get: function () { - return _production.buildProductionProjects; - } -}); -Object.defineProperty(exports, 'prepareExternalProjectDependencies', { - enumerable: true, - get: function () { - return _production.prepareExternalProjectDependencies; + if (typeof options === 'function') { + fn = options; + options = null; } -}); -var _workspaces = __webpack_require__(112); - -Object.defineProperty(exports, 'copyWorkspacePackages', { - enumerable: true, - get: function () { - return _workspaces.copyWorkspacePackages; + // allow separator to be defined as a string + if (typeof options === 'string') { + options = { sep: options }; } -}); - -/***/ }), -/* 120 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + var opts = extend({sep: '.'}, options); + var quotes = opts.quotes || ['"', "'", '`']; + var brackets; + if (opts.brackets === true) { + brackets = { + '<': '>', + '(': ')', + '[': ']', + '{': '}' + }; + } else if (opts.brackets) { + brackets = opts.brackets; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.run = undefined; + var tokens = []; + var stack = []; + var arr = ['']; + var sep = opts.sep; + var len = str.length; + var idx = -1; + var closeIdx; -let run = exports.run = (() => { - var _ref = _asyncToGenerator(function* (argv) { - // We can simplify this setup (and remove this extra handling) once Yarn - // starts forwarding the `--` directly to this script, see - // https://github.com/yarnpkg/yarn/blob/b2d3e1a8fe45ef376b716d597cc79b38702a9320/src/cli/index.js#L174-L182 - if (argv.includes('--')) { - _log.log.write(_chalk2.default.red(`Using "--" is not allowed, as it doesn't work with 'yarn kbn'.`)); - process.exit(1); - } - const options = (0, _getopts2.default)(argv, { - alias: { - e: 'exclude', - h: 'help', - i: 'include' - }, - boolean: ['prefer-offline', 'frozen-lockfile'] - }); - const args = options._; - if (options.help || args.length === 0) { - help(); - return; - } - // This `rootPath` is relative to `./dist/` as that's the location of the - // built version of this tool. - const rootPath = (0, _path.resolve)(__dirname, '../../../'); - const commandName = args[0]; - const extraArgs = args.slice(1); - const commandOptions = { options, extraArgs, rootPath }; - const command = _commands.commands[commandName]; - if (command === undefined) { - _log.log.write(_chalk2.default.red(`[${commandName}] is not a valid command, see 'kbn --help'`)); - process.exit(1); - } - yield (0, _run.runCommand)(command, commandOptions); - }); + function expected() { + if (brackets && stack.length) { + return brackets[stack[stack.length - 1]]; + } + } - return function run(_x) { - return _ref.apply(this, arguments); - }; -})(); + while (++idx < len) { + var ch = str[idx]; + var next = str[idx + 1]; + var tok = { val: ch, idx: idx, arr: arr, str: str }; + tokens.push(tok); -var _chalk = __webpack_require__(30); + if (ch === '\\') { + tok.val = keepEscaping(opts, str, idx) === true ? (ch + next) : next; + tok.escaped = true; + if (typeof fn === 'function') { + fn(tok); + } + arr[arr.length - 1] += tok.val; + idx++; + continue; + } -var _chalk2 = _interopRequireDefault(_chalk); + if (brackets && brackets[ch]) { + stack.push(ch); + var e = expected(); + var i = idx + 1; -var _dedent = __webpack_require__(126); + if (str.indexOf(e, i + 1) !== -1) { + while (stack.length && i < len) { + var s = str[++i]; + if (s === '\\') { + s++; + continue; + } -var _dedent2 = _interopRequireDefault(_dedent); + if (quotes.indexOf(s) !== -1) { + i = getClosingQuote(str, s, i + 1); + continue; + } -var _getopts = __webpack_require__(127); + e = expected(); + if (stack.length && str.indexOf(e, i + 1) === -1) { + break; + } -var _getopts2 = _interopRequireDefault(_getopts); + if (brackets[s]) { + stack.push(s); + continue; + } -var _path = __webpack_require__(7); + if (e === s) { + stack.pop(); + } + } + } -var _commands = __webpack_require__(128); + closeIdx = i; + if (closeIdx === -1) { + arr[arr.length - 1] += ch; + continue; + } -var _run = __webpack_require__(239); + ch = str.slice(idx, closeIdx + 1); + tok.val = ch; + tok.idx = idx = closeIdx; + } -var _log = __webpack_require__(36); + if (quotes.indexOf(ch) !== -1) { + closeIdx = getClosingQuote(str, ch, idx + 1); + if (closeIdx === -1) { + arr[arr.length - 1] += ch; + continue; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (keepQuotes(ch, opts) === true) { + ch = str.slice(idx, closeIdx + 1); + } else { + ch = str.slice(idx + 1, closeIdx); + } -function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ + tok.val = ch; + tok.idx = idx = closeIdx; + } + if (typeof fn === 'function') { + fn(tok, tokens); + ch = tok.val; + idx = tok.idx; + } -function help() { - const availableCommands = Object.keys(_commands.commands).map(commandName => _commands.commands[commandName]).map(command => `${command.name} - ${command.description}`); - _log.log.write(_dedent2.default` - usage: kbn [] + if (tok.val === sep && tok.split !== false) { + arr.push(''); + continue; + } - By default commands are run for Kibana itself, all packages in the 'packages/' - folder and for all plugins in '../kibana-extra'. + arr[arr.length - 1] += tok.val; + } - Available commands: + return arr; +}; - ${availableCommands.join('\n ')} +function getClosingQuote(str, ch, i, brackets) { + var idx = str.indexOf(ch, i); + if (str.charAt(idx - 1) === '\\') { + return getClosingQuote(str, ch, idx + 1); + } + return idx; +} - Global options: +function keepQuotes(ch, opts) { + if (opts.keepDoubleQuotes === true && ch === '"') return true; + if (opts.keepSingleQuotes === true && ch === "'") return true; + return opts.keepQuotes; +} - -e, --exclude Exclude specified project. Can be specified multiple times to exclude multiple projects, e.g. '-e kibana -e @kbn/pm'. - -i, --include Include only specified projects. If left unspecified, it defaults to including all projects. - --oss Do not include the x-pack when running command. - --skip-kibana-extra Filter all plugins in ../kibana-extra when running command. - `); +function keepEscaping(opts, str, idx) { + if (typeof opts.keepEscaping === 'function') { + return opts.keepEscaping(str, idx); + } + return opts.keepEscaping === true || str[idx + 1] === '\\'; } + /***/ }), -/* 121 */ +/* 137 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* WEBPACK VAR INJECTION */(function(module) { -const colorConvert = __webpack_require__(83); +/*! + * repeat-string + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ -const wrapAnsi16 = (fn, offset) => function () { - const code = fn.apply(colorConvert, arguments); - return `\u001B[${code + offset}m`; -}; -const wrapAnsi256 = (fn, offset) => function () { - const code = fn.apply(colorConvert, arguments); - return `\u001B[${38 + offset};5;${code}m`; -}; -const wrapAnsi16m = (fn, offset) => function () { - const rgb = fn.apply(colorConvert, arguments); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; -}; +/** + * Results cache + */ -function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39], +var res = ''; +var cache; - // Bright color - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], +/** + * Expose `repeat` + */ - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; +module.exports = repeat; - // Fix humans - styles.color.grey = styles.color.gray; +/** + * Repeat the given `string` the specified `number` + * of times. + * + * **Example:** + * + * ```js + * var repeat = require('repeat-string'); + * repeat('A', 5); + * //=> AAAAA + * ``` + * + * @param {String} `string` The string to repeat + * @param {Number} `number` The number of times to repeat the string + * @return {String} Repeated string + * @api public + */ - for (const groupName of Object.keys(styles)) { - const group = styles[groupName]; +function repeat(str, num) { + if (typeof str !== 'string') { + throw new TypeError('expected a string'); + } - for (const styleName of Object.keys(group)) { - const style = group[styleName]; + // cover common, quick use cases + if (num === 1) return str; + if (num === 2) return str + str; - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; + var max = str.length * num; + if (cache !== str || typeof cache === 'undefined') { + cache = str; + res = ''; + } else if (res.length >= max) { + return res.substr(0, max); + } - group[styleName] = styles[styleName]; + while (max > res.length && num > 1) { + if (num & 1) { + res += str; + } - codes.set(style[0], style[1]); - } + num >>= 1; + str += str; + } - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); + res += str; + res = res.substr(0, max); + return res; +} - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); - } - const ansi2ansi = n => n; - const rgb2rgb = (r, g, b) => [r, g, b]; +/***/ }), +/* 138 */ +/***/ (function(module, exports, __webpack_require__) { - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; +"use strict"; - styles.color.ansi = { - ansi: wrapAnsi16(ansi2ansi, 0) - }; - styles.color.ansi256 = { - ansi256: wrapAnsi256(ansi2ansi, 0) - }; - styles.color.ansi16m = { - rgb: wrapAnsi16m(rgb2rgb, 0) - }; - - styles.bgColor.ansi = { - ansi: wrapAnsi16(ansi2ansi, 10) - }; - styles.bgColor.ansi256 = { - ansi256: wrapAnsi256(ansi2ansi, 10) - }; - styles.bgColor.ansi16m = { - rgb: wrapAnsi16m(rgb2rgb, 10) - }; - for (let key of Object.keys(colorConvert)) { - if (typeof colorConvert[key] !== 'object') { - continue; - } +var Node = __webpack_require__(327); +var utils = __webpack_require__(75); - const suite = colorConvert[key]; +/** + * Braces parsers + */ - if (key === 'ansi16') { - key = 'ansi'; - } +module.exports = function(braces, options) { + braces.parser + .set('bos', function() { + if (!this.parsed) { + this.ast = this.nodes[0] = new Node(this.ast); + } + }) - if ('ansi16' in suite) { - styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); - styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); - } + /** + * Character parsers + */ - if ('ansi256' in suite) { - styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); - styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); - } + .set('escape', function() { + var pos = this.position(); + var m = this.match(/^(?:\\(.)|\$\{)/); + if (!m) return; - if ('rgb' in suite) { - styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); - styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); - } - } + var prev = this.prev(); + var last = utils.last(prev.nodes); - return styles; -} + var node = pos(new Node({ + type: 'text', + multiplier: 1, + val: m[0] + })); -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); + if (node.val === '\\\\') { + return node; + } -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(59)(module))) + if (node.val === '${') { + var str = this.input; + var idx = -1; + var ch; -/***/ }), -/* 122 */ -/***/ (function(module, exports, __webpack_require__) { + while ((ch = str[++idx])) { + this.consume(1); + node.val += ch; + if (ch === '\\') { + node.val += str[++idx]; + continue; + } + if (ch === '}') { + break; + } + } + } -"use strict"; - - -module.exports = { - "aliceblue": [240, 248, 255], - "antiquewhite": [250, 235, 215], - "aqua": [0, 255, 255], - "aquamarine": [127, 255, 212], - "azure": [240, 255, 255], - "beige": [245, 245, 220], - "bisque": [255, 228, 196], - "black": [0, 0, 0], - "blanchedalmond": [255, 235, 205], - "blue": [0, 0, 255], - "blueviolet": [138, 43, 226], - "brown": [165, 42, 42], - "burlywood": [222, 184, 135], - "cadetblue": [95, 158, 160], - "chartreuse": [127, 255, 0], - "chocolate": [210, 105, 30], - "coral": [255, 127, 80], - "cornflowerblue": [100, 149, 237], - "cornsilk": [255, 248, 220], - "crimson": [220, 20, 60], - "cyan": [0, 255, 255], - "darkblue": [0, 0, 139], - "darkcyan": [0, 139, 139], - "darkgoldenrod": [184, 134, 11], - "darkgray": [169, 169, 169], - "darkgreen": [0, 100, 0], - "darkgrey": [169, 169, 169], - "darkkhaki": [189, 183, 107], - "darkmagenta": [139, 0, 139], - "darkolivegreen": [85, 107, 47], - "darkorange": [255, 140, 0], - "darkorchid": [153, 50, 204], - "darkred": [139, 0, 0], - "darksalmon": [233, 150, 122], - "darkseagreen": [143, 188, 143], - "darkslateblue": [72, 61, 139], - "darkslategray": [47, 79, 79], - "darkslategrey": [47, 79, 79], - "darkturquoise": [0, 206, 209], - "darkviolet": [148, 0, 211], - "deeppink": [255, 20, 147], - "deepskyblue": [0, 191, 255], - "dimgray": [105, 105, 105], - "dimgrey": [105, 105, 105], - "dodgerblue": [30, 144, 255], - "firebrick": [178, 34, 34], - "floralwhite": [255, 250, 240], - "forestgreen": [34, 139, 34], - "fuchsia": [255, 0, 255], - "gainsboro": [220, 220, 220], - "ghostwhite": [248, 248, 255], - "gold": [255, 215, 0], - "goldenrod": [218, 165, 32], - "gray": [128, 128, 128], - "green": [0, 128, 0], - "greenyellow": [173, 255, 47], - "grey": [128, 128, 128], - "honeydew": [240, 255, 240], - "hotpink": [255, 105, 180], - "indianred": [205, 92, 92], - "indigo": [75, 0, 130], - "ivory": [255, 255, 240], - "khaki": [240, 230, 140], - "lavender": [230, 230, 250], - "lavenderblush": [255, 240, 245], - "lawngreen": [124, 252, 0], - "lemonchiffon": [255, 250, 205], - "lightblue": [173, 216, 230], - "lightcoral": [240, 128, 128], - "lightcyan": [224, 255, 255], - "lightgoldenrodyellow": [250, 250, 210], - "lightgray": [211, 211, 211], - "lightgreen": [144, 238, 144], - "lightgrey": [211, 211, 211], - "lightpink": [255, 182, 193], - "lightsalmon": [255, 160, 122], - "lightseagreen": [32, 178, 170], - "lightskyblue": [135, 206, 250], - "lightslategray": [119, 136, 153], - "lightslategrey": [119, 136, 153], - "lightsteelblue": [176, 196, 222], - "lightyellow": [255, 255, 224], - "lime": [0, 255, 0], - "limegreen": [50, 205, 50], - "linen": [250, 240, 230], - "magenta": [255, 0, 255], - "maroon": [128, 0, 0], - "mediumaquamarine": [102, 205, 170], - "mediumblue": [0, 0, 205], - "mediumorchid": [186, 85, 211], - "mediumpurple": [147, 112, 219], - "mediumseagreen": [60, 179, 113], - "mediumslateblue": [123, 104, 238], - "mediumspringgreen": [0, 250, 154], - "mediumturquoise": [72, 209, 204], - "mediumvioletred": [199, 21, 133], - "midnightblue": [25, 25, 112], - "mintcream": [245, 255, 250], - "mistyrose": [255, 228, 225], - "moccasin": [255, 228, 181], - "navajowhite": [255, 222, 173], - "navy": [0, 0, 128], - "oldlace": [253, 245, 230], - "olive": [128, 128, 0], - "olivedrab": [107, 142, 35], - "orange": [255, 165, 0], - "orangered": [255, 69, 0], - "orchid": [218, 112, 214], - "palegoldenrod": [238, 232, 170], - "palegreen": [152, 251, 152], - "paleturquoise": [175, 238, 238], - "palevioletred": [219, 112, 147], - "papayawhip": [255, 239, 213], - "peachpuff": [255, 218, 185], - "peru": [205, 133, 63], - "pink": [255, 192, 203], - "plum": [221, 160, 221], - "powderblue": [176, 224, 230], - "purple": [128, 0, 128], - "rebeccapurple": [102, 51, 153], - "red": [255, 0, 0], - "rosybrown": [188, 143, 143], - "royalblue": [65, 105, 225], - "saddlebrown": [139, 69, 19], - "salmon": [250, 128, 114], - "sandybrown": [244, 164, 96], - "seagreen": [46, 139, 87], - "seashell": [255, 245, 238], - "sienna": [160, 82, 45], - "silver": [192, 192, 192], - "skyblue": [135, 206, 235], - "slateblue": [106, 90, 205], - "slategray": [112, 128, 144], - "slategrey": [112, 128, 144], - "snow": [255, 250, 250], - "springgreen": [0, 255, 127], - "steelblue": [70, 130, 180], - "tan": [210, 180, 140], - "teal": [0, 128, 128], - "thistle": [216, 191, 216], - "tomato": [255, 99, 71], - "turquoise": [64, 224, 208], - "violet": [238, 130, 238], - "wheat": [245, 222, 179], - "white": [255, 255, 255], - "whitesmoke": [245, 245, 245], - "yellow": [255, 255, 0], - "yellowgreen": [154, 205, 50] -}; + if (this.options.unescape !== false) { + node.val = node.val.replace(/\\([{}])/g, '$1'); + } + if (last.val === '"' && this.input.charAt(0) === '"') { + last.val = node.val; + this.consume(1); + return; + } -/***/ }), -/* 123 */ -/***/ (function(module, exports, __webpack_require__) { + return concatNodes.call(this, pos, node, prev, options); + }) -var conversions = __webpack_require__(92); + /** + * Brackets: "[...]" (basic, this is overridden by + * other parsers in more advanced implementations) + */ -/* - this function routes a model to all other models. + .set('bracket', function() { + var isInside = this.isInside('brace'); + var pos = this.position(); + var m = this.match(/^(?:\[([!^]?)([^\]]{2,}|\]\-)(\]|[^*+?]+)|\[)/); + if (!m) return; + + var prev = this.prev(); + var val = m[0]; + var negated = m[1] ? '^' : ''; + var inner = m[2] || ''; + var close = m[3] || ''; + + if (isInside && prev.type === 'brace') { + prev.text = prev.text || ''; + prev.text += val; + } - all functions that are routed have a property `.conversion` attached - to the returned synthetic function. This property is an array - of strings, each with the steps in between the 'from' and 'to' - color models (inclusive). + var esc = this.input.slice(0, 2); + if (inner === '' && esc === '\\]') { + inner += esc; + this.consume(2); - conversions that are not possible simply are not included. -*/ + var str = this.input; + var idx = -1; + var ch; -function buildGraph() { - var graph = {}; - // https://jsperf.com/object-keys-vs-for-in-with-closure/3 - var models = Object.keys(conversions); + while ((ch = str[++idx])) { + this.consume(1); + if (ch === ']') { + close = ch; + break; + } + inner += ch; + } + } - for (var len = models.length, i = 0; i < len; i++) { - graph[models[i]] = { - // http://jsperf.com/1-vs-infinity - // micro-opt, but this is simple. - distance: -1, - parent: null - }; - } + return pos(new Node({ + type: 'bracket', + val: val, + escaped: close !== ']', + negated: negated, + inner: inner, + close: close + })); + }) - return graph; -} + /** + * Empty braces (we capture these early to + * speed up processing in the compiler) + */ -// https://en.wikipedia.org/wiki/Breadth-first_search -function deriveBFS(fromModel) { - var graph = buildGraph(); - var queue = [fromModel]; // unshift -> queue -> pop + .set('multiplier', function() { + var isInside = this.isInside('brace'); + var pos = this.position(); + var m = this.match(/^\{(,+(?:(\{,+\})*),*|,*(?:(\{,+\})*),+)\}/); + if (!m) return; - graph[fromModel].distance = 0; + this.multiplier = true; + var prev = this.prev(); + var val = m[0]; - while (queue.length) { - var current = queue.pop(); - var adjacents = Object.keys(conversions[current]); + if (isInside && prev.type === 'brace') { + prev.text = prev.text || ''; + prev.text += val; + } - for (var len = adjacents.length, i = 0; i < len; i++) { - var adjacent = adjacents[i]; - var node = graph[adjacent]; + var node = pos(new Node({ + type: 'text', + multiplier: 1, + match: m, + val: val + })); - if (node.distance === -1) { - node.distance = graph[current].distance + 1; - node.parent = current; - queue.unshift(adjacent); - } - } - } + return concatNodes.call(this, pos, node, prev, options); + }) - return graph; -} + /** + * Open + */ -function link(from, to) { - return function (args) { - return to(from(args)); - }; -} + .set('brace.open', function() { + var pos = this.position(); + var m = this.match(/^\{(?!(?:[^\\}]?|,+)\})/); + if (!m) return; -function wrapConversion(toModel, graph) { - var path = [graph[toModel].parent, toModel]; - var fn = conversions[graph[toModel].parent][toModel]; + var prev = this.prev(); + var last = utils.last(prev.nodes); - var cur = graph[toModel].parent; - while (graph[cur].parent) { - path.unshift(graph[cur].parent); - fn = link(conversions[graph[cur].parent][cur], fn); - cur = graph[cur].parent; - } + // if the last parsed character was an extglob character + // we need to _not optimize_ the brace pattern because + // it might be mistaken for an extglob by a downstream parser + if (last && last.val && isExtglobChar(last.val.slice(-1))) { + last.optimize = false; + } - fn.conversion = path; - return fn; -} + var open = pos(new Node({ + type: 'brace.open', + val: m[0] + })); -module.exports = function (fromModel) { - var graph = deriveBFS(fromModel); - var conversion = {}; + var node = pos(new Node({ + type: 'brace', + nodes: [] + })); - var models = Object.keys(graph); - for (var len = models.length, i = 0; i < len; i++) { - var toModel = models[i]; - var node = graph[toModel]; + node.push(open); + prev.push(node); + this.push('brace', node); + }) - if (node.parent === null) { - // no possible conversion, or this node is the source model. - continue; - } + /** + * Close + */ - conversion[toModel] = wrapConversion(toModel, graph); - } + .set('brace.close', function() { + var pos = this.position(); + var m = this.match(/^\}/); + if (!m || !m[0]) return; + + var brace = this.pop('brace'); + var node = pos(new Node({ + type: 'brace.close', + val: m[0] + })); + + if (!this.isType(brace, 'brace')) { + if (this.options.strict) { + throw new Error('missing opening "{"'); + } + node.type = 'text'; + node.multiplier = 0; + node.escaped = true; + return node; + } - return conversion; -}; + var prev = this.prev(); + var last = utils.last(prev.nodes); + if (last.text) { + var lastNode = utils.last(last.nodes); + if (lastNode.val === ')' && /[!@*?+]\(/.test(last.text)) { + var open = last.nodes[0]; + var text = last.nodes[1]; + if (open.type === 'brace.open' && text && text.type === 'text') { + text.optimize = false; + } + } + } + if (brace.nodes.length > 2) { + var first = brace.nodes[1]; + if (first.type === 'text' && first.val === ',') { + brace.nodes.splice(1, 1); + brace.nodes.push(first); + } + } + brace.push(node); + }) -/***/ }), -/* 124 */ -/***/ (function(module, exports, __webpack_require__) { + /** + * Capture boundary characters + */ -"use strict"; + .set('boundary', function() { + var pos = this.position(); + var m = this.match(/^[$^](?!\{)/); + if (!m) return; + return pos(new Node({ + type: 'text', + val: m[0] + })); + }) -const os = __webpack_require__(84); -const hasFlag = __webpack_require__(93); + /** + * One or zero, non-comma characters wrapped in braces + */ -const env = process.env; + .set('nobrace', function() { + var isInside = this.isInside('brace'); + var pos = this.position(); + var m = this.match(/^\{[^,]?\}/); + if (!m) return; -let forceColor; -if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false')) { - forceColor = false; -} else if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - forceColor = true; -} -if ('FORCE_COLOR' in env) { - forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; -} + var prev = this.prev(); + var val = m[0]; -function translateLevel(level) { - if (level === 0) { - return false; - } + if (isInside && prev.type === 'brace') { + prev.text = prev.text || ''; + prev.text += val; + } - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; -} + return pos(new Node({ + type: 'text', + multiplier: 0, + val: val + })); + }) -function supportsColor(stream) { - if (forceColor === false) { - return 0; - } + /** + * Text + */ - if (hasFlag('color=16m') || - hasFlag('color=full') || - hasFlag('color=truecolor')) { - return 3; - } + .set('text', function() { + var isInside = this.isInside('brace'); + var pos = this.position(); + var m = this.match(/^((?!\\)[^${}\[\]])+/); + if (!m) return; - if (hasFlag('color=256')) { - return 2; - } + var prev = this.prev(); + var val = m[0]; - if (stream && !stream.isTTY && forceColor !== true) { - // VS code debugger doesn't have isTTY set - if (env.VSCODE_PID) { - return 1; - } - return 0; - } + if (isInside && prev.type === 'brace') { + prev.text = prev.text || ''; + prev.text += val; + } - const min = forceColor ? 1 : 0; + var node = pos(new Node({ + type: 'text', + multiplier: 1, + val: val + })); - if (process.platform === 'win32') { - // Node.js 7.5.0 is the first version of Node.js to include a patch to - // libuv that enables 256 color output on Windows. Anything earlier and it - // won't work. However, here we target Node.js 8 at minimum as it is an LTS - // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows - // release that supports 256 colors. Windows 10 build 14931 is the first release - // that supports 16m/TrueColor. - const osRelease = os.release().split('.'); - if ( - Number(process.versions.node.split('.')[0]) >= 8 && - Number(osRelease[0]) >= 10 && - Number(osRelease[2]) >= 10586 - ) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } + return concatNodes.call(this, pos, node, prev, options); + }); +}; - return 1; - } +/** + * Returns true if the character is an extglob character. + */ - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { - return 1; - } +function isExtglobChar(ch) { + return ch === '!' || ch === '@' || ch === '*' || ch === '?' || ch === '+'; +} - return min; - } +/** + * Combine text nodes, and calculate empty sets (`{,,}`) + * @param {Function} `pos` Function to calculate node position + * @param {Object} `node` AST node + * @return {Object} + */ - if ('TEAMCITY_VERSION' in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } +function concatNodes(pos, node, parent, options) { + node.orig = node.val; + var prev = this.prev(); + var last = utils.last(prev.nodes); + var isEscaped = false; - if (env.COLORTERM === 'truecolor') { - return 3; - } + if (node.val.length > 1) { + var a = node.val.charAt(0); + var b = node.val.slice(-1); - if ('TERM_PROGRAM' in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + isEscaped = (a === '"' && b === '"') + || (a === "'" && b === "'") + || (a === '`' && b === '`'); + } - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Apple_Terminal': - return 2; - // No default - } - } + if (isEscaped && options.unescape !== false) { + node.val = node.val.slice(1, node.val.length - 1); + node.escaped = true; + } - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } + if (node.match) { + var match = node.match[1]; + if (!match || match.indexOf('}') === -1) { + match = node.match[0]; + } - if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } + // replace each set with a single "," + var val = match.replace(/\{/g, ',').replace(/\}/g, ''); + node.multiplier *= val.length; + node.val = ''; + } - if ('COLORTERM' in env) { - return 1; - } + var simpleText = last.type === 'text' + && last.multiplier === 1 + && node.multiplier === 1 + && node.val; - if (env.TERM === 'dumb') { - return min; - } + if (simpleText) { + last.val += node.val; + return; + } - return min; + prev.push(node); } -function getSupportLevel(stream) { - const level = supportsColor(stream); - return translateLevel(level); -} -module.exports = { - supportsColor: getSupportLevel, - stdout: getSupportLevel(process.stdout), - stderr: getSupportLevel(process.stderr) -}; +/***/ }), +/* 139 */ +/***/ (function(module, exports, __webpack_require__) { + + +/** + * Expose `Emitter`. + */ + +if (true) { + module.exports = Emitter; +} + +/** + * Initialize a new `Emitter`. + * + * @api public + */ + +function Emitter(obj) { + if (obj) return mixin(obj); +}; + +/** + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + +function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; + } + return obj; +} + +/** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.on = +Emitter.prototype.addEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + (this._callbacks['$' + event] = this._callbacks['$' + event] || []) + .push(fn); + return this; +}; + +/** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.once = function(event, fn){ + function on() { + this.off(event, on); + fn.apply(this, arguments); + } + + on.fn = fn; + this.on(event, on); + return this; +}; + +/** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.off = +Emitter.prototype.removeListener = +Emitter.prototype.removeAllListeners = +Emitter.prototype.removeEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + + // all + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } + + // specific event + var callbacks = this._callbacks['$' + event]; + if (!callbacks) return this; + + // remove all handlers + if (1 == arguments.length) { + delete this._callbacks['$' + event]; + return this; + } + + // remove specific handler + var cb; + for (var i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + if (cb === fn || cb.fn === fn) { + callbacks.splice(i, 1); + break; + } + } + return this; +}; + +/** + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} + */ + +Emitter.prototype.emit = function(event){ + this._callbacks = this._callbacks || {}; + var args = [].slice.call(arguments, 1) + , callbacks = this._callbacks['$' + event]; + + if (callbacks) { + callbacks = callbacks.slice(0); + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); + } + } + + return this; +}; + +/** + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public + */ + +Emitter.prototype.listeners = function(event){ + this._callbacks = this._callbacks || {}; + return this._callbacks['$' + event] || []; +}; + +/** + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public + */ + +Emitter.prototype.hasListeners = function(event){ + return !! this.listeners(event).length; +}; /***/ }), -/* 125 */ +/* 140 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/*! + * object-visit + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ -const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; -const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; -const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; -const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; -const ESCAPES = new Map([ - ['n', '\n'], - ['r', '\r'], - ['t', '\t'], - ['b', '\b'], - ['f', '\f'], - ['v', '\v'], - ['0', '\0'], - ['\\', '\\'], - ['e', '\u001B'], - ['a', '\u0007'] -]); -function unescape(c) { - if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) { - return String.fromCharCode(parseInt(c.slice(1), 16)); - } +var isObject = __webpack_require__(30); - return ESCAPES.get(c) || c; -} +module.exports = function visit(thisArg, method, target, val) { + if (!isObject(thisArg) && typeof thisArg !== 'function') { + throw new Error('object-visit expects `thisArg` to be an object.'); + } -function parseArguments(name, args) { - const results = []; - const chunks = args.trim().split(/\s*,\s*/g); - let matches; + if (typeof method !== 'string') { + throw new Error('object-visit expects `method` name to be a string'); + } - for (const chunk of chunks) { - if (!isNaN(chunk)) { - results.push(Number(chunk)); - } else if ((matches = chunk.match(STRING_REGEX))) { - results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr)); - } else { - throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); - } - } + if (typeof thisArg[method] !== 'function') { + return thisArg; + } - return results; -} + var args = [].slice.call(arguments, 3); + target = target || {}; -function parseStyle(style) { - STYLE_REGEX.lastIndex = 0; + for (var key in target) { + var arr = [key, target[key]].concat(args); + thisArg[method].apply(thisArg, arr); + } + return thisArg; +}; - const results = []; - let matches; - while ((matches = STYLE_REGEX.exec(style)) !== null) { - const name = matches[1]; +/***/ }), +/* 141 */ +/***/ (function(module, exports, __webpack_require__) { - if (matches[2]) { - const args = parseArguments(name, matches[2]); - results.push([name].concat(args)); - } else { - results.push([name]); - } - } +"use strict"; +/*! + * to-object-path + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ - return results; -} -function buildStyle(chalk, styles) { - const enabled = {}; - for (const layer of styles) { - for (const style of layer.styles) { - enabled[style[0]] = layer.inverse ? null : style.slice(1); - } - } +var typeOf = __webpack_require__(49); - let current = chalk; - for (const styleName of Object.keys(enabled)) { - if (Array.isArray(enabled[styleName])) { - if (!(styleName in current)) { - throw new Error(`Unknown Chalk style: ${styleName}`); - } +module.exports = function toPath(args) { + if (typeOf(args) !== 'arguments') { + args = arguments; + } + return filter(args).join('.'); +}; - if (enabled[styleName].length > 0) { - current = current[styleName].apply(current, enabled[styleName]); - } else { - current = current[styleName]; - } - } - } +function filter(arr) { + var len = arr.length; + var idx = -1; + var res = []; - return current; + while (++idx < len) { + var ele = arr[idx]; + if (typeOf(ele) === 'arguments' || Array.isArray(ele)) { + res.push.apply(res, filter(ele)); + } else if (typeof ele === 'string') { + res.push(ele); + } + } + return res; } -module.exports = (chalk, tmp) => { - const styles = []; - const chunks = []; - let chunk = []; - // eslint-disable-next-line max-params - tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { - if (escapeChar) { - chunk.push(unescape(escapeChar)); - } else if (style) { - const str = chunk.join(''); - chunk = []; - chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); - styles.push({inverse, styles: parseStyle(style)}); - } else if (close) { - if (styles.length === 0) { - throw new Error('Found extraneous } in Chalk template literal'); - } +/***/ }), +/* 142 */ +/***/ (function(module, exports, __webpack_require__) { - chunks.push(buildStyle(chalk, styles)(chunk.join(''))); - chunk = []; - styles.pop(); - } else { - chunk.push(chr); - } - }); +"use strict"; - chunks.push(chunk.join('')); - if (styles.length > 0) { - const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; - throw new Error(errMsg); - } +module.exports = function union(init) { + if (!Array.isArray(init)) { + throw new TypeError('arr-union expects the first argument to be an array.'); + } - return chunks.join(''); + var len = arguments.length; + var i = 0; + + while (++i < len) { + var arg = arguments[i]; + if (!arg) continue; + + if (!Array.isArray(arg)) { + arg = [arg]; + } + + for (var j = 0; j < arg.length; j++) { + var ele = arg[j]; + + if (init.indexOf(ele) >= 0) { + continue; + } + init.push(ele); + } + } + return init; }; /***/ }), -/* 126 */ +/* 143 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/*! + * use + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ -function dedent(strings) { - var raw = void 0; - if (typeof strings === "string") { - // dedent can be used as a plain function - raw = [strings]; - } else { - raw = strings.raw; - } +var utils = __webpack_require__(380); - // first, perform interpolation - var result = ""; - for (var i = 0; i < raw.length; i++) { - result += raw[i]. - // join lines when there is a suppressed newline - replace(/\\\n[ \t]*/g, ""). +module.exports = function base(app, opts) { + if (!utils.isObject(app) && typeof app !== 'function') { + throw new TypeError('use: expect `app` be an object or function'); + } - // handle escaped backticks - replace(/\\`/g, "`"); + if (!utils.isObject(opts)) { + opts = {}; + } - if (i < (arguments.length <= 1 ? 0 : arguments.length - 1)) { - result += arguments.length <= i + 1 ? undefined : arguments[i + 1]; - } + var prop = utils.isString(opts.prop) ? opts.prop : 'fns'; + if (!Array.isArray(app[prop])) { + utils.define(app, prop, []); } - // now strip indentation - var lines = result.split("\n"); - var mindent = null; - lines.forEach(function (l) { - var m = l.match(/^(\s+)\S+/); - if (m) { - var indent = m[1].length; - if (!mindent) { - // this is the first indented line - mindent = indent; - } else { - mindent = Math.min(mindent, indent); - } + /** + * Define a plugin function to be passed to use. The only + * parameter exposed to the plugin is `app`, the object or function. + * passed to `use(app)`. `app` is also exposed as `this` in plugins. + * + * Additionally, **if a plugin returns a function, the function will + * be pushed onto the `fns` array**, allowing the plugin to be + * called at a later point by the `run` method. + * + * ```js + * var use = require('use'); + * + * // define a plugin + * function foo(app) { + * // do stuff + * } + * + * var app = function(){}; + * use(app); + * + * // register plugins + * app.use(foo); + * app.use(bar); + * app.use(baz); + * ``` + * @name .use + * @param {Function} `fn` plugin function to call + * @api public + */ + + utils.define(app, 'use', use); + + /** + * Run all plugins on `fns`. Any plugin that returns a function + * when called by `use` is pushed onto the `fns` array. + * + * ```js + * var config = {}; + * app.run(config); + * ``` + * @name .run + * @param {Object} `value` Object to be modified by plugins. + * @return {Object} Returns the object passed to `run` + * @api public + */ + + utils.define(app, 'run', function(val) { + if (!utils.isObject(val)) return; + decorate(val); + + var self = this || app; + var fns = self[prop]; + var len = fns.length; + var idx = -1; + + while (++idx < len) { + val.use(fns[idx]); } + return val; }); - if (mindent !== null) { - result = lines.map(function (l) { - return l[0] === " " ? l.slice(mindent) : l; - }).join("\n"); + /** + * Call plugin `fn`. If a function is returned push it into the + * `fns` array to be called by the `run` method. + */ + + function use(fn, options) { + if (typeof fn !== 'function') { + throw new TypeError('.use expects `fn` be a function'); + } + + var self = this || app; + if (typeof opts.fn === 'function') { + opts.fn.call(self, self, options); + } + + var plugin = fn.call(self, self); + if (typeof plugin === 'function') { + var fns = self[prop]; + fns.push(plugin); + } + return self; } - // dedent eats leading and trailing whitespace too - result = result.trim(); + /** + * Ensure the `.use` method exists on `val` + */ - // handle escaped newlines at the end to ensure they don't get stripped too - return result.replace(/\\n/g, "\n"); -} + function decorate(val) { + if (!val.use || !val.run) { + base(val); + } + } -if (true) { - module.exports = dedent; -} + return app; +}; /***/ }), -/* 127 */ -/***/ (function(module, exports) { +/* 144 */ +/***/ (function(module, exports, __webpack_require__) { -const SHORTSPLIT = /$|[!-@\[-`{-~].*/g -const EMPTY = [] -function array(any) { - return Array.isArray(any) ? any : [any] -} +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ -function aliases(aliases) { - var out = {} +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = __webpack_require__(389); - for (var key in aliases) { - var alias = (out[key] = array(aliases[key])) +/** + * The currently active debug mode names, and names to skip. + */ - for (var i = 0, len = alias.length; i < len; i++) { - var curr = (out[alias[i]] = [key]) +exports.names = []; +exports.skips = []; - for (var j = 0; j < len; j++) { - if (i !== j) { - curr.push(alias[j]) - } - } - } - } +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ - return out -} +exports.formatters = {}; -function booleans(aliases, booleans) { - var out = {} +/** + * Previous log timestamp. + */ - if (booleans !== undefined) { - for (var i = 0, len = booleans.length; i < len; i++) { - var key = booleans[i] - var alias = aliases[key] +var prevTime; - out[key] = true +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ - if (alias === undefined) { - aliases[key] = EMPTY - } else { - for (var j = 0, end = alias.length; j < end; j++) { - out[alias[j]] = true - } - } - } +function selectColor(namespace) { + var hash = 0, i; + + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer } - return out + return exports.colors[Math.abs(hash) % exports.colors.length]; } -function defaults(aliases, defaults) { - var out = {} +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ - for (var key in defaults) { - var value = defaults[key] - var alias = aliases[key] +function createDebug(namespace) { - if (out[key] === undefined) { - out[key] = value + function debug() { + // disabled? + if (!debug.enabled) return; - if (alias === undefined) { - aliases[key] = EMPTY - } else { - for (var i = 0, len = alias.length; i < len; i++) { - out[alias[i]] = value - } - } - } - } + var self = debug; - return out -} + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; -function set(out, key, value, aliases, unknown) { - var curr = out[key] - var alias = aliases[key] - var known = alias !== undefined + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } - if (known || unknown === undefined || false !== unknown(key)) { - if (curr === undefined) { - out[key] = value - } else { - if (Array.isArray(curr)) { - curr.push(value) - } else { - out[key] = [curr, value] - } + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); } - if (known) { - for (var i = 0, len = alias.length; i < len; ) { - out[alias[i++]] = out[key] + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); + + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; } - } + return match; + }); + + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); + + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); } + + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + return debug; } -module.exports = function(argv, opts) { - var unknown = (opts = opts || {}).unknown - var alias = aliases(opts.alias) - var values = defaults(alias, opts.default) - var bools = booleans(alias, opts.boolean) - var out = { _: [] } +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ - for (var i = 0, j = 0, len = argv.length, _ = out._; i < len; i++) { - var arg = argv[i] +function enable(namespaces) { + exports.save(namespaces); - if (arg === "--") { - while (++i < len) { - _.push(argv[i]) - } - } else if (arg === "-" || arg[0] !== "-") { - _.push(arg) - } else { - if (arg[1] === "-") { - var end = arg.indexOf("=", 2) + exports.names = []; + exports.skips = []; - if (0 <= end) { - set(out, arg.slice(2, end), arg.slice(end + 1), alias, unknown) - } else { - if ("n" === arg[2] && "o" === arg[3] && "-" === arg[4]) { - set(out, arg.slice(5), false, alias, unknown) - } else { - var key = arg.slice(2) - set( - out, - key, - len === (j = i + 1) || - argv[j][0] === "-" || - bools[key] !== undefined || - argv[(i = j)], - alias, - unknown - ) - } - } - } else { - SHORTSPLIT.lastIndex = 2 - var match = SHORTSPLIT.exec(arg) - var end = match.index - var value = - match[0] || - len === (j = i + 1) || - argv[j][0] === "-" || - bools[arg[end - 1]] !== undefined || - argv[(i = j)] + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; - for (j = 1; j < end; ) { - set(out, arg[j], ++j !== end || value, alias, unknown) - } - } + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); } } +} - for (var key in values) { - if (out[key] === undefined) { - out[key] = values[key] +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; } } + return false; +} - return out +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; } /***/ }), -/* 128 */ +/* 145 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +var base64VLQ = __webpack_require__(146); +var util = __webpack_require__(68); +var ArraySet = __webpack_require__(147).ArraySet; +var MappingList = __webpack_require__(395).MappingList; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.commands = undefined; +/** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ +function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; +} -var _bootstrap = __webpack_require__(129); +SourceMapGenerator.prototype._version = 3; + +/** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ +SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; -var _clean = __webpack_require__(214); + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } -var _run = __webpack_require__(236); + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; -var _watch = __webpack_require__(237); + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + +/** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. */ -const commands = exports.commands = { - bootstrap: _bootstrap.BootstrapCommand, - clean: _clean.CleanCommand, - run: _run.RunCommand, - watch: _watch.WatchCommand -}; - -/***/ }), -/* 129 */ -/***/ (function(module, exports, __webpack_require__) { +SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); -"use strict"; + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.BootstrapCommand = undefined; + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } -var _chalk = __webpack_require__(30); + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; -var _chalk2 = _interopRequireDefault(_chalk); +/** + * Set the source content for a source file. + */ +SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; -var _link_project_executables = __webpack_require__(130); +/** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ +SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } -var _log = __webpack_require__(36); + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } -var _parallelize = __webpack_require__(85); + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } -var _projects = __webpack_require__(42); + }, this); + this._sources = newSources; + this._names = newNames; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; -function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ +/** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ +SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + throw new Error( + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.' + ); + } + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; -const BootstrapCommand = exports.BootstrapCommand = { - description: 'Install dependencies and crosslink projects', - name: 'bootstrap', - run(projects, projectGraph, { options }) { - return _asyncToGenerator(function* () { - const batchedProjectsByWorkspace = (0, _projects.topologicallyBatchProjects)(projects, projectGraph, { - batchByWorkspace: true - }); - const batchedProjects = (0, _projects.topologicallyBatchProjects)(projects, projectGraph); - const extraArgs = [...(options['frozen-lockfile'] === true ? ['--frozen-lockfile'] : []), ...(options['prefer-offline'] === true ? ['--prefer-offline'] : [])]; - _log.log.write(_chalk2.default.bold('\nRunning installs in topological order:')); - for (const batch of batchedProjectsByWorkspace) { - for (const project of batch) { - if (project.isWorkspaceProject) { - _log.log.write(`Skipping workspace project: ${project.name}`); - continue; - } - if (project.hasDependencies()) { - yield project.installDependencies({ extraArgs }); - } - } - } - _log.log.write(_chalk2.default.bold('\nInstalls completed, linking package executables:\n')); - yield (0, _link_project_executables.linkProjectExecutables)(projects, projectGraph); - /** - * At the end of the bootstrapping process we call all `kbn:bootstrap` scripts - * in the list of projects. We do this because some projects need to be - * transpiled before they can be used. Ideally we shouldn't do this unless we - * have to, as it will slow down the bootstrapping process. - */ - _log.log.write(_chalk2.default.bold('\nLinking executables completed, running `kbn:bootstrap` scripts\n')); - yield (0, _parallelize.parallelizeBatches)(batchedProjects, (() => { - var _ref = _asyncToGenerator(function* (pkg) { - if (pkg.hasScript('kbn:bootstrap')) { - yield pkg.runScriptStreaming('kbn:bootstrap'); - } - }); - - return function (_x) { - return _ref.apply(this, arguments); - }; - })()); - _log.log.write(_chalk2.default.green.bold('\nBootstrapping completed!\n')); - })(); - } -}; +/** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ +SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } -/***/ }), -/* 130 */ -/***/ (function(module, exports, __webpack_require__) { + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; -"use strict"; + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.linkProjectExecutables = undefined; + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; -/** - * Yarn does not link the executables from dependencies that are installed - * using `link:` https://github.com/yarnpkg/yarn/pull/5046 - * - * We simulate this functionality by walking through each project's project - * dependencies, and manually linking their executables if defined. The logic - * for linking was mostly adapted from lerna: https://github.com/lerna/lerna/blob/1d7eb9eeff65d5a7de64dea73613b1bf6bfa8d57/src/PackageUtilities.js#L348 - */ -let linkProjectExecutables = exports.linkProjectExecutables = (() => { - var _ref = _asyncToGenerator(function* (projectsByName, projectGraph) { - for (const [projectName, projectDeps] of projectGraph) { - const project = projectsByName.get(projectName); - const binsDir = (0, _path.resolve)(project.nodeModulesLocation, '.bin'); - for (const projectDep of projectDeps) { - const executables = projectDep.getExecutables(); - for (const name of Object.keys(executables)) { - const srcPath = executables[name]; - // existing logic from lerna -- ensure that the bin we are going to - // point to exists or ignore it - if (!(yield (0, _fs.isFile)(srcPath))) { - continue; - } - const dest = (0, _path.resolve)(binsDir, name); - // Get relative project path with normalized path separators. - const projectRelativePath = (0, _path.relative)(project.path, srcPath).split(_path.sep).join('/'); - _log.log.write(_chalk2.default`{dim [${project.name}]} ${name} -> {dim ${projectRelativePath}}`); - yield (0, _fs.mkdirp)((0, _path.dirname)(dest)); - yield (0, _fs.createSymlink)(srcPath, dest, 'exec'); - yield (0, _fs.chmod)(dest, '755'); - } - } + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; } - }); + } - return function linkProjectExecutables(_x, _x2) { - return _ref.apply(this, arguments); - }; -})(); + result += next; + } -var _path = __webpack_require__(7); + return result; + }; -var _chalk = __webpack_require__(30); +SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; -var _chalk2 = _interopRequireDefault(_chalk); +/** + * Externalize the source map. + */ +SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } -var _fs = __webpack_require__(60); + return map; + }; -var _log = __webpack_require__(36); +/** + * Render the source map being generated to a string. + */ +SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +exports.SourceMapGenerator = SourceMapGenerator; -function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ /***/ }), -/* 131 */ +/* 146 */ /***/ (function(module, exports, __webpack_require__) { -// On windows, create a .cmd file. -// Read the #! in the file to see what it uses. The vast majority -// of the time, this will be either: -// "#!/usr/bin/env " -// or: -// "#! " +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +var base64 = __webpack_require__(394); + +// A single base 64 digit can contain 6 bits of data. For the base 64 variable +// length quantities we use in the source map spec, the first bit is the sign, +// the next four bits are the actual value, and the 6th bit is the +// continuation bit. The continuation bit tells us whether there are more +// digits in this value following this digit. // -// Write a binroot/pkg.bin + ".cmd" file that has this line in it: -// @ %~dp0 %* +// Continuation +// | Sign +// | | +// V V +// 101011 -module.exports = cmdShim -cmdShim.ifExists = cmdShimIfExists +var VLQ_BASE_SHIFT = 5; -var fs = __webpack_require__(56) +// binary: 100000 +var VLQ_BASE = 1 << VLQ_BASE_SHIFT; -var mkdir = __webpack_require__(95) - , path = __webpack_require__(7) - , shebangExpr = /^#\!\s*(?:\/usr\/bin\/env)?\s*([^ \t]+)(.*)$/ +// binary: 011111 +var VLQ_BASE_MASK = VLQ_BASE - 1; -function cmdShimIfExists (from, to, cb) { - fs.stat(from, function (er) { - if (er) return cb() - cmdShim(from, to, cb) - }) +// binary: 100000 +var VLQ_CONTINUATION_BIT = VLQ_BASE; + +/** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ +function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; } -// Try to unlink, but ignore errors. -// Any problems will surface later. -function rm (path, cb) { - fs.unlink(path, function(er) { - cb() - }) +/** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ +function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; } -function cmdShim (from, to, cb) { - fs.stat(from, function (er, stat) { - if (er) - return cb(er) +/** + * Returns the base 64 VLQ encoded value. + */ +exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; - cmdShim_(from, to, cb) - }) -} + var vlq = toVLQSigned(aValue); -function cmdShim_ (from, to, cb) { - var then = times(2, next, cb) - rm(to, then) - rm(to + ".cmd", then) + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); - function next(er) { - writeShim(from, to, cb) - } -} + return encoded; +}; -function writeShim (from, to, cb) { - // make a cmd file and a sh script - // First, check if the bin is a #! of some sort. - // If not, then assume it's something that'll be compiled, or some other - // sort of script, and just call it directly. - mkdir(path.dirname(to), function (er) { - if (er) - return cb(er) - fs.readFile(from, "utf8", function (er, data) { - if (er) return writeShim_(from, to, null, null, cb) - var firstLine = data.trim().split(/\r*\n/)[0] - , shebang = firstLine.match(shebangExpr) - if (!shebang) return writeShim_(from, to, null, null, cb) - var prog = shebang[1] - , args = shebang[2] || "" - return writeShim_(from, to, prog, args, cb) - }) - }) +/** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ +exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; +}; + + +/***/ }), +/* 147 */ +/***/ (function(module, exports, __webpack_require__) { + +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = __webpack_require__(68); +var has = Object.prototype.hasOwnProperty; +var hasNativeMap = typeof Map !== "undefined"; + +/** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ +function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); } -function writeShim_ (from, to, prog, args, cb) { - var shTarget = path.relative(path.dirname(to), from) - , target = shTarget.split("/").join("\\") - , longProg - , shProg = prog && prog.split("\\").join("/") - , shLongProg - shTarget = shTarget.split("\\").join("/") - args = args || "" - if (!prog) { - prog = "\"%~dp0\\" + target + "\"" - shProg = "\"$basedir/" + shTarget + "\"" - args = "" - target = "" - shTarget = "" +/** + * Static method for creating ArraySet instances from an existing array. + */ +ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; +}; + +/** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ +ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; +}; + +/** + * Add the given string to this set. + * + * @param String aStr + */ +ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } +}; + +/** + * Is the given string a member of this set? + * + * @param String aStr + */ +ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); } else { - longProg = "\"%~dp0\\" + prog + ".exe\"" - shLongProg = "\"$basedir/" + prog + "\"" - target = "\"%~dp0\\" + target + "\"" - shTarget = "\"$basedir/" + shTarget + "\"" + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); } +}; - // @IF EXIST "%~dp0\node.exe" ( - // "%~dp0\node.exe" "%~dp0\.\node_modules\npm\bin\npm-cli.js" %* - // ) ELSE ( - // SETLOCAL - // SET PATHEXT=%PATHEXT:;.JS;=;% - // node "%~dp0\.\node_modules\npm\bin\npm-cli.js" %* - // ) - var cmd - if (longProg) { - cmd = "@IF EXIST " + longProg + " (\r\n" - + " " + longProg + " " + args + " " + target + " %*\r\n" - + ") ELSE (\r\n" - + " @SETLOCAL\r\n" - + " @SET PATHEXT=%PATHEXT:;.JS;=;%\r\n" - + " " + prog + " " + args + " " + target + " %*\r\n" - + ")" +/** + * What is the index of the given string in the array? + * + * @param String aStr + */ +ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } } else { - cmd = "@" + prog + " " + args + " " + target + " %*\r\n" + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } } - // #!/bin/sh - // basedir=`dirname "$0"` - // - // case `uname` in - // *CYGWIN*) basedir=`cygpath -w "$basedir"`;; - // esac - // - // if [ -x "$basedir/node.exe" ]; then - // "$basedir/node.exe" "$basedir/node_modules/npm/bin/npm-cli.js" "$@" - // ret=$? - // else - // node "$basedir/node_modules/npm/bin/npm-cli.js" "$@" - // ret=$? - // fi - // exit $ret + throw new Error('"' + aStr + '" is not in the set.'); +}; - var sh = "#!/bin/sh\n" +/** + * What is the element at the given index? + * + * @param Number aIdx + */ +ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); +}; - if (shLongProg) { - sh = sh - + "basedir=$(dirname \"$(echo \"$0\" | sed -e 's,\\\\,/,g')\")\n" - + "\n" - + "case `uname` in\n" - + " *CYGWIN*) basedir=`cygpath -w \"$basedir\"`;;\n" - + "esac\n" - + "\n" +/** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ +ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); +}; - sh = sh - + "if [ -x "+shLongProg+" ]; then\n" - + " " + shLongProg + " " + args + " " + shTarget + " \"$@\"\n" - + " ret=$?\n" - + "else \n" - + " " + shProg + " " + args + " " + shTarget + " \"$@\"\n" - + " ret=$?\n" - + "fi\n" - + "exit $ret\n" - } else { - sh = shProg + " " + args + " " + shTarget + " \"$@\"\n" - + "exit $?\n" - } +exports.ArraySet = ArraySet; - var then = times(2, next, cb) - fs.writeFile(to + ".cmd", cmd, "utf8", then) - fs.writeFile(to, sh, "utf8", then) - function next () { - chmodShim(to, cb) - } -} -function chmodShim (to, cb) { - var then = times(2, cb, cb) - fs.chmod(to, 0755, then) - fs.chmod(to + ".cmd", 0755, then) +/***/ }), +/* 148 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * map-cache + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +var hasOwn = Object.prototype.hasOwnProperty; + +/** + * Expose `MapCache` + */ + +module.exports = MapCache; + +/** + * Creates a cache object to store key/value pairs. + * + * ```js + * var cache = new MapCache(); + * ``` + * + * @api public + */ + +function MapCache(data) { + this.__data__ = data || {}; } -function times(n, ok, cb) { - var errState = null - return function(er) { - if (!errState) { - if (er) - cb(errState = er) - else if (--n === 0) - ok() - } +/** + * Adds `value` to `key` on the cache. + * + * ```js + * cache.set('foo', 'bar'); + * ``` + * + * @param {String} `key` The key of the value to cache. + * @param {*} `value` The value to cache. + * @returns {Object} Returns the `Cache` object for chaining. + * @api public + */ + +MapCache.prototype.set = function mapSet(key, value) { + if (key !== '__proto__') { + this.__data__[key] = value; } -} + return this; +}; + +/** + * Gets the cached value for `key`. + * + * ```js + * cache.get('foo'); + * //=> 'bar' + * ``` + * + * @param {String} `key` The key of the value to get. + * @returns {*} Returns the cached value. + * @api public + */ + +MapCache.prototype.get = function mapGet(key) { + return key === '__proto__' ? undefined : this.__data__[key]; +}; + +/** + * Checks if a cached value for `key` exists. + * + * ```js + * cache.has('foo'); + * //=> true + * ``` + * + * @param {String} `key` The key of the entry to check. + * @returns {Boolean} Returns `true` if an entry for `key` exists, else `false`. + * @api public + */ + +MapCache.prototype.has = function mapHas(key) { + return key !== '__proto__' && hasOwn.call(this.__data__, key); +}; + +/** + * Removes `key` and its value from the cache. + * + * ```js + * cache.del('foo'); + * ``` + * @title .del + * @param {String} `key` The key of the value to remove. + * @returns {Boolean} Returns `true` if the entry was removed successfully, else `false`. + * @api public + */ + +MapCache.prototype.del = function mapDelete(key) { + return this.has(key) && delete this.__data__[key]; +}; /***/ }), -/* 132 */ +/* 149 */ /***/ (function(module, exports, __webpack_require__) { -var fs = __webpack_require__(94) -var constants = __webpack_require__(133) +"use strict"; -var origCwd = process.cwd -var cwd = null -var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform +/** + * Module dependencies + */ -process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process) - return cwd -} -try { - process.cwd() -} catch (er) {} +var util = __webpack_require__(14); +var toRegex = __webpack_require__(43); +var extend = __webpack_require__(20); -var chdir = process.chdir -process.chdir = function(d) { - cwd = null - chdir.call(process, d) -} +/** + * Local dependencies + */ -module.exports = patch +var compilers = __webpack_require__(411); +var parsers = __webpack_require__(412); +var cache = __webpack_require__(414); +var utils = __webpack_require__(415); +var MAX_LENGTH = 1024 * 64; -function patch (fs) { - // (re-)implement some things that are known busted or missing. +/** + * The main function takes a list of strings and one or more + * glob patterns to use for matching. + * + * ```js + * var nm = require('nanomatch'); + * nm(list, patterns[, options]); + * + * console.log(nm(['a.js', 'a.txt'], ['*.js'])); + * //=> [ 'a.js' ] + * ``` + * @param {Array} `list` A list of strings to match + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of matches + * @summary false + * @api public + */ - // lchmod, broken prior to 0.6.2 - // back-port the fix here. - if (constants.hasOwnProperty('O_SYMLINK') && - process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs) +function nanomatch(list, patterns, options) { + patterns = utils.arrayify(patterns); + list = utils.arrayify(list); + + var len = patterns.length; + if (list.length === 0 || len === 0) { + return []; } - // lutimes implementation, or no-op - if (!fs.lutimes) { - patchLutimes(fs) + if (len === 1) { + return nanomatch.match(list, patterns[0], options); } - // https://github.com/isaacs/node-graceful-fs/issues/4 - // Chown should not fail on einval or eperm if non-root. - // It should not fail on enosys ever, as this just indicates - // that a fs doesn't support the intended operation. + var negated = false; + var omit = []; + var keep = []; + var idx = -1; - fs.chown = chownFix(fs.chown) - fs.fchown = chownFix(fs.fchown) - fs.lchown = chownFix(fs.lchown) + while (++idx < len) { + var pattern = patterns[idx]; - fs.chmod = chmodFix(fs.chmod) - fs.fchmod = chmodFix(fs.fchmod) - fs.lchmod = chmodFix(fs.lchmod) + if (typeof pattern === 'string' && pattern.charCodeAt(0) === 33 /* ! */) { + omit.push.apply(omit, nanomatch.match(list, pattern.slice(1), options)); + negated = true; + } else { + keep.push.apply(keep, nanomatch.match(list, pattern, options)); + } + } - fs.chownSync = chownFixSync(fs.chownSync) - fs.fchownSync = chownFixSync(fs.fchownSync) - fs.lchownSync = chownFixSync(fs.lchownSync) + // minimatch.match parity + if (negated && keep.length === 0) { + if (options && options.unixify === false) { + keep = list.slice(); + } else { + var unixify = utils.unixify(options); + for (var i = 0; i < list.length; i++) { + keep.push(unixify(list[i])); + } + } + } - fs.chmodSync = chmodFixSync(fs.chmodSync) - fs.fchmodSync = chmodFixSync(fs.fchmodSync) - fs.lchmodSync = chmodFixSync(fs.lchmodSync) + var matches = utils.diff(keep, omit); + if (!options || options.nodupes !== false) { + return utils.unique(matches); + } - fs.stat = statFix(fs.stat) - fs.fstat = statFix(fs.fstat) - fs.lstat = statFix(fs.lstat) + return matches; +} - fs.statSync = statFixSync(fs.statSync) - fs.fstatSync = statFixSync(fs.fstatSync) - fs.lstatSync = statFixSync(fs.lstatSync) +/** + * Similar to the main function, but `pattern` must be a string. + * + * ```js + * var nm = require('nanomatch'); + * nm.match(list, pattern[, options]); + * + * console.log(nm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a')); + * //=> ['a.a', 'a.aa'] + * ``` + * @param {Array} `list` Array of strings to match + * @param {String} `pattern` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of matches + * @api public + */ - // if lchmod/lchown do not exist, then make them no-ops - if (!fs.lchmod) { - fs.lchmod = function (path, mode, cb) { - if (cb) process.nextTick(cb) +nanomatch.match = function(list, pattern, options) { + if (Array.isArray(pattern)) { + throw new TypeError('expected pattern to be a string'); + } + + var unixify = utils.unixify(options); + var isMatch = memoize('match', pattern, options, nanomatch.matcher); + var matches = []; + + list = utils.arrayify(list); + var len = list.length; + var idx = -1; + + while (++idx < len) { + var ele = list[idx]; + if (ele === pattern || isMatch(ele)) { + matches.push(utils.value(ele, unixify, options)); } - fs.lchmodSync = function () {} } - if (!fs.lchown) { - fs.lchown = function (path, uid, gid, cb) { - if (cb) process.nextTick(cb) + + // if no options were passed, uniquify results and return + if (typeof options === 'undefined') { + return utils.unique(matches); + } + + if (matches.length === 0) { + if (options.failglob === true) { + throw new Error('no matches found for "' + pattern + '"'); + } + if (options.nonull === true || options.nullglob === true) { + return [options.unescape ? utils.unescape(pattern) : pattern]; } - fs.lchownSync = function () {} } - // on Windows, A/V software can lock the directory, causing this - // to fail with an EACCES or EPERM if the directory contains newly - // created files. Try again on failure, for up to 60 seconds. + // if `opts.ignore` was defined, diff ignored list + if (options.ignore) { + matches = nanomatch.not(matches, options.ignore, options); + } - // Set the timeout this long because some Windows Anti-Virus, such as Parity - // bit9, may lock files for up to a minute, causing npm package install - // failures. Also, take care to yield the scheduler. Windows scheduling gives - // CPU to a busy looping process, which can cause the program causing the lock - // contention to be starved of CPU by node, so the contention doesn't resolve. - if (platform === "win32") { - fs.rename = (function (fs$rename) { return function (from, to, cb) { - var start = Date.now() - var backoff = 0; - fs$rename(from, to, function CB (er) { - if (er - && (er.code === "EACCES" || er.code === "EPERM") - && Date.now() - start < 60000) { - setTimeout(function() { - fs.stat(to, function (stater, st) { - if (stater && stater.code === "ENOENT") - fs$rename(from, to, CB); - else - cb(er) - }) - }, backoff) - if (backoff < 100) - backoff += 10; - return; - } - if (cb) cb(er) - }) - }})(fs.rename) - } + return options.nodupes !== false ? utils.unique(matches) : matches; +}; - // if read() returns EAGAIN, then just try it again. - fs.read = (function (fs$read) { return function (fd, buffer, offset, length, position, callback_) { - var callback - if (callback_ && typeof callback_ === 'function') { - var eagCounter = 0 - callback = function (er, _, __) { - if (er && er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } - callback_.apply(this, arguments) - } - } - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - }})(fs.read) +/** + * Returns true if the specified `string` matches the given glob `pattern`. + * + * ```js + * var nm = require('nanomatch'); + * nm.isMatch(string, pattern[, options]); + * + * console.log(nm.isMatch('a.a', '*.a')); + * //=> true + * console.log(nm.isMatch('a.b', '*.a')); + * //=> false + * ``` + * @param {String} `string` String to match + * @param {String} `pattern` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if the string matches the glob pattern. + * @api public + */ - fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { - var eagCounter = 0 - while (true) { - try { - return fs$readSync.call(fs, fd, buffer, offset, length, position) - } catch (er) { - if (er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - continue - } - throw er - } - } - }})(fs.readSync) -} +nanomatch.isMatch = function(str, pattern, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + } -function patchLchmod (fs) { - fs.lchmod = function (path, mode, callback) { - fs.open( path - , constants.O_WRONLY | constants.O_SYMLINK - , mode - , function (err, fd) { - if (err) { - if (callback) callback(err) - return - } - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - fs.fchmod(fd, mode, function (err) { - fs.close(fd, function(err2) { - if (callback) callback(err || err2) - }) - }) - }) + if (utils.isEmptyString(str) || utils.isEmptyString(pattern)) { + return false; } - fs.lchmodSync = function (path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) + var equals = utils.equalsPattern(options); + if (equals(str)) { + return true; + } - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - var threw = true - var ret - try { - ret = fs.fchmodSync(fd, mode) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret + var isMatch = memoize('isMatch', pattern, options, nanomatch.matcher); + return isMatch(str); +}; + +/** + * Returns true if some of the elements in the given `list` match any of the + * given glob `patterns`. + * + * ```js + * var nm = require('nanomatch'); + * nm.some(list, patterns[, options]); + * + * console.log(nm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // true + * console.log(nm.some(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +nanomatch.some = function(list, patterns, options) { + if (typeof list === 'string') { + list = [list]; } -} -function patchLutimes (fs) { - if (constants.hasOwnProperty("O_SYMLINK")) { - fs.lutimes = function (path, at, mt, cb) { - fs.open(path, constants.O_SYMLINK, function (er, fd) { - if (er) { - if (cb) cb(er) - return - } - fs.futimes(fd, at, mt, function (er) { - fs.close(fd, function (er2) { - if (cb) cb(er || er2) - }) - }) - }) + for (var i = 0; i < list.length; i++) { + if (nanomatch(list[i], patterns, options).length === 1) { + return true; } + } - fs.lutimesSync = function (path, at, mt) { - var fd = fs.openSync(path, constants.O_SYMLINK) - var ret - var threw = true - try { - ret = fs.futimesSync(fd, at, mt) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } + return false; +}; - } else { - fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } - fs.lutimesSync = function () {} - } -} +/** + * Returns true if every element in the given `list` matches + * at least one of the given glob `patterns`. + * + * ```js + * var nm = require('nanomatch'); + * nm.every(list, patterns[, options]); + * + * console.log(nm.every('foo.js', ['foo.js'])); + * // true + * console.log(nm.every(['foo.js', 'bar.js'], ['*.js'])); + * // true + * console.log(nm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // false + * console.log(nm.every(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ -function chmodFix (orig) { - if (!orig) return orig - return function (target, mode, cb) { - return orig.call(fs, target, mode, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) +nanomatch.every = function(list, patterns, options) { + if (typeof list === 'string') { + list = [list]; } -} -function chmodFixSync (orig) { - if (!orig) return orig - return function (target, mode) { - try { - return orig.call(fs, target, mode) - } catch (er) { - if (!chownErOk(er)) throw er + for (var i = 0; i < list.length; i++) { + if (nanomatch(list[i], patterns, options).length !== 1) { + return false; } } -} + return true; +}; -function chownFix (orig) { - if (!orig) return orig - return function (target, uid, gid, cb) { - return orig.call(fs, target, uid, gid, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) +/** + * Returns true if **any** of the given glob `patterns` + * match the specified `string`. + * + * ```js + * var nm = require('nanomatch'); + * nm.any(string, patterns[, options]); + * + * console.log(nm.any('a.a', ['b.*', '*.a'])); + * //=> true + * console.log(nm.any('a.a', 'b.*')); + * //=> false + * ``` + * @param {String|Array} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +nanomatch.any = function(str, patterns, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); } -} -function chownFixSync (orig) { - if (!orig) return orig - return function (target, uid, gid) { - try { - return orig.call(fs, target, uid, gid) - } catch (er) { - if (!chownErOk(er)) throw er + if (utils.isEmptyString(str) || utils.isEmptyString(patterns)) { + return false; + } + + if (typeof patterns === 'string') { + patterns = [patterns]; + } + + for (var i = 0; i < patterns.length; i++) { + if (nanomatch.isMatch(str, patterns[i], options)) { + return true; } } -} + return false; +}; +/** + * Returns true if **all** of the given `patterns` + * match the specified string. + * + * ```js + * var nm = require('nanomatch'); + * nm.all(string, patterns[, options]); + * + * console.log(nm.all('foo.js', ['foo.js'])); + * // true + * + * console.log(nm.all('foo.js', ['*.js', '!foo.js'])); + * // false + * + * console.log(nm.all('foo.js', ['*.js', 'foo.js'])); + * // true + * + * console.log(nm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); + * // true + * ``` + * @param {String|Array} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ -function statFix (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, cb) { - return orig.call(fs, target, function (er, stats) { - if (!stats) return cb.apply(this, arguments) - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - if (cb) cb.apply(this, arguments) - }) +nanomatch.all = function(str, patterns, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); } -} -function statFixSync (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target) { - var stats = orig.call(fs, target) - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - return stats; + if (typeof patterns === 'string') { + patterns = [patterns]; } -} -// ENOSYS means that the fs doesn't support the op. Just ignore -// that, because it doesn't matter. -// -// if there's no getuid, or if getuid() is something other -// than 0, and the error is EINVAL or EPERM, then just ignore -// it. -// -// This specific case is a silent failure in cp, install, tar, -// and most other unix tools that manage permissions. -// -// When running as root, or if other types of errors are -// encountered, then it's strict. -function chownErOk (er) { - if (!er) - return true + for (var i = 0; i < patterns.length; i++) { + if (!nanomatch.isMatch(str, patterns[i], options)) { + return false; + } + } + return true; +}; - if (er.code === "ENOSYS") - return true +/** + * Returns a list of strings that _**do not match any**_ of the given `patterns`. + * + * ```js + * var nm = require('nanomatch'); + * nm.not(list, patterns[, options]); + * + * console.log(nm.not(['a.a', 'b.b', 'c.c'], '*.a')); + * //=> ['b.b', 'c.c'] + * ``` + * @param {Array} `list` Array of strings to match. + * @param {String|Array} `patterns` One or more glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of strings that **do not match** the given patterns. + * @api public + */ - var nonroot = !process.getuid || process.getuid() !== 0 - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true +nanomatch.not = function(list, patterns, options) { + var opts = extend({}, options); + var ignore = opts.ignore; + delete opts.ignore; + + list = utils.arrayify(list); + + var matches = utils.diff(list, nanomatch(list, patterns, opts)); + if (ignore) { + matches = utils.diff(matches, nanomatch(list, ignore)); } - return false -} + return opts.nodupes !== false ? utils.unique(matches) : matches; +}; +/** + * Returns true if the given `string` contains the given pattern. Similar + * to [.isMatch](#isMatch) but the pattern can match any part of the string. + * + * ```js + * var nm = require('nanomatch'); + * nm.contains(string, pattern[, options]); + * + * console.log(nm.contains('aa/bb/cc', '*b')); + * //=> true + * console.log(nm.contains('aa/bb/cc', '*d')); + * //=> false + * ``` + * @param {String} `str` The string to match. + * @param {String|Array} `patterns` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if the patter matches any part of `str`. + * @api public + */ -/***/ }), -/* 133 */ -/***/ (function(module, exports) { +nanomatch.contains = function(str, patterns, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + } -module.exports = require("constants"); + if (typeof patterns === 'string') { + if (utils.isEmptyString(str) || utils.isEmptyString(patterns)) { + return false; + } -/***/ }), -/* 134 */ -/***/ (function(module, exports, __webpack_require__) { + var equals = utils.equalsPattern(patterns, options); + if (equals(str)) { + return true; + } + var contains = utils.containsPattern(patterns, options); + if (contains(str)) { + return true; + } + } -var Stream = __webpack_require__(41).Stream + var opts = extend({}, options, {contains: true}); + return nanomatch.any(str, patterns, opts); +}; -module.exports = legacy +/** + * Returns true if the given pattern and options should enable + * the `matchBase` option. + * @return {Boolean} + * @api private + */ -function legacy (fs) { - return { - ReadStream: ReadStream, - WriteStream: WriteStream - } +nanomatch.matchBase = function(pattern, options) { + if (pattern && pattern.indexOf('/') !== -1 || !options) return false; + return options.basename === true || options.matchBase === true; +}; - function ReadStream (path, options) { - if (!(this instanceof ReadStream)) return new ReadStream(path, options); +/** + * Filter the keys of the given object with the given `glob` pattern + * and `options`. Does not attempt to match nested keys. If you need this feature, + * use [glob-object][] instead. + * + * ```js + * var nm = require('nanomatch'); + * nm.matchKeys(object, patterns[, options]); + * + * var obj = { aa: 'a', ab: 'b', ac: 'c' }; + * console.log(nm.matchKeys(obj, '*b')); + * //=> { ab: 'b' } + * ``` + * @param {Object} `object` The object with keys to filter. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Object} Returns an object with only keys that match the given patterns. + * @api public + */ - Stream.call(this); +nanomatch.matchKeys = function(obj, patterns, options) { + if (!utils.isObject(obj)) { + throw new TypeError('expected the first argument to be an object'); + } + var keys = nanomatch(Object.keys(obj), patterns, options); + return utils.pick(obj, keys); +}; - var self = this; +/** + * Returns a memoized matcher function from the given glob `pattern` and `options`. + * The returned function takes a string to match as its only argument and returns + * true if the string is a match. + * + * ```js + * var nm = require('nanomatch'); + * nm.matcher(pattern[, options]); + * + * var isMatch = nm.matcher('*.!(*a)'); + * console.log(isMatch('a.a')); + * //=> false + * console.log(isMatch('a.b')); + * //=> true + * ``` + * @param {String} `pattern` Glob pattern + * @param {Object} `options` See available [options](#options) for changing how matches are performed. + * @return {Function} Returns a matcher function. + * @api public + */ - this.path = path; - this.fd = null; - this.readable = true; - this.paused = false; +nanomatch.matcher = function matcher(pattern, options) { + if (utils.isEmptyString(pattern)) { + return function() { + return false; + }; + } - this.flags = 'r'; - this.mode = 438; /*=0666*/ - this.bufferSize = 64 * 1024; + if (Array.isArray(pattern)) { + return compose(pattern, options, matcher); + } - options = options || {}; + // if pattern is a regex + if (pattern instanceof RegExp) { + return test(pattern); + } - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; + // if pattern is invalid + if (!utils.isString(pattern)) { + throw new TypeError('expected pattern to be an array, string or regex'); + } + + // if pattern is a non-glob string + if (!utils.hasSpecialChars(pattern)) { + if (options && options.nocase === true) { + pattern = pattern.toLowerCase(); } + return utils.matchPath(pattern, options); + } - if (this.encoding) this.setEncoding(this.encoding); + // if pattern is a glob string + var re = nanomatch.makeRe(pattern, options); - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.end === undefined) { - this.end = Infinity; - } else if ('number' !== typeof this.end) { - throw TypeError('end must be a Number'); + // if `options.matchBase` or `options.basename` is defined + if (nanomatch.matchBase(pattern, options)) { + return utils.matchBasename(re, options); + } + + function test(regex) { + var equals = utils.equalsPattern(options); + var unixify = utils.unixify(options); + + return function(str) { + if (equals(str)) { + return true; } - if (this.start > this.end) { - throw new Error('start must be <= end'); + if (regex.test(unixify(str))) { + return true; } + return false; + }; + } - this.pos = this.start; - } + var fn = test(re); + Object.defineProperty(fn, 'result', { + configurable: true, + enumerable: false, + value: re.result + }); + return fn; +}; - if (this.fd !== null) { - process.nextTick(function() { - self._read(); - }); - return; - } +/** + * Returns an array of matches captured by `pattern` in `string, or + * `null` if the pattern did not match. + * + * ```js + * var nm = require('nanomatch'); + * nm.capture(pattern, string[, options]); + * + * console.log(nm.capture('test/*.js', 'test/foo.js')); + * //=> ['foo'] + * console.log(nm.capture('test/*.js', 'foo/bar.css')); + * //=> null + * ``` + * @param {String} `pattern` Glob pattern to use for matching. + * @param {String} `string` String to match + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`. + * @api public + */ - fs.open(this.path, this.flags, this.mode, function (err, fd) { - if (err) { - self.emit('error', err); - self.readable = false; - return; +nanomatch.capture = function(pattern, str, options) { + var re = nanomatch.makeRe(pattern, extend({capture: true}, options)); + var unixify = utils.unixify(options); + + function match() { + return function(string) { + var match = re.exec(unixify(string)); + if (!match) { + return null; } - self.fd = fd; - self.emit('open', fd); - self._read(); - }) + return match.slice(1); + }; } - function WriteStream (path, options) { - if (!(this instanceof WriteStream)) return new WriteStream(path, options); + var capture = memoize('capture', pattern, options, match); + return capture(str); +}; - Stream.call(this); +/** + * Create a regular expression from the given glob `pattern`. + * + * ```js + * var nm = require('nanomatch'); + * nm.makeRe(pattern[, options]); + * + * console.log(nm.makeRe('*.js')); + * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ + * ``` + * @param {String} `pattern` A glob pattern to convert to regex. + * @param {Object} `options` See available [options](#options) for changing how matches are performed. + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ - this.path = path; - this.fd = null; - this.writable = true; +nanomatch.makeRe = function(pattern, options) { + if (pattern instanceof RegExp) { + return pattern; + } - this.flags = 'w'; - this.encoding = 'binary'; - this.mode = 438; /*=0666*/ - this.bytesWritten = 0; + if (typeof pattern !== 'string') { + throw new TypeError('expected pattern to be a string'); + } - options = options || {}; + if (pattern.length > MAX_LENGTH) { + throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); + } - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } + function makeRe() { + var opts = utils.extend({wrap: false}, options); + var res = nanomatch.create(pattern, opts); + var regex = toRegex(res.output, opts); + Object.defineProperty(regex, 'result', { + configurable: true, + enumerable: false, + value: res + }); + return regex; + } - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.start < 0) { - throw new Error('start must be >= zero'); - } + return memoize('makeRe', pattern, options, makeRe); +}; - this.pos = this.start; - } +/** + * Parses the given glob `pattern` and returns an object with the compiled `output` + * and optional source `map`. + * + * ```js + * var nm = require('nanomatch'); + * nm.create(pattern[, options]); + * + * console.log(nm.create('abc/*.js')); + * // { options: { source: 'string', sourcemap: true }, + * // state: {}, + * // compilers: + * // { ... }, + * // output: '(\\.[\\\\\\/])?abc\\/(?!\\.)(?=.)[^\\/]*?\\.js', + * // ast: + * // { type: 'root', + * // errors: [], + * // nodes: + * // [ ... ], + * // dot: false, + * // input: 'abc/*.js' }, + * // parsingErrors: [], + * // map: + * // { version: 3, + * // sources: [ 'string' ], + * // names: [], + * // mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE', + * // sourcesContent: [ 'abc/*.js' ] }, + * // position: { line: 1, column: 28 }, + * // content: {}, + * // files: {}, + * // idx: 6 } + * ``` + * @param {String} `pattern` Glob pattern to parse and compile. + * @param {Object} `options` Any [options](#options) to change how parsing and compiling is performed. + * @return {Object} Returns an object with the parsed AST, compiled string and optional source map. + * @api public + */ - this.busy = false; - this._queue = []; +nanomatch.create = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } + function create() { + return nanomatch.compile(nanomatch.parse(pattern, options), options); + } + return memoize('create', pattern, options, create); +}; - if (this.fd === null) { - this._open = fs.open; - this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); - this.flush(); - } +/** + * Parse the given `str` with the given `options`. + * + * ```js + * var nm = require('nanomatch'); + * nm.parse(pattern[, options]); + * + * var ast = nm.parse('a/{b,c}/d'); + * console.log(ast); + * // { type: 'root', + * // errors: [], + * // input: 'a/{b,c}/d', + * // nodes: + * // [ { type: 'bos', val: '' }, + * // { type: 'text', val: 'a/' }, + * // { type: 'brace', + * // nodes: + * // [ { type: 'brace.open', val: '{' }, + * // { type: 'text', val: 'b,c' }, + * // { type: 'brace.close', val: '}' } ] }, + * // { type: 'text', val: '/d' }, + * // { type: 'eos', val: '' } ] } + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {Object} Returns an AST + * @api public + */ + +nanomatch.parse = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); } -} + function parse() { + var snapdragon = utils.instantiate(null, options); + parsers(snapdragon, options); -/***/ }), -/* 135 */ -/***/ (function(module, exports, __webpack_require__) { + var ast = snapdragon.parse(pattern, options); + utils.define(ast, 'snapdragon', snapdragon); + ast.input = pattern; + return ast; + } -var fs = __webpack_require__(16), - path = __webpack_require__(7); + return memoize('parse', pattern, options, parse); +}; -module.exports = ncp; -ncp.ncp = ncp; +/** + * Compile the given `ast` or string with the given `options`. + * + * ```js + * var nm = require('nanomatch'); + * nm.compile(ast[, options]); + * + * var ast = nm.parse('a/{b,c}/d'); + * console.log(nm.compile(ast)); + * // { options: { source: 'string' }, + * // state: {}, + * // compilers: + * // { eos: [Function], + * // noop: [Function], + * // bos: [Function], + * // brace: [Function], + * // 'brace.open': [Function], + * // text: [Function], + * // 'brace.close': [Function] }, + * // output: [ 'a/(b|c)/d' ], + * // ast: + * // { ... }, + * // parsingErrors: [] } + * ``` + * @param {Object|String} `ast` + * @param {Object} `options` + * @return {Object} Returns an object that has an `output` property with the compiled string. + * @api public + */ -function ncp (source, dest, options, callback) { - var cback = callback; +nanomatch.compile = function(ast, options) { + if (typeof ast === 'string') { + ast = nanomatch.parse(ast, options); + } - if (!callback) { - cback = options; - options = {}; + function compile() { + var snapdragon = utils.instantiate(ast, options); + compilers(snapdragon, options); + return snapdragon.compile(ast, options); } - var basePath = process.cwd(), - currentPath = path.resolve(basePath, source), - targetPath = path.resolve(basePath, dest), - filter = options.filter, - rename = options.rename, - transform = options.transform, - clobber = options.clobber !== false, - modified = options.modified, - dereference = options.dereference, - errs = null, - started = 0, - finished = 0, - running = 0, - limit = options.limit || ncp.limit || 16; + return memoize('compile', ast.input, options, compile); +}; - limit = (limit < 1) ? 1 : (limit > 512) ? 512 : limit; +/** + * Clear the regex cache. + * + * ```js + * nm.clearCache(); + * ``` + * @api public + */ - startCopy(currentPath); - - function startCopy(source) { - started++; - if (filter) { - if (filter instanceof RegExp) { - if (!filter.test(source)) { - return cb(true); +nanomatch.clearCache = function() { + nanomatch.cache.__data__ = {}; +}; + +/** + * Compose a matcher function with the given patterns. + * This allows matcher functions to be compiled once and + * called multiple times. + */ + +function compose(patterns, options, matcher) { + var matchers; + + return memoize('compose', String(patterns), options, function() { + return function(file) { + // delay composition until it's invoked the first time, + // after that it won't be called again + if (!matchers) { + matchers = []; + for (var i = 0; i < patterns.length; i++) { + matchers.push(matcher(patterns[i], options)); } } - else if (typeof filter === 'function') { - if (!filter(source)) { - return cb(true); + + var len = matchers.length; + while (len--) { + if (matchers[len](file) === true) { + return true; } } - } - return getStats(source); - } + return false; + }; + }); +} - function getStats(source) { - var stat = dereference ? fs.stat : fs.lstat; - if (running >= limit) { - return setImmediate(function () { - getStats(source); - }); - } - running++; - stat(source, function (err, stats) { - var item = {}; - if (err) { - return onError(err); - } +/** + * Memoize a generated regex or function. A unique key is generated + * from the `type` (usually method name), the `pattern`, and + * user-defined options. + */ - // We need to get the mode from the stats object and preserve it. - item.name = source; - item.mode = stats.mode; - item.mtime = stats.mtime; //modified time - item.atime = stats.atime; //access time +function memoize(type, pattern, options, fn) { + var key = utils.createKey(type + '=' + pattern, options); - if (stats.isDirectory()) { - return onDir(item); - } - else if (stats.isFile()) { - return onFile(item); - } - else if (stats.isSymbolicLink()) { - // Symlinks don't really need to know about the mode. - return onLink(source); - } - }); + if (options && options.cache === false) { + return fn(pattern, options); } - function onFile(file) { - var target = file.name.replace(currentPath, targetPath); - if(rename) { - target = rename(target); - } - isWritable(target, function (writable) { - if (writable) { - return copyFile(file, target); - } - if(clobber) { - rmFile(target, function () { - copyFile(file, target); - }); - } - if (modified) { - var stat = dereference ? fs.stat : fs.lstat; - stat(target, function(err, stats) { - //if souce modified time greater to target modified time copy file - if (file.mtime.getTime()>stats.mtime.getTime()) - copyFile(file, target); - else return cb(); - }); - } - else { - return cb(); - } - }); + if (cache.has(type, key)) { + return cache.get(type, key); } - function copyFile(file, target) { - var readStream = fs.createReadStream(file.name), - writeStream = fs.createWriteStream(target, { mode: file.mode }); - - readStream.on('error', onError); - writeStream.on('error', onError); - - if(transform) { - transform(readStream, writeStream, file); - } else { - writeStream.on('open', function() { - readStream.pipe(writeStream); - }); - } - writeStream.once('finish', function() { - if (modified) { - //target file modified date sync. - fs.utimesSync(target, file.atime, file.mtime); - cb(); - } - else cb(); - }); - } + var val = fn(pattern, options); + cache.set(type, key, val); + return val; +} - function rmFile(file, done) { - fs.unlink(file, function (err) { - if (err) { - return onError(err); - } - return done(); - }); - } +/** + * Expose compiler, parser and cache on `nanomatch` + */ - function onDir(dir) { - var target = dir.name.replace(currentPath, targetPath); - isWritable(target, function (writable) { - if (writable) { - return mkDir(dir, target); - } - copyDir(dir.name); - }); - } +nanomatch.compilers = compilers; +nanomatch.parsers = parsers; +nanomatch.cache = cache; - function mkDir(dir, target) { - fs.mkdir(target, dir.mode, function (err) { - if (err) { - return onError(err); - } - copyDir(dir.name); - }); - } +/** + * Expose `nanomatch` + * @type {Function} + */ - function copyDir(dir) { - fs.readdir(dir, function (err, items) { - if (err) { - return onError(err); - } - items.forEach(function (item) { - startCopy(path.join(dir, item)); - }); - return cb(); - }); - } +module.exports = nanomatch; - function onLink(link) { - var target = link.replace(currentPath, targetPath); - fs.readlink(link, function (err, resolvedPath) { - if (err) { - return onError(err); - } - checkLink(resolvedPath, target); - }); - } - function checkLink(resolvedPath, target) { - if (dereference) { - resolvedPath = path.resolve(basePath, resolvedPath); - } - isWritable(target, function (writable) { - if (writable) { - return makeLink(resolvedPath, target); - } - fs.readlink(target, function (err, targetDest) { - if (err) { - return onError(err); - } - if (dereference) { - targetDest = path.resolve(basePath, targetDest); - } - if (targetDest === resolvedPath) { - return cb(); - } - return rmFile(target, function () { - makeLink(resolvedPath, target); - }); - }); - }); - } +/***/ }), +/* 150 */ +/***/ (function(module, exports, __webpack_require__) { - function makeLink(linkPath, target) { - fs.symlink(linkPath, target, function (err) { - if (err) { - return onError(err); - } - return cb(); - }); - } +"use strict"; +/*! + * arr-diff + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ - function isWritable(path, done) { - fs.lstat(path, function (err) { - if (err) { - if (err.code === 'ENOENT') return done(true); - return done(false); - } - return done(false); - }); + + +module.exports = function diff(arr/*, arrays*/) { + var len = arguments.length; + var idx = 0; + while (++idx < len) { + arr = diffArray(arr, arguments[idx]); } + return arr; +}; - function onError(err) { - if (options.stopOnError) { - return cback(err); - } - else if (!errs && options.errs) { - errs = fs.createWriteStream(options.errs); - } - else if (!errs) { - errs = []; - } - if (typeof errs.write === 'undefined') { - errs.push(err); - } - else { - errs.write(err.stack + '\n\n'); - } - return cb(); +function diffArray(one, two) { + if (!Array.isArray(two)) { + return one.slice(); } - function cb(skipped) { - if (!skipped) running--; - finished++; - if ((started === finished) && (running === 0)) { - if (cback !== undefined ) { - return errs ? cback(errs) : cback(null); + var tlen = two.length + var olen = one.length; + var idx = -1; + var arr = []; + + while (++idx < olen) { + var ele = one[idx]; + + var hasEle = false; + for (var i = 0; i < tlen; i++) { + var val = two[i]; + + if (ele === val) { + hasEle = true; + break; } } + + if (hasEle === false) { + arr.push(ele); + } } + return arr; } - - /***/ }), -/* 136 */ +/* 151 */ /***/ (function(module, exports, __webpack_require__) { -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var pathModule = __webpack_require__(7); -var isWindows = process.platform === 'win32'; -var fs = __webpack_require__(16); +"use strict"; +/*! + * object.pick + * + * Copyright (c) 2014-2015 Jon Schlinkert, contributors. + * Licensed under the MIT License + */ -// JavaScript implementation of realpath, ported from node pre-v6 -var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); -function rethrow() { - // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and - // is fairly slow to generate. - var callback; - if (DEBUG) { - var backtrace = new Error; - callback = debugCallback; - } else - callback = missingCallback; +var isObject = __webpack_require__(30); - return callback; +module.exports = function pick(obj, keys) { + if (!isObject(obj) && typeof obj !== 'function') { + return {}; + } - function debugCallback(err) { - if (err) { - backtrace.message = err.message; - err = backtrace; - missingCallback(err); + var res = {}; + if (typeof keys === 'string') { + if (keys in obj) { + res[keys] = obj[keys]; } + return res; } - function missingCallback(err) { - if (err) { - if (process.throwDeprecation) - throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs - else if (!process.noDeprecation) { - var msg = 'fs: missing callback ' + (err.stack || err.message); - if (process.traceDeprecation) - console.trace(msg); - else - console.error(msg); - } + var len = keys.length; + var idx = -1; + + while (++idx < len) { + var key = keys[idx]; + if (key in obj) { + res[key] = obj[key]; } } -} + return res; +}; -function maybeCallback(cb) { - return typeof cb === 'function' ? cb : rethrow(); -} -var normalize = pathModule.normalize; +/***/ }), +/* 152 */ +/***/ (function(module, exports, __webpack_require__) { -// Regexp that finds the next partion of a (partial) path -// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] -if (isWindows) { - var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; -} else { - var nextPartRe = /(.*?)(?:[\/]+|$)/g; -} +"use strict"; -// Regex to find the device root, including trailing slash. E.g. 'c:\\'. -if (isWindows) { - var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; -} else { - var splitRootRe = /^[\/]*/; + +/** + * Module dependencies + */ + +var extend = __webpack_require__(20); +var unique = __webpack_require__(65); +var toRegex = __webpack_require__(43); + +/** + * Local dependencies + */ + +var compilers = __webpack_require__(153); +var parsers = __webpack_require__(155); +var Extglob = __webpack_require__(428); +var utils = __webpack_require__(156); +var MAX_LENGTH = 1024 * 64; + +/** + * Convert the given `extglob` pattern into a regex-compatible string. Returns + * an object with the compiled result and the parsed AST. + * + * ```js + * var extglob = require('extglob'); + * console.log(extglob('*.!(*a)')); + * //=> '(?!\\.)[^/]*?\\.(?!(?!\\.)[^/]*?a\\b).*?' + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {String} + * @api public + */ + +function extglob(pattern, options) { + return extglob.create(pattern, options).output; } -exports.realpathSync = function realpathSync(p, cache) { - // make p is absolute - p = pathModule.resolve(p); +/** + * Takes an array of strings and an extglob pattern and returns a new + * array that contains only the strings that match the pattern. + * + * ```js + * var extglob = require('extglob'); + * console.log(extglob.match(['a.a', 'a.b', 'a.c'], '*.!(*a)')); + * //=> ['a.b', 'a.c'] + * ``` + * @param {Array} `list` Array of strings to match + * @param {String} `pattern` Extglob pattern + * @param {Object} `options` + * @return {Array} Returns an array of matches + * @api public + */ - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return cache[p]; +extglob.match = function(list, pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected pattern to be a string'); } - var original = p, - seenLinks = {}, - knownHard = {}; + list = utils.arrayify(list); + var isMatch = extglob.matcher(pattern, options); + var len = list.length; + var idx = -1; + var matches = []; - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; + while (++idx < len) { + var ele = list[idx]; - start(); + if (isMatch(ele)) { + matches.push(ele); + } + } - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; + // if no options were passed, uniquify results and return + if (typeof options === 'undefined') { + return unique(matches); + } - // On windows, check that the root exists. On unix there is no need. - if (isWindows && !knownHard[base]) { - fs.lstatSync(base); - knownHard[base] = true; + if (matches.length === 0) { + if (options.failglob === true) { + throw new Error('no matches found for "' + pattern + '"'); + } + if (options.nonull === true || options.nullglob === true) { + return [pattern.split('\\').join('')]; } } - // walk down the path, swapping out linked pathparts for their real - // values - // NB: p.length changes. - while (pos < p.length) { - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; + return options.nodupes !== false ? unique(matches) : matches; +}; - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - continue; - } +/** + * Returns true if the specified `string` matches the given + * extglob `pattern`. + * + * ```js + * var extglob = require('extglob'); + * + * console.log(extglob.isMatch('a.a', '*.!(*a)')); + * //=> false + * console.log(extglob.isMatch('a.b', '*.!(*a)')); + * //=> true + * ``` + * @param {String} `string` String to match + * @param {String} `pattern` Extglob pattern + * @param {String} `options` + * @return {Boolean} + * @api public + */ - var resolvedLink; - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // some known symbolic link. no need to stat again. - resolvedLink = cache[base]; - } else { - var stat = fs.lstatSync(base); - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - continue; - } +extglob.isMatch = function(str, pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected pattern to be a string'); + } - // read the link if it wasn't read before - // dev/ino always return 0 on windows, so skip the check. - var linkTarget = null; - if (!isWindows) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - linkTarget = seenLinks[id]; - } - } - if (linkTarget === null) { - fs.statSync(base); - linkTarget = fs.readlinkSync(base); - } - resolvedLink = pathModule.resolve(previous, linkTarget); - // track this, if given a cache. - if (cache) cache[base] = resolvedLink; - if (!isWindows) seenLinks[id] = linkTarget; - } + if (typeof str !== 'string') { + throw new TypeError('expected a string'); + } - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); + if (pattern === str) { + return true; } - if (cache) cache[original] = p; + if (pattern === '' || pattern === ' ' || pattern === '.') { + return pattern === str; + } - return p; + var isMatch = utils.memoize('isMatch', pattern, options, extglob.matcher); + return isMatch(str); }; +/** + * Returns true if the given `string` contains the given pattern. Similar to `.isMatch` but + * the pattern can match any part of the string. + * + * ```js + * var extglob = require('extglob'); + * console.log(extglob.contains('aa/bb/cc', '*b')); + * //=> true + * console.log(extglob.contains('aa/bb/cc', '*d')); + * //=> false + * ``` + * @param {String} `str` The string to match. + * @param {String} `pattern` Glob pattern to use for matching. + * @param {Object} `options` + * @return {Boolean} Returns true if the patter matches any part of `str`. + * @api public + */ -exports.realpath = function realpath(p, cache, cb) { - if (typeof cb !== 'function') { - cb = maybeCallback(cache); - cache = null; +extglob.contains = function(str, pattern, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string'); } - // make p is absolute - p = pathModule.resolve(p); + if (pattern === '' || pattern === ' ' || pattern === '.') { + return pattern === str; + } - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return process.nextTick(cb.bind(null, null, cache[p])); + var opts = extend({}, options, {contains: true}); + opts.strictClose = false; + opts.strictOpen = false; + return extglob.isMatch(str, pattern, opts); +}; + +/** + * Takes an extglob pattern and returns a matcher function. The returned + * function takes the string to match as its only argument. + * + * ```js + * var extglob = require('extglob'); + * var isMatch = extglob.matcher('*.!(*a)'); + * + * console.log(isMatch('a.a')); + * //=> false + * console.log(isMatch('a.b')); + * //=> true + * ``` + * @param {String} `pattern` Extglob pattern + * @param {String} `options` + * @return {Boolean} + * @api public + */ + +extglob.matcher = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected pattern to be a string'); } - var original = p, - seenLinks = {}, - knownHard = {}; + function matcher() { + var re = extglob.makeRe(pattern, options); + return function(str) { + return re.test(str); + }; + } - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; + return utils.memoize('matcher', pattern, options, matcher); +}; - start(); +/** + * Convert the given `extglob` pattern into a regex-compatible string. Returns + * an object with the compiled result and the parsed AST. + * + * ```js + * var extglob = require('extglob'); + * console.log(extglob.create('*.!(*a)').output); + * //=> '(?!\\.)[^/]*?\\.(?!(?!\\.)[^/]*?a\\b).*?' + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {String} + * @api public + */ - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; +extglob.create = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected pattern to be a string'); + } - // On windows, check that the root exists. On unix there is no need. - if (isWindows && !knownHard[base]) { - fs.lstat(base, function(err) { - if (err) return cb(err); - knownHard[base] = true; - LOOP(); - }); - } else { - process.nextTick(LOOP); - } + function create() { + var ext = new Extglob(options); + var ast = ext.parse(pattern, options); + return ext.compile(ast, options); } - // walk down the path, swapping out linked pathparts for their real - // values - function LOOP() { - // stop if scanned past end of path - if (pos >= p.length) { - if (cache) cache[original] = p; - return cb(null, p); - } + return utils.memoize('create', pattern, options, create); +}; - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; +/** + * Returns an array of matches captured by `pattern` in `string`, or `null` + * if the pattern did not match. + * + * ```js + * var extglob = require('extglob'); + * extglob.capture(pattern, string[, options]); + * + * console.log(extglob.capture('test/*.js', 'test/foo.js')); + * //=> ['foo'] + * console.log(extglob.capture('test/*.js', 'foo/bar.css')); + * //=> null + * ``` + * @param {String} `pattern` Glob pattern to use for matching. + * @param {String} `string` String to match + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`. + * @api public + */ - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - return process.nextTick(LOOP); - } +extglob.capture = function(pattern, str, options) { + var re = extglob.makeRe(pattern, extend({capture: true}, options)); - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // known symbolic link. no need to stat again. - return gotResolvedLink(cache[base]); - } + function match() { + return function(string) { + var match = re.exec(string); + if (!match) { + return null; + } - return fs.lstat(base, gotStat); + return match.slice(1); + }; } - function gotStat(err, stat) { - if (err) return cb(err); + var capture = utils.memoize('capture', pattern, options, match); + return capture(str); +}; - // if not a symlink, skip to the next path part - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - return process.nextTick(LOOP); - } +/** + * Create a regular expression from the given `pattern` and `options`. + * + * ```js + * var extglob = require('extglob'); + * var re = extglob.makeRe('*.!(*a)'); + * console.log(re); + * //=> /^[^\/]*?\.(?![^\/]*?a)[^\/]*?$/ + * ``` + * @param {String} `pattern` The pattern to convert to regex. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ - // stat & read the link if not read before - // call gotTarget as soon as the link target is known - // dev/ino always return 0 on windows, so skip the check. - if (!isWindows) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - return gotTarget(null, seenLinks[id], base); - } - } - fs.stat(base, function(err) { - if (err) return cb(err); +extglob.makeRe = function(pattern, options) { + if (pattern instanceof RegExp) { + return pattern; + } - fs.readlink(base, function(err, target) { - if (!isWindows) seenLinks[id] = target; - gotTarget(err, target); - }); - }); + if (typeof pattern !== 'string') { + throw new TypeError('expected pattern to be a string'); } - function gotTarget(err, target, base) { - if (err) return cb(err); + if (pattern.length > MAX_LENGTH) { + throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); + } - var resolvedLink = pathModule.resolve(previous, target); - if (cache) cache[base] = resolvedLink; - gotResolvedLink(resolvedLink); + function makeRe() { + var opts = extend({strictErrors: false}, options); + if (opts.strictErrors === true) opts.strict = true; + var res = extglob.create(pattern, opts); + return toRegex(res.output, opts); } - function gotResolvedLink(resolvedLink) { - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); + var regex = utils.memoize('makeRe', pattern, options, makeRe); + if (regex.source.length > MAX_LENGTH) { + throw new SyntaxError('potentially malicious regex detected'); } + + return regex; }; +/** + * Cache + */ -/***/ }), -/* 137 */ -/***/ (function(module, exports, __webpack_require__) { +extglob.cache = utils.cache; +extglob.clearCache = function() { + extglob.cache.__data__ = {}; +}; -var concatMap = __webpack_require__(138); -var balanced = __webpack_require__(139); +/** + * Expose `Extglob` constructor, parsers and compilers + */ -module.exports = expandTop; - -var escSlash = '\0SLASH'+Math.random()+'\0'; -var escOpen = '\0OPEN'+Math.random()+'\0'; -var escClose = '\0CLOSE'+Math.random()+'\0'; -var escComma = '\0COMMA'+Math.random()+'\0'; -var escPeriod = '\0PERIOD'+Math.random()+'\0'; +extglob.Extglob = Extglob; +extglob.compilers = compilers; +extglob.parsers = parsers; -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); -} +/** + * Expose `extglob` + * @type {Function} + */ -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); -} +module.exports = extglob; -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); -} +/***/ }), +/* 153 */ +/***/ (function(module, exports, __webpack_require__) { -// Basically just str.split(","), but handling cases -// where we have nested braced sections, which should be -// treated as individual members, like {a,{b,c},d} -function parseCommaParts(str) { - if (!str) - return ['']; +"use strict"; - var parts = []; - var m = balanced('{', '}', str); - if (!m) - return str.split(','); +var brackets = __webpack_require__(154); - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); +/** + * Extglob compilers + */ - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); +module.exports = function(extglob) { + function star() { + if (typeof extglob.options.star === 'function') { + return extglob.options.star.apply(this, arguments); + } + if (typeof extglob.options.star === 'string') { + return extglob.options.star; + } + return '.*?'; } - parts.push.apply(parts, p); + /** + * Use `expand-brackets` compilers + */ - return parts; -} + extglob.use(brackets.compilers); + extglob.compiler -function expandTop(str) { - if (!str) - return []; + /** + * Escaped: "\\*" + */ - // I don't know why Bash 4.3 does this, but it does. - // Anything starting with {} will have the first two bytes preserved - // but *only* at the top level, so {},a}b will not expand to anything, - // but a{},b}c will be expanded to [a}c,abc]. - // One could argue that this is a bug in Bash, but since the goal of - // this module is to match Bash's rules, we escape a leading {} - if (str.substr(0, 2) === '{}') { - str = '\\{\\}' + str.substr(2); - } + .set('escape', function(node) { + return this.emit(node.val, node); + }) - return expand(escapeBraces(str), true).map(unescapeBraces); -} + /** + * Dot: "." + */ -function identity(e) { - return e; -} + .set('dot', function(node) { + return this.emit('\\' + node.val, node); + }) -function embrace(str) { - return '{' + str + '}'; -} -function isPadded(el) { - return /^-?0\d/.test(el); -} + /** + * Question mark: "?" + */ -function lte(i, y) { - return i <= y; -} -function gte(i, y) { - return i >= y; -} + .set('qmark', function(node) { + var val = '[^\\\\/.]'; + var prev = this.prev(); -function expand(str, isTop) { - var expansions = []; + if (node.parsed.slice(-1) === '(') { + var ch = node.rest.charAt(0); + if (ch !== '!' && ch !== '=' && ch !== ':') { + return this.emit(val, node); + } + return this.emit(node.val, node); + } - var m = balanced('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; + if (prev.type === 'text' && prev.val) { + return this.emit(val, node); + } - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,.*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str); - } - return [str]; - } + if (node.val.length > 1) { + val += '{' + node.val.length + '}'; + } + return this.emit(val, node); + }) - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], false).map(embrace); - if (n.length === 1) { - var post = m.post.length - ? expand(m.post, false) - : ['']; - return post.map(function(p) { - return m.pre + n[0] + p; - }); + /** + * Plus: "+" + */ + + .set('plus', function(node) { + var prev = node.parsed.slice(-1); + if (prev === ']' || prev === ')') { + return this.emit(node.val, node); } - } - } + var ch = this.output.slice(-1); + if (!this.output || (/[?*+]/.test(ch) && node.parent.type !== 'bracket')) { + return this.emit('\\+', node); + } + if (/\w/.test(ch) && !node.inside) { + return this.emit('+\\+?', node); + } + return this.emit('+', node); + }) - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. + /** + * Star: "*" + */ - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, false) - : ['']; + .set('star', function(node) { + var prev = this.prev(); + var prefix = prev.type !== 'text' && prev.type !== 'escape' + ? '(?!\\.)' + : ''; - var N; + return this.emit(prefix + star.call(this, node), node); + }) - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length) - var incr = n.length == 3 - ? Math.abs(numeric(n[2])) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; - } - var pad = n.some(isPadded); + /** + * Parens + */ - N = []; + .set('paren', function(node) { + return this.mapVisit(node.nodes); + }) + .set('paren.open', function(node) { + var capture = this.options.capture ? '(' : ''; - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; - } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; + switch (node.parent.prefix) { + case '!': + case '^': + return this.emit(capture + '(?:(?!(?:', node); + case '*': + case '+': + case '?': + case '@': + return this.emit(capture + '(?:', node); + default: { + var val = node.val; + if (this.options.bash === true) { + val = '\\' + val; + } else if (!this.options.capture && val === '(' && node.parent.rest[0] !== '?') { + val += '?:'; } + + return this.emit(val, node); } } - N.push(c); - } - } else { - N = concatMap(n, function(el) { return expand(el, false) }); - } - - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); - } - } - - return expansions; -} - - + }) + .set('paren.close', function(node) { + var capture = this.options.capture ? ')' : ''; + + switch (node.prefix) { + case '!': + case '^': + var prefix = /^(\)|$)/.test(node.rest) ? '$' : ''; + var str = star.call(this, node); + + // if the extglob has a slash explicitly defined, we know the user wants + // to match slashes, so we need to ensure the "star" regex allows for it + if (node.parent.hasSlash && !this.options.star && this.options.slash !== false) { + str = '.*?'; + } -/***/ }), -/* 138 */ -/***/ (function(module, exports) { + return this.emit(prefix + ('))' + str + ')') + capture, node); + case '*': + case '+': + case '?': + return this.emit(')' + node.prefix + capture, node); + case '@': + return this.emit(')' + capture, node); + default: { + var val = (this.options.bash === true ? '\\' : '') + ')'; + return this.emit(val, node); + } + } + }) -module.exports = function (xs, fn) { - var res = []; - for (var i = 0; i < xs.length; i++) { - var x = fn(xs[i], i); - if (isArray(x)) res.push.apply(res, x); - else res.push(x); - } - return res; -}; + /** + * Text + */ -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; + .set('text', function(node) { + var val = node.val.replace(/[\[\]]/g, '\\$&'); + return this.emit(val, node); + }); }; /***/ }), -/* 139 */ +/* 154 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = balanced; -function balanced(a, b, str) { - if (a instanceof RegExp) a = maybeMatch(a, str); - if (b instanceof RegExp) b = maybeMatch(b, str); - var r = range(a, b, str); +/** + * Local dependencies + */ - return r && { - start: r[0], - end: r[1], - pre: str.slice(0, r[0]), - body: str.slice(r[0] + a.length, r[1]), - post: str.slice(r[1] + b.length) - }; -} +var compilers = __webpack_require__(417); +var parsers = __webpack_require__(419); -function maybeMatch(reg, str) { - var m = str.match(reg); - return m ? m[0] : null; -} +/** + * Module dependencies + */ -balanced.range = range; -function range(a, b, str) { - var begs, beg, left, right, result; - var ai = str.indexOf(a); - var bi = str.indexOf(b, ai + 1); - var i = ai; +var debug = __webpack_require__(106)('expand-brackets'); +var extend = __webpack_require__(20); +var Snapdragon = __webpack_require__(66); +var toRegex = __webpack_require__(43); - if (ai >= 0 && bi > 0) { - begs = []; - left = str.length; +/** + * Parses the given POSIX character class `pattern` and returns a + * string that can be used for creating regular expressions for matching. + * + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} + * @api public + */ - while (i >= 0 && !result) { - if (i == ai) { - begs.push(i); - ai = str.indexOf(a, i + 1); - } else if (begs.length == 1) { - result = [ begs.pop(), bi ]; - } else { - beg = begs.pop(); - if (beg < left) { - left = beg; - right = bi; - } +function brackets(pattern, options) { + debug('initializing from <%s>', __filename); + var res = brackets.create(pattern, options); + return res.output; +} - bi = str.indexOf(b, i + 1); - } +/** + * Takes an array of strings and a POSIX character class pattern, and returns a new + * array with only the strings that matched the pattern. + * + * ```js + * var brackets = require('expand-brackets'); + * console.log(brackets.match(['1', 'a', 'ab'], '[[:alpha:]]')); + * //=> ['a'] + * + * console.log(brackets.match(['1', 'a', 'ab'], '[[:alpha:]]+')); + * //=> ['a', 'ab'] + * ``` + * @param {Array} `arr` Array of strings to match + * @param {String} `pattern` POSIX character class pattern(s) + * @param {Object} `options` + * @return {Array} + * @api public + */ - i = ai < bi && ai >= 0 ? ai : bi; +brackets.match = function(arr, pattern, options) { + arr = [].concat(arr); + var opts = extend({}, options); + var isMatch = brackets.matcher(pattern, opts); + var len = arr.length; + var idx = -1; + var res = []; + + while (++idx < len) { + var ele = arr[idx]; + if (isMatch(ele)) { + res.push(ele); + } + } + + if (res.length === 0) { + if (opts.failglob === true) { + throw new Error('no matches found for "' + pattern + '"'); } - if (begs.length) { - result = [ left, right ]; + if (opts.nonull === true || opts.nullglob === true) { + return [pattern.split('\\').join('')]; } } + return res; +}; - return result; -} +/** + * Returns true if the specified `string` matches the given + * brackets `pattern`. + * + * ```js + * var brackets = require('expand-brackets'); + * + * console.log(brackets.isMatch('a.a', '[[:alpha:]].[[:alpha:]]')); + * //=> true + * console.log(brackets.isMatch('1.2', '[[:alpha:]].[[:alpha:]]')); + * //=> false + * ``` + * @param {String} `string` String to match + * @param {String} `pattern` Poxis pattern + * @param {String} `options` + * @return {Boolean} + * @api public + */ +brackets.isMatch = function(str, pattern, options) { + return brackets.matcher(pattern, options)(str); +}; -/***/ }), -/* 140 */ -/***/ (function(module, exports) { +/** + * Takes a POSIX character class pattern and returns a matcher function. The returned + * function takes the string to match as its only argument. + * + * ```js + * var brackets = require('expand-brackets'); + * var isMatch = brackets.matcher('[[:lower:]].[[:upper:]]'); + * + * console.log(isMatch('a.a')); + * //=> false + * console.log(isMatch('a.A')); + * //=> true + * ``` + * @param {String} `pattern` Poxis pattern + * @param {String} `options` + * @return {Boolean} + * @api public + */ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); +brackets.matcher = function(pattern, options) { + var re = brackets.makeRe(pattern, options); + return function(str) { + return re.test(str); }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} +}; +/** + * Create a regular expression from the given `pattern`. + * + * ```js + * var brackets = require('expand-brackets'); + * var re = brackets.makeRe('[[:alpha:]]'); + * console.log(re); + * //=> /^(?:[a-zA-Z])$/ + * ``` + * @param {String} `pattern` The pattern to convert to regex. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ -/***/ }), -/* 141 */ -/***/ (function(module, exports, __webpack_require__) { +brackets.makeRe = function(pattern, options) { + var res = brackets.create(pattern, options); + var opts = extend({strictErrors: false}, options); + return toRegex(res.output, opts); +}; -module.exports = globSync -globSync.GlobSync = GlobSync +/** + * Parses the given POSIX character class `pattern` and returns an object + * with the compiled `output` and optional source `map`. + * + * ```js + * var brackets = require('expand-brackets'); + * console.log(brackets('[[:alpha:]]')); + * // { options: { source: 'string' }, + * // input: '[[:alpha:]]', + * // state: {}, + * // compilers: + * // { eos: [Function], + * // noop: [Function], + * // bos: [Function], + * // not: [Function], + * // escape: [Function], + * // text: [Function], + * // posix: [Function], + * // bracket: [Function], + * // 'bracket.open': [Function], + * // 'bracket.inner': [Function], + * // 'bracket.literal': [Function], + * // 'bracket.close': [Function] }, + * // output: '[a-zA-Z]', + * // ast: + * // { type: 'root', + * // errors: [], + * // nodes: [ [Object], [Object], [Object] ] }, + * // parsingErrors: [] } + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} + * @api public + */ -var fs = __webpack_require__(16) -var rp = __webpack_require__(96) -var minimatch = __webpack_require__(86) -var Minimatch = minimatch.Minimatch -var Glob = __webpack_require__(43).Glob -var util = __webpack_require__(19) -var path = __webpack_require__(7) -var assert = __webpack_require__(57) -var isAbsolute = __webpack_require__(87) -var common = __webpack_require__(98) -var alphasort = common.alphasort -var alphasorti = common.alphasorti -var setopts = common.setopts -var ownProp = common.ownProp -var childrenIgnored = common.childrenIgnored -var isIgnored = common.isIgnored +brackets.create = function(pattern, options) { + var snapdragon = (options && options.snapdragon) || new Snapdragon(options); + compilers(snapdragon); + parsers(snapdragon); -function globSync (pattern, options) { - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') + var ast = snapdragon.parse(pattern, options); + ast.input = pattern; + var res = snapdragon.compile(ast, options); + res.input = pattern; + return res; +}; - return new GlobSync(pattern, options).found -} +/** + * Expose `brackets` constructor, parsers and compilers + */ -function GlobSync (pattern, options) { - if (!pattern) - throw new Error('must provide pattern') +brackets.compilers = compilers; +brackets.parsers = parsers; - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') +/** + * Expose `brackets` + * @type {Function} + */ - if (!(this instanceof GlobSync)) - return new GlobSync(pattern, options) +module.exports = brackets; - setopts(this, pattern, options) - if (this.noprocess) - return this +/***/ }), +/* 155 */ +/***/ (function(module, exports, __webpack_require__) { - var n = this.minimatch.set.length - this.matches = new Array(n) - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false) - } - this._finish() -} +"use strict"; -GlobSync.prototype._finish = function () { - assert(this instanceof GlobSync) - if (this.realpath) { - var self = this - this.matches.forEach(function (matchset, index) { - var set = self.matches[index] = Object.create(null) - for (var p in matchset) { - try { - p = self._makeAbs(p) - var real = rp.realpathSync(p, self.realpathCache) - set[real] = true - } catch (er) { - if (er.syscall === 'stat') - set[self._makeAbs(p)] = true - else - throw er - } - } - }) - } - common.finish(this) -} +var brackets = __webpack_require__(154); +var define = __webpack_require__(44); +var utils = __webpack_require__(156); -GlobSync.prototype._process = function (pattern, index, inGlobStar) { - assert(this instanceof GlobSync) +/** + * Characters to use in text regex (we want to "not" match + * characters that are matched by other parsers) + */ - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === 'string') { - n ++ - } - // now n is the index of the first one that is *not* a string. +var TEXT_REGEX = '([!@*?+]?\\(|\\)|[*?.+\\\\]|\\[:?(?=.*\\])|:?\\])+'; +var not = utils.createRegex(TEXT_REGEX); - // See if there's anything else - var prefix - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index) - return +/** + * Extglob parsers + */ - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break +function parsers(extglob) { + extglob.state = extglob.state || {}; - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/') - break - } + /** + * Use `expand-brackets` parsers + */ - var remain = pattern.slice(n) + extglob.use(brackets.parsers); + extglob.parser.sets.paren = extglob.parser.sets.paren || []; + extglob.parser - // get the list of entries. - var read - if (prefix === null) - read = '.' - else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { - if (!prefix || !isAbsolute(prefix)) - prefix = '/' + prefix - read = prefix - } else - read = prefix + /** + * Extglob open: "*(" + */ - var abs = this._makeAbs(read) + .capture('paren.open', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^([!@*?+])?\(/); + if (!m) return; - //if ignored, skip processing - if (childrenIgnored(this, read)) - return + var prev = this.prev(); + var prefix = m[1]; + var val = m[0]; - var isGlobStar = remain[0] === minimatch.GLOBSTAR - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar) -} + var open = pos({ + type: 'paren.open', + parsed: parsed, + val: val + }); + var node = pos({ + type: 'paren', + prefix: prefix, + nodes: [open] + }); -GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { - var entries = this._readdir(abs, inGlobStar) + // if nested negation extglobs, just cancel them out to simplify + if (prefix === '!' && prev.type === 'paren' && prev.prefix === '!') { + prev.prefix = '@'; + node.prefix = '@'; + } - // if the abs isn't a dir, then nothing can match! - if (!entries) - return + define(node, 'rest', this.input); + define(node, 'parsed', parsed); + define(node, 'parent', prev); + define(open, 'parent', node); - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0] - var negate = !!this.minimatch.negate - var rawGlob = pn._glob - var dotOk = this.dot || rawGlob.charAt(0) === '.' + this.push('paren', node); + prev.nodes.push(node); + }) - var matchedEntries = [] - for (var i = 0; i < entries.length; i++) { - var e = entries[i] - if (e.charAt(0) !== '.' || dotOk) { - var m - if (negate && !prefix) { - m = !e.match(pn) - } else { - m = e.match(pn) + /** + * Extglob close: ")" + */ + + .capture('paren.close', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\)/); + if (!m) return; + + var parent = this.pop('paren'); + var node = pos({ + type: 'paren.close', + rest: this.input, + parsed: parsed, + val: m[0] + }); + + if (!this.isType(parent, 'paren')) { + if (this.options.strict) { + throw new Error('missing opening paren: "("'); + } + node.escaped = true; + return node; } - if (m) - matchedEntries.push(e) - } - } - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return + node.prefix = parent.prefix; + parent.nodes.push(node); + define(node, 'parent', parent); + }) - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. + /** + * Escape: "\\." + */ - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) + .capture('escape', function() { + var pos = this.position(); + var m = this.match(/^\\(.)/); + if (!m) return; - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix.slice(-1) !== '/') - e = prefix + '/' + e - else - e = prefix + e - } - - if (e.charAt(0) === '/' && !this.nomount) { - e = path.join(this.root, e) - } - this._emitMatch(index, e) - } - // This was the last one, and no stats were needed - return - } - - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift() - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - var newPattern - if (prefix) - newPattern = [prefix, e] - else - newPattern = [e] - this._process(newPattern.concat(remain), index, inGlobStar) - } -} + return pos({ + type: 'escape', + val: m[0], + ch: m[1] + }); + }) + /** + * Question marks: "?" + */ -GlobSync.prototype._emitMatch = function (index, e) { - if (isIgnored(this, e)) - return + .capture('qmark', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\?+(?!\()/); + if (!m) return; + extglob.state.metachar = true; + return pos({ + type: 'qmark', + rest: this.input, + parsed: parsed, + val: m[0] + }); + }) - var abs = this._makeAbs(e) + /** + * Character parsers + */ - if (this.mark) - e = this._mark(e) + .capture('star', /^\*(?!\()/) + .capture('plus', /^\+(?!\()/) + .capture('dot', /^\./) + .capture('text', not); +}; - if (this.absolute) { - e = abs - } +/** + * Expose text regex string + */ - if (this.matches[index][e]) - return +module.exports.TEXT_REGEX = TEXT_REGEX; - if (this.nodir) { - var c = this.cache[abs] - if (c === 'DIR' || Array.isArray(c)) - return - } +/** + * Extglob parsers + */ - this.matches[index][e] = true +module.exports = parsers; - if (this.stat) - this._stat(e) -} +/***/ }), +/* 156 */ +/***/ (function(module, exports, __webpack_require__) { -GlobSync.prototype._readdirInGlobStar = function (abs) { - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false) +"use strict"; - var entries - var lstat - var stat - try { - lstat = fs.lstatSync(abs) - } catch (er) { - if (er.code === 'ENOENT') { - // lstat failed, doesn't exist - return null - } - } - var isSym = lstat && lstat.isSymbolicLink() - this.symlinks[abs] = isSym +var regex = __webpack_require__(64); +var Cache = __webpack_require__(107); - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && lstat && !lstat.isDirectory()) - this.cache[abs] = 'FILE' - else - entries = this._readdir(abs, false) +/** + * Utils + */ - return entries -} +var utils = module.exports; +var cache = utils.cache = new Cache(); -GlobSync.prototype._readdir = function (abs, inGlobStar) { - var entries +/** + * Cast `val` to an array + * @return {Array} + */ - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs) +utils.arrayify = function(val) { + if (!Array.isArray(val)) { + return [val]; + } + return val; +}; - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return null +/** + * Memoize a generated regex or function + */ - if (Array.isArray(c)) - return c - } +utils.memoize = function(type, pattern, options, fn) { + var key = utils.createKey(type + pattern, options); - try { - return this._readdirEntries(abs, fs.readdirSync(abs)) - } catch (er) { - this._readdirError(abs, er) - return null + if (cache.has(type, key)) { + return cache.get(type, key); } -} -GlobSync.prototype._readdirEntries = function (abs, entries) { - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i] - if (abs === '/') - e = abs + e - else - e = abs + '/' + e - this.cache[e] = true - } + var val = fn(pattern, options); + if (options && options.cache === false) { + return val; } - this.cache[abs] = entries + cache.set(type, key, val); + return val; +}; - // mark and cache dir-ness - return entries -} +/** + * Create the key to use for memoization. The key is generated + * by iterating over the options and concatenating key-value pairs + * to the pattern string. + */ -GlobSync.prototype._readdirError = function (f, er) { - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - var abs = this._makeAbs(f) - this.cache[abs] = 'FILE' - if (abs === this.cwdAbs) { - var error = new Error(er.code + ' invalid cwd ' + this.cwd) - error.path = this.cwd - error.code = er.code - throw error - } - break +utils.createKey = function(pattern, options) { + var key = pattern; + if (typeof options === 'undefined') { + return key; + } + for (var prop in options) { + key += ';' + prop + '=' + String(options[prop]); + } + return key; +}; - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false - break +/** + * Create the regex to use for matching text + */ - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false - if (this.strict) - throw er - if (!this.silent) - console.error('glob error', er) - break - } -} +utils.createRegex = function(str) { + var opts = {contains: true, strictClose: false}; + return regex(str, opts); +}; -GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { - var entries = this._readdir(abs, inGlobStar) +/***/ }), +/* 157 */ +/***/ (function(module, exports, __webpack_require__) { - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return +"use strict"; - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1) - var gspref = prefix ? [ prefix ] : [] - var noGlobStar = gspref.concat(remainWithoutGlobStar) - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false) +module.exports = asyncForEach; - var len = entries.length - var isSym = this.symlinks[abs] +/** + * Simultaneously processes all items in the given array. + * + * @param {array} array - The array to iterate over + * @param {function} iterator - The function to call for each item in the array + * @param {function} done - The function to call when all iterators have completed + */ +function asyncForEach (array, iterator, done) { + if (array.length === 0) { + // NOTE: Normally a bad idea to mix sync and async, but it's safe here because + // of the way that this method is currently used by DirectoryReader. + done(); + return; + } + + // Simultaneously process all items in the array. + let pending = array.length; + array.forEach(item => { + iterator(item, () => { + if (--pending === 0) { + done(); + } + }); + }); +} - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue +/***/ }), +/* 158 */ +/***/ (function(module, exports, __webpack_require__) { - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true) +"use strict"; - var below = gspref.concat(entries[i], remain) - this._process(below, index, true) - } +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Flatten nested arrays (max depth is 2) into a non-nested array of non-array items. + */ +function flatten(items) { + return items.reduce(function (collection, item) { return [].concat(collection, item); }, []); } +exports.flatten = flatten; +/** + * Returns max number from array. + */ +function max(items) { + return Math.max.apply(null, items); +} +exports.max = max; -GlobSync.prototype._processSimple = function (prefix, index) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var exists = this._stat(prefix) - - if (!this.matches[index]) - this.matches[index] = Object.create(null) - // If it doesn't exist, then just mark the lack of results - if (!exists) - return +/***/ }), +/* 159 */ +/***/ (function(module, exports, __webpack_require__) { - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) - } else { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' - } - } +"use strict"; - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') +const NestedError = __webpack_require__(160); - // Mark this as a match - this._emitMatch(index, prefix) +class CpFileError extends NestedError { + constructor(message, nested) { + super(message, nested); + Object.assign(this, nested); + this.name = 'CpFileError'; + } } -// Returns either 'DIR', 'FILE', or false -GlobSync.prototype._stat = function (f) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' - - if (f.length > this.maxLength) - return false - - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] +module.exports = CpFileError; - if (Array.isArray(c)) - c = 'DIR' - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return c +/***/ }), +/* 160 */ +/***/ (function(module, exports, __webpack_require__) { - if (needDir && c === 'FILE') - return false +var inherits = __webpack_require__(118); - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. - } +var NestedError = function (message, nested) { + this.nested = nested; - var exists - var stat = this.statCache[abs] - if (!stat) { - var lstat - try { - lstat = fs.lstatSync(abs) - } catch (er) { - if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { - this.statCache[abs] = false - return false - } + if (typeof message !== 'undefined') { + Object.defineProperty(this, 'message', { + value: message, + writable: true, + enumerable: false, + configurable: true + }); } - if (lstat && lstat.isSymbolicLink()) { - try { - stat = fs.statSync(abs) - } catch (er) { - stat = lstat - } + Error.captureStackTrace(this, this.constructor); + var oldStackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack'); + var stackDescriptor = buildStackDescriptor(oldStackDescriptor, nested); + Object.defineProperty(this, 'stack', stackDescriptor); +}; + +function buildStackDescriptor(oldStackDescriptor, nested) { + if (oldStackDescriptor.get) { + return { + get: function () { + var stack = oldStackDescriptor.get.call(this); + return buildCombinedStacks(stack, this.nested); + } + }; } else { - stat = lstat + var stack = oldStackDescriptor.value; + return { + value: buildCombinedStacks(stack, nested) + }; } - } - - this.statCache[abs] = stat - - var c = true - if (stat) - c = stat.isDirectory() ? 'DIR' : 'FILE' - - this.cache[abs] = this.cache[abs] || c - - if (needDir && c === 'FILE') - return false - - return c } -GlobSync.prototype._mark = function (p) { - return common.mark(this, p) +function buildCombinedStacks(stack, nested) { + if (nested) { + stack += '\nCaused By: ' + nested.stack; + } + return stack; } -GlobSync.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -} +inherits(NestedError, Error); +NestedError.prototype.name = 'NestedError'; + + +module.exports = NestedError; /***/ }), -/* 142 */ +/* 161 */ /***/ (function(module, exports, __webpack_require__) { -var wrappy = __webpack_require__(99) -var reqs = Object.create(null) -var once = __webpack_require__(100) +"use strict"; -module.exports = wrappy(inflight) -function inflight (key, cb) { - if (reqs[key]) { - reqs[key].push(cb) - return null - } else { - reqs[key] = [cb] - return makeres(key) - } -} +Object.defineProperty(exports, "__esModule", { + value: true +}); -function makeres (key) { - return once(function RES () { - var cbs = reqs[key] - var len = cbs.length - var args = slice(arguments) +var _cli = __webpack_require__(162); - // XXX It's somewhat ambiguous whether a new callback added in this - // pass should be queued for later execution if something in the - // list of callbacks throws, or if it should just be discarded. - // However, it's such an edge case that it hardly matters, and either - // choice is likely as surprising as the other. - // As it happens, we do go ahead and schedule it for later execution. - try { - for (var i = 0; i < len; i++) { - cbs[i].apply(null, args) - } - } finally { - if (cbs.length > len) { - // added more in the interim. - // de-zalgo, just in case, but don't call again. - cbs.splice(0, len) - process.nextTick(function () { - RES.apply(null, args) - }) - } else { - delete reqs[key] - } - } - }) -} +Object.defineProperty(exports, 'run', { + enumerable: true, + get: function () { + return _cli.run; + } +}); -function slice (args) { - var length = args.length - var array = [] +var _production = __webpack_require__(292); - for (var i = 0; i < length; i++) array[i] = args[i] - return array -} +Object.defineProperty(exports, 'buildProductionProjects', { + enumerable: true, + get: function () { + return _production.buildProductionProjects; + } +}); +Object.defineProperty(exports, 'prepareExternalProjectDependencies', { + enumerable: true, + get: function () { + return _production.prepareExternalProjectDependencies; + } +}); +var _workspaces = __webpack_require__(130); + +Object.defineProperty(exports, 'copyWorkspacePackages', { + enumerable: true, + get: function () { + return _workspaces.copyWorkspacePackages; + } +}); /***/ }), -/* 143 */ +/* 162 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const path = __webpack_require__(7); -const loadJsonFile = __webpack_require__(144); -const pathType = __webpack_require__(150); -module.exports = (fp, opts) => { - if (typeof fp !== 'string') { - opts = fp; - fp = '.'; - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.run = undefined; - opts = opts || {}; +let run = exports.run = (() => { + var _ref = _asyncToGenerator(function* (argv) { + // We can simplify this setup (and remove this extra handling) once Yarn + // starts forwarding the `--` directly to this script, see + // https://github.com/yarnpkg/yarn/blob/b2d3e1a8fe45ef376b716d597cc79b38702a9320/src/cli/index.js#L174-L182 + if (argv.includes('--')) { + _log.log.write(_chalk2.default.red(`Using "--" is not allowed, as it doesn't work with 'yarn kbn'.`)); + process.exit(1); + } + const options = (0, _getopts2.default)(argv, { + alias: { + e: 'exclude', + h: 'help', + i: 'include' + }, + boolean: ['prefer-offline', 'frozen-lockfile'] + }); + const args = options._; + if (options.help || args.length === 0) { + help(); + return; + } + // This `rootPath` is relative to `./dist/` as that's the location of the + // built version of this tool. + const rootPath = (0, _path.resolve)(__dirname, '../../../'); + const commandName = args[0]; + const extraArgs = args.slice(1); + const commandOptions = { options, extraArgs, rootPath }; + const command = _commands.commands[commandName]; + if (command === undefined) { + _log.log.write(_chalk2.default.red(`[${commandName}] is not a valid command, see 'kbn --help'`)); + process.exit(1); + } + yield (0, _run.runCommand)(command, commandOptions); + }); - return pathType.dir(fp) - .then(isDir => { - if (isDir) { - fp = path.join(fp, 'package.json'); - } + return function run(_x) { + return _ref.apply(this, arguments); + }; +})(); - return loadJsonFile(fp); - }) - .then(x => { - if (opts.normalize !== false) { - __webpack_require__(102)(x); - } +var _chalk = __webpack_require__(26); - return x; - }); -}; +var _chalk2 = _interopRequireDefault(_chalk); -module.exports.sync = (fp, opts) => { - if (typeof fp !== 'string') { - opts = fp; - fp = '.'; - } +var _dedent = __webpack_require__(171); - opts = opts || {}; - fp = pathType.dirSync(fp) ? path.join(fp, 'package.json') : fp; +var _dedent2 = _interopRequireDefault(_dedent); - const x = loadJsonFile.sync(fp); +var _getopts = __webpack_require__(172); - if (opts.normalize !== false) { - __webpack_require__(102)(x); - } +var _getopts2 = _interopRequireDefault(_getopts); - return x; -}; +var _path = __webpack_require__(5); +var _commands = __webpack_require__(173); -/***/ }), -/* 144 */ -/***/ (function(module, exports, __webpack_require__) { +var _run = __webpack_require__(282); -"use strict"; +var _log = __webpack_require__(40); -const path = __webpack_require__(7); -const fs = __webpack_require__(56); -const stripBom = __webpack_require__(145); -const parseJson = __webpack_require__(146); -const pify = __webpack_require__(44); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -const parse = (data, fp) => parseJson(stripBom(data), path.relative('.', fp)); - -module.exports = fp => pify(fs.readFile)(fp, 'utf8').then(data => parse(data, fp)); -module.exports.sync = fp => parse(fs.readFileSync(fp, 'utf8'), fp); +function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ -/***/ }), -/* 145 */ -/***/ (function(module, exports, __webpack_require__) { +function help() { + const availableCommands = Object.keys(_commands.commands).map(commandName => _commands.commands[commandName]).map(command => `${command.name} - ${command.description}`); + _log.log.write(_dedent2.default` + usage: kbn [] -"use strict"; + By default commands are run for Kibana itself, all packages in the 'packages/' + folder and for all plugins in '../kibana-extra'. -module.exports = x => { - if (typeof x !== 'string') { - throw new TypeError('Expected a string, got ' + typeof x); - } + Available commands: - // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string - // conversion translates it to FEFF (UTF-16 BOM) - if (x.charCodeAt(0) === 0xFEFF) { - return x.slice(1); - } + ${availableCommands.join('\n ')} - return x; -}; + Global options: + -e, --exclude Exclude specified project. Can be specified multiple times to exclude multiple projects, e.g. '-e kibana -e @kbn/pm'. + -i, --include Include only specified projects. If left unspecified, it defaults to including all projects. + --oss Do not include the x-pack when running command. + --skip-kibana-extra Filter all plugins in ../kibana-extra when running command. + `); +} /***/ }), -/* 146 */ +/* 163 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const errorEx = __webpack_require__(147); -const fallback = __webpack_require__(149); -const JSONError = errorEx('JSONError', { - fileName: errorEx.append('in %s') -}); +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; -module.exports = (input, reviver, filename) => { - if (typeof reviver === 'string') { - filename = reviver; - reviver = null; +module.exports = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); } - try { - try { - return JSON.parse(input, reviver); - } catch (err) { - fallback(input, reviver); - - throw err; - } - } catch (err) { - err.message = err.message.replace(/\n/g, ''); - - const jsonErr = new JSONError(err); - if (filename) { - jsonErr.fileName = filename; - } - - throw jsonErr; - } + return str.replace(matchOperatorsRe, '\\$&'); }; /***/ }), -/* 147 */ +/* 164 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/* WEBPACK VAR INJECTION */(function(module) { +const colorConvert = __webpack_require__(165); +const wrapAnsi16 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${code + offset}m`; +}; -var util = __webpack_require__(19); -var isArrayish = __webpack_require__(148); - -var errorEx = function errorEx(name, properties) { - if (!name || name.constructor !== String) { - properties = name || {}; - name = Error.name; - } - - var errorExError = function ErrorEXError(message) { - if (!this) { - return new ErrorEXError(message); - } - - message = message instanceof Error - ? message.message - : (message || this.message); - - Error.call(this, message); - Error.captureStackTrace(this, errorExError); +const wrapAnsi256 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};5;${code}m`; +}; - this.name = name; +const wrapAnsi16m = (fn, offset) => function () { + const rgb = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; - Object.defineProperty(this, 'message', { - configurable: true, - enumerable: false, - get: function () { - var newMessage = message.split(/\r?\n/g); +function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], - for (var key in properties) { - if (!properties.hasOwnProperty(key)) { - continue; - } + // Bright color + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], - var modifier = properties[key]; + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; - if ('message' in modifier) { - newMessage = modifier.message(this[key], newMessage) || newMessage; - if (!isArrayish(newMessage)) { - newMessage = [newMessage]; - } - } - } + // Fix humans + styles.color.grey = styles.color.gray; - return newMessage.join('\n'); - }, - set: function (v) { - message = v; - } - }); + for (const groupName of Object.keys(styles)) { + const group = styles[groupName]; - var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack'); - var stackGetter = stackDescriptor.get; - var stackValue = stackDescriptor.value; - delete stackDescriptor.value; - delete stackDescriptor.writable; + for (const styleName of Object.keys(group)) { + const style = group[styleName]; - stackDescriptor.get = function () { - var stack = (stackGetter) - ? stackGetter.call(this).split(/\r?\n+/g) - : stackValue.split(/\r?\n+/g); + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; - // starting in Node 7, the stack builder caches the message. - // just replace it. - stack[0] = this.name + ': ' + this.message; + group[styleName] = styles[styleName]; - var lineCount = 1; - for (var key in properties) { - if (!properties.hasOwnProperty(key)) { - continue; - } + codes.set(style[0], style[1]); + } - var modifier = properties[key]; + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); - if ('line' in modifier) { - var line = modifier.line(this[key]); - if (line) { - stack.splice(lineCount++, 0, ' ' + line); - } - } + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + } - if ('stack' in modifier) { - modifier.stack(this[key], stack); - } - } + const ansi2ansi = n => n; + const rgb2rgb = (r, g, b) => [r, g, b]; - return stack.join('\n'); - }; + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; - Object.defineProperty(this, 'stack', stackDescriptor); + styles.color.ansi = { + ansi: wrapAnsi16(ansi2ansi, 0) + }; + styles.color.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 0) + }; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) }; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(errorExError.prototype, Error.prototype); - Object.setPrototypeOf(errorExError, Error); - } else { - util.inherits(errorExError, Error); - } - - return errorExError; -}; + styles.bgColor.ansi = { + ansi: wrapAnsi16(ansi2ansi, 10) + }; + styles.bgColor.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 10) + }; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; -errorEx.append = function (str, def) { - return { - message: function (v, message) { - v = v || def; + for (let key of Object.keys(colorConvert)) { + if (typeof colorConvert[key] !== 'object') { + continue; + } - if (v) { - message[0] += ' ' + str.replace('%s', v.toString()); - } + const suite = colorConvert[key]; - return message; + if (key === 'ansi16') { + key = 'ansi'; } - }; -}; -errorEx.line = function (str, def) { - return { - line: function (v) { - v = v || def; + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } - if (v) { - return str.replace('%s', v.toString()); - } + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } - return null; + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); } - }; -}; + } -module.exports = errorEx; + return styles; +} + +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(112)(module))) /***/ }), -/* 148 */ +/* 165 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - +var conversions = __webpack_require__(113); +var route = __webpack_require__(167); -module.exports = function isArrayish(obj) { - if (!obj) { - return false; - } +var convert = {}; - return obj instanceof Array || Array.isArray(obj) || - (obj.length >= 0 && obj.splice instanceof Function); -}; +var models = Object.keys(conversions); +function wrapRaw(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } -/***/ }), -/* 149 */ -/***/ (function(module, exports, __webpack_require__) { + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } -"use strict"; + return fn(args); + }; + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } -module.exports = parseJson -function parseJson (txt, reviver, context) { - context = context || 20 - try { - return JSON.parse(txt, reviver) - } catch (e) { - const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i) - const errIdx = syntaxErr - ? +syntaxErr[1] - : e.message.match(/^Unexpected end of JSON.*/i) - ? txt.length - 1 - : null - if (errIdx != null) { - const start = errIdx <= context - ? 0 - : errIdx - context - const end = errIdx + context >= txt.length - ? txt.length - : errIdx + context - e.message += ` while parsing near '${ - start === 0 ? '' : '...' - }${txt.slice(start, end)}${ - end === txt.length ? '' : '...' - }'` - } else { - e.message += ` while parsing '${txt.slice(0, context * 2)}'` - } - throw e - } + return wrappedFn; } +function wrapRounded(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } -/***/ }), -/* 150 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -const fs = __webpack_require__(16); -const pify = __webpack_require__(44); + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } -function type(fn, fn2, fp) { - if (typeof fp !== 'string') { - return Promise.reject(new TypeError(`Expected a string, got ${typeof fp}`)); - } + var result = fn(args); - return pify(fs[fn])(fp) - .then(stats => stats[fn2]()) - .catch(err => { - if (err.code === 'ENOENT') { - return false; + // we're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (var len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); } + } - throw err; - }); -} + return result; + }; -function typeSync(fn, fn2, fp) { - if (typeof fp !== 'string') { - throw new TypeError(`Expected a string, got ${typeof fp}`); + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; } - try { - return fs[fn](fp)[fn2](); - } catch (err) { - if (err.code === 'ENOENT') { - return false; - } - - throw err; - } + return wrappedFn; } -exports.file = type.bind(null, 'stat', 'isFile'); -exports.dir = type.bind(null, 'stat', 'isDirectory'); -exports.symlink = type.bind(null, 'lstat', 'isSymbolicLink'); -exports.fileSync = typeSync.bind(null, 'statSync', 'isFile'); -exports.dirSync = typeSync.bind(null, 'statSync', 'isDirectory'); -exports.symlinkSync = typeSync.bind(null, 'lstatSync', 'isSymbolicLink'); +models.forEach(function (fromModel) { + convert[fromModel] = {}; + Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); + Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); -/***/ }), -/* 151 */ -/***/ (function(module, exports, __webpack_require__) { + var routes = route(fromModel); + var routeModels = Object.keys(routes); -var semver = __webpack_require__(152) -var validateLicense = __webpack_require__(153); -var hostedGitInfo = __webpack_require__(158) -var isBuiltinModule = __webpack_require__(160) -var depTypes = ["dependencies","devDependencies","optionalDependencies"] -var extractDescription = __webpack_require__(162) -var url = __webpack_require__(103) -var typos = __webpack_require__(163) + routeModels.forEach(function (toModel) { + var fn = routes[toModel]; -var fixer = module.exports = { - // default warning function - warn: function() {}, + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); +}); - fixRepositoryField: function(data) { - if (data.repositories) { - this.warn("repositories"); - data.repository = data.repositories[0] - } - if (!data.repository) return this.warn("missingRepository") - if (typeof data.repository === "string") { - data.repository = { - type: "git", - url: data.repository - } - } - var r = data.repository.url || "" - if (r) { - var hosted = hostedGitInfo.fromUrl(r) - if (hosted) { - r = data.repository.url - = hosted.getDefaultRepresentation() == "shortcut" ? hosted.https() : hosted.toString() - } - } +module.exports = convert; - if (r.match(/github.com\/[^\/]+\/[^\/]+\.git\.git$/)) { - this.warn("brokenGitUrl", r) - } - } -, fixTypos: function(data) { - Object.keys(typos.topLevel).forEach(function (d) { - if (data.hasOwnProperty(d)) { - this.warn("typo", d, typos.topLevel[d]) - } - }, this) - } +/***/ }), +/* 166 */ +/***/ (function(module, exports, __webpack_require__) { -, fixScriptsField: function(data) { - if (!data.scripts) return - if (typeof data.scripts !== "object") { - this.warn("nonObjectScripts") - delete data.scripts - return - } - Object.keys(data.scripts).forEach(function (k) { - if (typeof data.scripts[k] !== "string") { - this.warn("nonStringScript") - delete data.scripts[k] - } else if (typos.script[k] && !data.scripts[typos.script[k]]) { - this.warn("typo", k, typos.script[k], "scripts") - } - }, this) - } - -, fixFilesField: function(data) { - var files = data.files - if (files && !Array.isArray(files)) { - this.warn("nonArrayFiles") - delete data.files - } else if (data.files) { - data.files = data.files.filter(function(file) { - if (!file || typeof file !== "string") { - this.warn("invalidFilename", file) - return false - } else { - return true - } - }, this) - } - } +"use strict"; + + +module.exports = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] +}; -, fixBinField: function(data) { - if (!data.bin) return; - if (typeof data.bin === "string") { - var b = {} - var match - if (match = data.name.match(/^@[^/]+[/](.*)$/)) { - b[match[1]] = data.bin - } else { - b[data.name] = data.bin - } - data.bin = b - } - } -, fixManField: function(data) { - if (!data.man) return; - if (typeof data.man === "string") { - data.man = [ data.man ] - } - } -, fixBundleDependenciesField: function(data) { - var bdd = "bundledDependencies" - var bd = "bundleDependencies" - if (data[bdd] && !data[bd]) { - data[bd] = data[bdd] - delete data[bdd] - } - if (data[bd] && !Array.isArray(data[bd])) { - this.warn("nonArrayBundleDependencies") - delete data[bd] - } else if (data[bd]) { - data[bd] = data[bd].filter(function(bd) { - if (!bd || typeof bd !== 'string') { - this.warn("nonStringBundleDependency", bd) - return false - } else { - if (!data.dependencies) { - data.dependencies = {} - } - if (!data.dependencies.hasOwnProperty(bd)) { - this.warn("nonDependencyBundleDependency", bd) - data.dependencies[bd] = "*" - } - return true - } - }, this) - } - } +/***/ }), +/* 167 */ +/***/ (function(module, exports, __webpack_require__) { -, fixDependencies: function(data, strict) { - var loose = !strict - objectifyDeps(data, this.warn) - addOptionalDepsToDeps(data, this.warn) - this.fixBundleDependenciesField(data) +var conversions = __webpack_require__(113); - ;['dependencies','devDependencies'].forEach(function(deps) { - if (!(deps in data)) return - if (!data[deps] || typeof data[deps] !== "object") { - this.warn("nonObjectDependencies", deps) - delete data[deps] - return - } - Object.keys(data[deps]).forEach(function (d) { - var r = data[deps][d] - if (typeof r !== 'string') { - this.warn("nonStringDependency", d, JSON.stringify(r)) - delete data[deps][d] - } - var hosted = hostedGitInfo.fromUrl(data[deps][d]) - if (hosted) data[deps][d] = hosted.toString() - }, this) - }, this) - } +/* + this function routes a model to all other models. -, fixModulesField: function (data) { - if (data.modules) { - this.warn("deprecatedModules") - delete data.modules - } - } + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). -, fixKeywordsField: function (data) { - if (typeof data.keywords === "string") { - data.keywords = data.keywords.split(/,\s+/) - } - if (data.keywords && !Array.isArray(data.keywords)) { - delete data.keywords - this.warn("nonArrayKeywords") - } else if (data.keywords) { - data.keywords = data.keywords.filter(function(kw) { - if (typeof kw !== "string" || !kw) { - this.warn("nonStringKeyword"); - return false - } else { - return true - } - }, this) - } - } + conversions that are not possible simply are not included. +*/ -, fixVersionField: function(data, strict) { - // allow "loose" semver 1.0 versions in non-strict mode - // enforce strict semver 2.0 compliance in strict mode - var loose = !strict - if (!data.version) { - data.version = "" - return true - } - if (!semver.valid(data.version, loose)) { - throw new Error('Invalid version: "'+ data.version + '"') - } - data.version = semver.clean(data.version, loose) - return true - } +function buildGraph() { + var graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + var models = Object.keys(conversions); -, fixPeople: function(data) { - modifyPeople(data, unParsePerson) - modifyPeople(data, parsePerson) - } + for (var len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } -, fixNameField: function(data, options) { - if (typeof options === "boolean") options = {strict: options} - else if (typeof options === "undefined") options = {} - var strict = options.strict - if (!data.name && !strict) { - data.name = "" - return - } - if (typeof data.name !== "string") { - throw new Error("name field must be a string.") - } - if (!strict) - data.name = data.name.trim() - ensureValidName(data.name, strict, options.allowLegacyCase) - if (isBuiltinModule(data.name)) - this.warn("conflictingName", data.name) - } + return graph; +} +// https://en.wikipedia.org/wiki/Breadth-first_search +function deriveBFS(fromModel) { + var graph = buildGraph(); + var queue = [fromModel]; // unshift -> queue -> pop -, fixDescriptionField: function (data) { - if (data.description && typeof data.description !== 'string') { - this.warn("nonStringDescription") - delete data.description - } - if (data.readme && !data.description) - data.description = extractDescription(data.readme) - if(data.description === undefined) delete data.description; - if (!data.description) this.warn("missingDescription") - } + graph[fromModel].distance = 0; -, fixReadmeField: function (data) { - if (!data.readme) { - this.warn("missingReadme") - data.readme = "ERROR: No README data found!" - } - } + while (queue.length) { + var current = queue.pop(); + var adjacents = Object.keys(conversions[current]); -, fixBugsField: function(data) { - if (!data.bugs && data.repository && data.repository.url) { - var hosted = hostedGitInfo.fromUrl(data.repository.url) - if(hosted && hosted.bugs()) { - data.bugs = {url: hosted.bugs()} - } - } - else if(data.bugs) { - var emailRe = /^.+@.*\..+$/ - if(typeof data.bugs == "string") { - if(emailRe.test(data.bugs)) - data.bugs = {email:data.bugs} - else if(url.parse(data.bugs).protocol) - data.bugs = {url: data.bugs} - else - this.warn("nonEmailUrlBugsString") - } - else { - bugsTypos(data.bugs, this.warn) - var oldBugs = data.bugs - data.bugs = {} - if(oldBugs.url) { - if(typeof(oldBugs.url) == "string" && url.parse(oldBugs.url).protocol) - data.bugs.url = oldBugs.url - else - this.warn("nonUrlBugsUrlField") - } - if(oldBugs.email) { - if(typeof(oldBugs.email) == "string" && emailRe.test(oldBugs.email)) - data.bugs.email = oldBugs.email - else - this.warn("nonEmailBugsEmailField") - } - } - if(!data.bugs.email && !data.bugs.url) { - delete data.bugs - this.warn("emptyNormalizedBugs") - } - } - } + for (var len = adjacents.length, i = 0; i < len; i++) { + var adjacent = adjacents[i]; + var node = graph[adjacent]; -, fixHomepageField: function(data) { - if (!data.homepage && data.repository && data.repository.url) { - var hosted = hostedGitInfo.fromUrl(data.repository.url) - if (hosted && hosted.docs()) data.homepage = hosted.docs() - } - if (!data.homepage) return + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } - if(typeof data.homepage !== "string") { - this.warn("nonUrlHomepage") - return delete data.homepage - } - if(!url.parse(data.homepage).protocol) { - data.homepage = "http://" + data.homepage - } - } + return graph; +} -, fixLicenseField: function(data) { - if (!data.license) { - return this.warn("missingLicense") - } else{ - if ( - typeof(data.license) !== 'string' || - data.license.length < 1 - ) { - this.warn("invalidLicense") - } else { - if (!validateLicense(data.license).validForNewPackages) - this.warn("invalidLicense") - } - } - } +function link(from, to) { + return function (args) { + return to(from(args)); + }; } -function isValidScopedPackageName(spec) { - if (spec.charAt(0) !== '@') return false +function wrapConversion(toModel, graph) { + var path = [graph[toModel].parent, toModel]; + var fn = conversions[graph[toModel].parent][toModel]; - var rest = spec.slice(1).split('/') - if (rest.length !== 2) return false + var cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } - return rest[0] && rest[1] && - rest[0] === encodeURIComponent(rest[0]) && - rest[1] === encodeURIComponent(rest[1]) + fn.conversion = path; + return fn; } -function isCorrectlyEncodedName(spec) { - return !spec.match(/[\/@\s\+%:]/) && - spec === encodeURIComponent(spec) -} +module.exports = function (fromModel) { + var graph = deriveBFS(fromModel); + var conversion = {}; -function ensureValidName (name, strict, allowLegacyCase) { - if (name.charAt(0) === "." || - !(isValidScopedPackageName(name) || isCorrectlyEncodedName(name)) || - (strict && (!allowLegacyCase) && name !== name.toLowerCase()) || - name.toLowerCase() === "node_modules" || - name.toLowerCase() === "favicon.ico") { - throw new Error("Invalid name: " + JSON.stringify(name)) - } -} + var models = Object.keys(graph); + for (var len = models.length, i = 0; i < len; i++) { + var toModel = models[i]; + var node = graph[toModel]; -function modifyPeople (data, fn) { - if (data.author) data.author = fn(data.author) - ;["maintainers", "contributors"].forEach(function (set) { - if (!Array.isArray(data[set])) return; - data[set] = data[set].map(fn) - }) - return data -} + if (node.parent === null) { + // no possible conversion, or this node is the source model. + continue; + } -function unParsePerson (person) { - if (typeof person === "string") return person - var name = person.name || "" - var u = person.url || person.web - var url = u ? (" ("+u+")") : "" - var e = person.email || person.mail - var email = e ? (" <"+e+">") : "" - return name+email+url -} + conversion[toModel] = wrapConversion(toModel, graph); + } -function parsePerson (person) { - if (typeof person !== "string") return person - var name = person.match(/^([^\(<]+)/) - var url = person.match(/\(([^\)]+)\)/) - var email = person.match(/<([^>]+)>/) - var obj = {} - if (name && name[0].trim()) obj.name = name[0].trim() - if (email) obj.email = email[1]; - if (url) obj.url = url[1]; - return obj -} + return conversion; +}; -function addOptionalDepsToDeps (data, warn) { - var o = data.optionalDependencies - if (!o) return; - var d = data.dependencies || {} - Object.keys(o).forEach(function (k) { - d[k] = o[k] - }) - data.dependencies = d -} -function depObjectify (deps, type, warn) { - if (!deps) return {} - if (typeof deps === "string") { - deps = deps.trim().split(/[\n\r\s\t ,]+/) - } - if (!Array.isArray(deps)) return deps - warn("deprecatedArrayDependencies", type) - var o = {} - deps.filter(function (d) { - return typeof d === "string" - }).forEach(function(d) { - d = d.trim().split(/(:?[@\s><=])/) - var dn = d.shift() - var dv = d.join("") - dv = dv.trim() - dv = dv.replace(/^@/, "") - o[dn] = dv - }) - return o -} -function objectifyDeps (data, warn) { - depTypes.forEach(function (type) { - if (!data[type]) return; - data[type] = depObjectify(data[type], type, warn) - }) -} +/***/ }), +/* 168 */ +/***/ (function(module, exports, __webpack_require__) { -function bugsTypos(bugs, warn) { - if (!bugs) return - Object.keys(bugs).forEach(function (k) { - if (typos.bugs[k]) { - warn("typo", k, typos.bugs[k], "bugs") - bugs[typos.bugs[k]] = bugs[k] - delete bugs[k] - } - }) -} +"use strict"; +const os = __webpack_require__(114); +const hasFlag = __webpack_require__(169); -/***/ }), -/* 152 */ -/***/ (function(module, exports) { +const env = process.env; -exports = module.exports = SemVer; +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false')) { + forceColor = false; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = true; +} +if ('FORCE_COLOR' in env) { + forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; +} -// The debug function is excluded entirely from the minified version. -/* nomin */ var debug; -/* nomin */ if (typeof process === 'object' && - /* nomin */ process.env && - /* nomin */ process.env.NODE_DEBUG && - /* nomin */ /\bsemver\b/i.test(process.env.NODE_DEBUG)) - /* nomin */ debug = function() { - /* nomin */ var args = Array.prototype.slice.call(arguments, 0); - /* nomin */ args.unshift('SEMVER'); - /* nomin */ console.log.apply(console, args); - /* nomin */ }; -/* nomin */ else - /* nomin */ debug = function() {}; +function translateLevel(level) { + if (level === 0) { + return false; + } -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -exports.SEMVER_SPEC_VERSION = '2.0.0'; + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} -var MAX_LENGTH = 256; -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; +function supportsColor(stream) { + if (forceColor === false) { + return 0; + } -// The actual regexps go on exports.re -var re = exports.re = []; -var src = exports.src = []; -var R = 0; + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. + if (hasFlag('color=256')) { + return 2; + } -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. + if (stream && !stream.isTTY && forceColor !== true) { + // VS code debugger doesn't have isTTY set + if (env.VSCODE_PID) { + return 1; + } + return 0; + } -var NUMERICIDENTIFIER = R++; -src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; -var NUMERICIDENTIFIERLOOSE = R++; -src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; + const min = forceColor ? 1 : 0; + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. Windows 10 build 14931 is the first release + // that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(process.versions.node.split('.')[0]) >= 8 && + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. + return 1; + } -var NONNUMERICIDENTIFIER = R++; -src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + return min; + } -// ## Main Version -// Three dot-separated numeric identifiers. + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } -var MAINVERSION = R++; -src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')'; + if (env.COLORTERM === 'truecolor') { + return 3; + } -var MAINVERSIONLOOSE = R++; -src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } -var PRERELEASEIDENTIFIER = R++; -src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + - '|' + src[NONNUMERICIDENTIFIER] + ')'; + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } -var PRERELEASEIDENTIFIERLOOSE = R++; -src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + - '|' + src[NONNUMERICIDENTIFIER] + ')'; + if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + if ('COLORTERM' in env) { + return 1; + } -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. + if (env.TERM === 'dumb') { + return min; + } -var PRERELEASE = R++; -src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + - '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; + return min; +} -var PRERELEASELOOSE = R++; -src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + - '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; +function getSupportLevel(stream) { + const level = supportsColor(stream); + return translateLevel(level); +} -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. +module.exports = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr) +}; -var BUILDIDENTIFIER = R++; -src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. +/***/ }), +/* 169 */ +/***/ (function(module, exports, __webpack_require__) { -var BUILD = R++; -src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + - '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; +"use strict"; +module.exports = (flag, argv) => { + argv = argv || process.argv; + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const pos = argv.indexOf(prefix + flag); + const terminatorPos = argv.indexOf('--'); + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); +}; -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. +/***/ }), +/* 170 */ +/***/ (function(module, exports, __webpack_require__) { -var FULL = R++; -var FULLPLAIN = 'v?' + src[MAINVERSION] + - src[PRERELEASE] + '?' + - src[BUILD] + '?'; +"use strict"; -src[FULL] = '^' + FULLPLAIN + '$'; +const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; +const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; +const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; +const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + - src[PRERELEASELOOSE] + '?' + - src[BUILD] + '?'; +const ESCAPES = new Map([ + ['n', '\n'], + ['r', '\r'], + ['t', '\t'], + ['b', '\b'], + ['f', '\f'], + ['v', '\v'], + ['0', '\0'], + ['\\', '\\'], + ['e', '\u001B'], + ['a', '\u0007'] +]); -var LOOSE = R++; -src[LOOSE] = '^' + LOOSEPLAIN + '$'; +function unescape(c) { + if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } -var GTLT = R++; -src[GTLT] = '((?:<|>)?=?)'; + return ESCAPES.get(c) || c; +} -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -var XRANGEIDENTIFIERLOOSE = R++; -src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; -var XRANGEIDENTIFIER = R++; -src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; +function parseArguments(name, args) { + const results = []; + const chunks = args.trim().split(/\s*,\s*/g); + let matches; -var XRANGEPLAIN = R++; -src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:' + src[PRERELEASE] + ')?' + - src[BUILD] + '?' + - ')?)?'; + for (const chunk of chunks) { + if (!isNaN(chunk)) { + results.push(Number(chunk)); + } else if ((matches = chunk.match(STRING_REGEX))) { + results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } -var XRANGEPLAINLOOSE = R++; -src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:' + src[PRERELEASELOOSE] + ')?' + - src[BUILD] + '?' + - ')?)?'; + return results; +} -var XRANGE = R++; -src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; -var XRANGELOOSE = R++; -src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; +function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; -// Tilde ranges. -// Meaning is "reasonably at or greater than" -var LONETILDE = R++; -src[LONETILDE] = '(?:~>?)'; + const results = []; + let matches; -var TILDETRIM = R++; -src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; -re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); -var tildeTrimReplace = '$1~'; + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; -var TILDE = R++; -src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; -var TILDELOOSE = R++; -src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; + if (matches[2]) { + const args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } -// Caret ranges. -// Meaning is "at least and backwards compatible with" -var LONECARET = R++; -src[LONECARET] = '(?:\\^)'; + return results; +} -var CARETTRIM = R++; -src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; -re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); -var caretTrimReplace = '$1^'; +function buildStyle(chalk, styles) { + const enabled = {}; -var CARET = R++; -src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; -var CARETLOOSE = R++; -src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } -// A simple gt/lt/eq thing, or just "" to indicate "any version" -var COMPARATORLOOSE = R++; -src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; -var COMPARATOR = R++; -src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; + let current = chalk; + for (const styleName of Object.keys(enabled)) { + if (Array.isArray(enabled[styleName])) { + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } + if (enabled[styleName].length > 0) { + current = current[styleName].apply(current, enabled[styleName]); + } else { + current = current[styleName]; + } + } + } -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -var COMPARATORTRIM = R++; -src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + - '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; + return current; +} -// this one has to use the /g flag -re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); -var comparatorTrimReplace = '$1$2$3'; +module.exports = (chalk, tmp) => { + const styles = []; + const chunks = []; + let chunk = []; + // eslint-disable-next-line max-params + tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { + if (escapeChar) { + chunk.push(unescape(escapeChar)); + } else if (style) { + const str = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); + styles.push({inverse, styles: parseStyle(style)}); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -var HYPHENRANGE = R++; -src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAIN] + ')' + - '\\s*$'; + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(chr); + } + }); -var HYPHENRANGELOOSE = R++; -src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s*$'; + chunks.push(chunk.join('')); -// Star ranges basically just allow anything at all. -var STAR = R++; -src[STAR] = '(<|>)?=?\\s*\\*'; + if (styles.length > 0) { + const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; + throw new Error(errMsg); + } -// Compile to actual regexp objects. -// All are flag-free, unless they were created above with a flag. -for (var i = 0; i < R; i++) { - debug(i, src[i]); - if (!re[i]) - re[i] = new RegExp(src[i]); -} + return chunks.join(''); +}; -exports.parse = parse; -function parse(version, loose) { - if (version instanceof SemVer) - return version; - if (typeof version !== 'string') - return null; +/***/ }), +/* 171 */ +/***/ (function(module, exports, __webpack_require__) { - if (version.length > MAX_LENGTH) - return null; +"use strict"; - var r = loose ? re[LOOSE] : re[FULL]; - if (!r.test(version)) - return null; - try { - return new SemVer(version, loose); - } catch (er) { - return null; - } -} +function dedent(strings) { -exports.valid = valid; -function valid(version, loose) { - var v = parse(version, loose); - return v ? v.version : null; -} + var raw = void 0; + if (typeof strings === "string") { + // dedent can be used as a plain function + raw = [strings]; + } else { + raw = strings.raw; + } + // first, perform interpolation + var result = ""; + for (var i = 0; i < raw.length; i++) { + result += raw[i]. + // join lines when there is a suppressed newline + replace(/\\\n[ \t]*/g, ""). -exports.clean = clean; -function clean(version, loose) { - var s = parse(version.trim().replace(/^[=v]+/, ''), loose); - return s ? s.version : null; -} + // handle escaped backticks + replace(/\\`/g, "`"); -exports.SemVer = SemVer; + if (i < (arguments.length <= 1 ? 0 : arguments.length - 1)) { + result += arguments.length <= i + 1 ? undefined : arguments[i + 1]; + } + } -function SemVer(version, loose) { - if (version instanceof SemVer) { - if (version.loose === loose) - return version; - else - version = version.version; - } else if (typeof version !== 'string') { - throw new TypeError('Invalid Version: ' + version); + // now strip indentation + var lines = result.split("\n"); + var mindent = null; + lines.forEach(function (l) { + var m = l.match(/^(\s+)\S+/); + if (m) { + var indent = m[1].length; + if (!mindent) { + // this is the first indented line + mindent = indent; + } else { + mindent = Math.min(mindent, indent); + } + } + }); + + if (mindent !== null) { + result = lines.map(function (l) { + return l[0] === " " ? l.slice(mindent) : l; + }).join("\n"); } - if (version.length > MAX_LENGTH) - throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + // dedent eats leading and trailing whitespace too + result = result.trim(); - if (!(this instanceof SemVer)) - return new SemVer(version, loose); + // handle escaped newlines at the end to ensure they don't get stripped too + return result.replace(/\\n/g, "\n"); +} - debug('SemVer', version, loose); - this.loose = loose; - var m = version.trim().match(loose ? re[LOOSE] : re[FULL]); +if (true) { + module.exports = dedent; +} - if (!m) - throw new TypeError('Invalid Version: ' + version); - this.raw = version; +/***/ }), +/* 172 */ +/***/ (function(module, exports) { - // these are actually numbers - this.major = +m[1]; - this.minor = +m[2]; - this.patch = +m[3]; +const SHORTSPLIT = /$|[!-@\[-`{-~].*/g +const EMPTY = [] - if (this.major > MAX_SAFE_INTEGER || this.major < 0) - throw new TypeError('Invalid major version') +function array(any) { + return Array.isArray(any) ? any : [any] +} - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) - throw new TypeError('Invalid minor version') +function aliases(aliases) { + var out = {} - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) - throw new TypeError('Invalid patch version') + for (var key in aliases) { + var alias = (out[key] = array(aliases[key])) - // numberify any prerelease numeric ids - if (!m[4]) - this.prerelease = []; - else - this.prerelease = m[4].split('.').map(function(id) { - if (/^[0-9]+$/.test(id)) { - var num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER) - return num; + for (var i = 0, len = alias.length; i < len; i++) { + var curr = (out[alias[i]] = [key]) + + for (var j = 0; j < len; j++) { + if (i !== j) { + curr.push(alias[j]) + } } - return id; - }); + } + } - this.build = m[5] ? m[5].split('.') : []; - this.format(); + return out } -SemVer.prototype.format = function() { - this.version = this.major + '.' + this.minor + '.' + this.patch; - if (this.prerelease.length) - this.version += '-' + this.prerelease.join('.'); - return this.version; -}; - -SemVer.prototype.toString = function() { - return this.version; -}; - -SemVer.prototype.compare = function(other) { - debug('SemVer.compare', this.version, this.loose, other); - if (!(other instanceof SemVer)) - other = new SemVer(other, this.loose); +function booleans(aliases, booleans) { + var out = {} - return this.compareMain(other) || this.comparePre(other); -}; + if (booleans !== undefined) { + for (var i = 0, len = booleans.length; i < len; i++) { + var key = booleans[i] + var alias = aliases[key] -SemVer.prototype.compareMain = function(other) { - if (!(other instanceof SemVer)) - other = new SemVer(other, this.loose); + out[key] = true - return compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch); -}; + if (alias === undefined) { + aliases[key] = EMPTY + } else { + for (var j = 0, end = alias.length; j < end; j++) { + out[alias[j]] = true + } + } + } + } -SemVer.prototype.comparePre = function(other) { - if (!(other instanceof SemVer)) - other = new SemVer(other, this.loose); + return out +} - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) - return -1; - else if (!this.prerelease.length && other.prerelease.length) - return 1; - else if (!this.prerelease.length && !other.prerelease.length) - return 0; +function defaults(aliases, defaults) { + var out = {} - var i = 0; - do { - var a = this.prerelease[i]; - var b = other.prerelease[i]; - debug('prerelease compare', i, a, b); - if (a === undefined && b === undefined) - return 0; - else if (b === undefined) - return 1; - else if (a === undefined) - return -1; - else if (a === b) - continue; - else - return compareIdentifiers(a, b); - } while (++i); -}; + for (var key in defaults) { + var value = defaults[key] + var alias = aliases[key] -// preminor will bump the version up to the next minor release, and immediately -// down to pre-release. premajor and prepatch work the same way. -SemVer.prototype.inc = function(release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0; - this.patch = 0; - this.minor = 0; - this.major++; - this.inc('pre', identifier); - break; - case 'preminor': - this.prerelease.length = 0; - this.patch = 0; - this.minor++; - this.inc('pre', identifier); - break; - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0; - this.inc('patch', identifier); - this.inc('pre', identifier); - break; - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) - this.inc('patch', identifier); - this.inc('pre', identifier); - break; + if (out[key] === undefined) { + out[key] = value - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) - this.major++; - this.minor = 0; - this.patch = 0; - this.prerelease = []; - break; - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) - this.minor++; - this.patch = 0; - this.prerelease = []; - break; - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) - this.patch++; - this.prerelease = []; - break; - // This probably shouldn't be used publicly. - // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) - this.prerelease = [0]; - else { - var i = this.prerelease.length; - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++; - i = -2; - } + if (alias === undefined) { + aliases[key] = EMPTY + } else { + for (var i = 0, len = alias.length; i < len; i++) { + out[alias[i]] = value } - if (i === -1) // didn't increment anything - this.prerelease.push(0); - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) - this.prerelease = [identifier, 0]; - } else - this.prerelease = [identifier, 0]; } - break; - - default: - throw new Error('invalid increment argument: ' + release); + } } - this.format(); - this.raw = this.version; - return this; -}; -exports.inc = inc; -function inc(version, release, loose, identifier) { - if (typeof(loose) === 'string') { - identifier = loose; - loose = undefined; - } + return out +} - try { - return new SemVer(version, loose).inc(release, identifier).version; - } catch (er) { - return null; +function set(out, key, value, aliases, unknown) { + var curr = out[key] + var alias = aliases[key] + var known = alias !== undefined + + if (known || unknown === undefined || false !== unknown(key)) { + if (curr === undefined) { + out[key] = value + } else { + if (Array.isArray(curr)) { + curr.push(value) + } else { + out[key] = [curr, value] + } + } + + if (known) { + for (var i = 0, len = alias.length; i < len; ) { + out[alias[i++]] = out[key] + } + } } } -exports.diff = diff; -function diff(version1, version2) { - if (eq(version1, version2)) { - return null; - } else { - var v1 = parse(version1); - var v2 = parse(version2); - if (v1.prerelease.length || v2.prerelease.length) { - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return 'pre'+key; +module.exports = function(argv, opts) { + var unknown = (opts = opts || {}).unknown + var alias = aliases(opts.alias) + var values = defaults(alias, opts.default) + var bools = booleans(alias, opts.boolean) + var out = { _: [] } + + for (var i = 0, j = 0, len = argv.length, _ = out._; i < len; i++) { + var arg = argv[i] + + if (arg === "--") { + while (++i < len) { + _.push(argv[i]) + } + } else if (arg === "-" || arg[0] !== "-") { + _.push(arg) + } else { + if (arg[1] === "-") { + var end = arg.indexOf("=", 2) + + if (0 <= end) { + set(out, arg.slice(2, end), arg.slice(end + 1), alias, unknown) + } else { + if ("n" === arg[2] && "o" === arg[3] && "-" === arg[4]) { + set(out, arg.slice(5), false, alias, unknown) + } else { + var key = arg.slice(2) + set( + out, + key, + len === (j = i + 1) || + argv[j][0] === "-" || + bools[key] !== undefined || + argv[(i = j)], + alias, + unknown + ) } } - } - return 'prerelease'; - } - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return key; + } else { + SHORTSPLIT.lastIndex = 2 + var match = SHORTSPLIT.exec(arg) + var end = match.index + var value = + match[0] || + len === (j = i + 1) || + argv[j][0] === "-" || + bools[arg[end - 1]] !== undefined || + argv[(i = j)] + + for (j = 1; j < end; ) { + set(out, arg[j], ++j !== end || value, alias, unknown) } } } } + + for (var key in values) { + if (out[key] === undefined) { + out[key] = values[key] + } + } + + return out } -exports.compareIdentifiers = compareIdentifiers; -var numeric = /^[0-9]+$/; -function compareIdentifiers(a, b) { - var anum = numeric.test(a); - var bnum = numeric.test(b); +/***/ }), +/* 173 */ +/***/ (function(module, exports, __webpack_require__) { - if (anum && bnum) { - a = +a; - b = +b; - } +"use strict"; - return (anum && !bnum) ? -1 : - (bnum && !anum) ? 1 : - a < b ? -1 : - a > b ? 1 : - 0; -} -exports.rcompareIdentifiers = rcompareIdentifiers; -function rcompareIdentifiers(a, b) { - return compareIdentifiers(b, a); -} +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.commands = undefined; -exports.major = major; -function major(a, loose) { - return new SemVer(a, loose).major; -} +var _bootstrap = __webpack_require__(174); -exports.minor = minor; -function minor(a, loose) { - return new SemVer(a, loose).minor; -} +var _clean = __webpack_require__(258); -exports.patch = patch; -function patch(a, loose) { - return new SemVer(a, loose).patch; -} +var _run = __webpack_require__(279); -exports.compare = compare; -function compare(a, b, loose) { - return new SemVer(a, loose).compare(new SemVer(b, loose)); -} +var _watch = __webpack_require__(280); -exports.compareLoose = compareLoose; -function compareLoose(a, b) { - return compare(a, b, true); -} +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +const commands = exports.commands = { + bootstrap: _bootstrap.BootstrapCommand, + clean: _clean.CleanCommand, + run: _run.RunCommand, + watch: _watch.WatchCommand +}; -exports.rcompare = rcompare; -function rcompare(a, b, loose) { - return compare(b, a, loose); -} +/***/ }), +/* 174 */ +/***/ (function(module, exports, __webpack_require__) { -exports.sort = sort; -function sort(list, loose) { - return list.sort(function(a, b) { - return exports.compare(a, b, loose); - }); -} +"use strict"; -exports.rsort = rsort; -function rsort(list, loose) { - return list.sort(function(a, b) { - return exports.rcompare(a, b, loose); - }); -} -exports.gt = gt; -function gt(a, b, loose) { - return compare(a, b, loose) > 0; -} +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.BootstrapCommand = undefined; -exports.lt = lt; -function lt(a, b, loose) { - return compare(a, b, loose) < 0; -} +var _chalk = __webpack_require__(26); -exports.eq = eq; -function eq(a, b, loose) { - return compare(a, b, loose) === 0; -} +var _chalk2 = _interopRequireDefault(_chalk); -exports.neq = neq; -function neq(a, b, loose) { - return compare(a, b, loose) !== 0; -} +var _link_project_executables = __webpack_require__(175); -exports.gte = gte; -function gte(a, b, loose) { - return compare(a, b, loose) >= 0; -} +var _log = __webpack_require__(40); -exports.lte = lte; -function lte(a, b, loose) { - return compare(a, b, loose) <= 0; -} +var _parallelize = __webpack_require__(98); -exports.cmp = cmp; -function cmp(a, op, b, loose) { - var ret; - switch (op) { - case '===': - if (typeof a === 'object') a = a.version; - if (typeof b === 'object') b = b.version; - ret = a === b; - break; - case '!==': - if (typeof a === 'object') a = a.version; - if (typeof b === 'object') b = b.version; - ret = a !== b; - break; - case '': case '=': case '==': ret = eq(a, b, loose); break; - case '!=': ret = neq(a, b, loose); break; - case '>': ret = gt(a, b, loose); break; - case '>=': ret = gte(a, b, loose); break; - case '<': ret = lt(a, b, loose); break; - case '<=': ret = lte(a, b, loose); break; - default: throw new TypeError('Invalid operator: ' + op); - } - return ret; -} +var _projects = __webpack_require__(47); -exports.Comparator = Comparator; -function Comparator(comp, loose) { - if (comp instanceof Comparator) { - if (comp.loose === loose) - return comp; - else - comp = comp.value; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - if (!(this instanceof Comparator)) - return new Comparator(comp, loose); +function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ - debug('comparator', comp, loose); - this.loose = loose; - this.parse(comp); - if (this.semver === ANY) - this.value = ''; - else - this.value = this.operator + this.semver.version; +const BootstrapCommand = exports.BootstrapCommand = { + description: 'Install dependencies and crosslink projects', + name: 'bootstrap', + run(projects, projectGraph, { options }) { + return _asyncToGenerator(function* () { + const batchedProjectsByWorkspace = (0, _projects.topologicallyBatchProjects)(projects, projectGraph, { + batchByWorkspace: true + }); + const batchedProjects = (0, _projects.topologicallyBatchProjects)(projects, projectGraph); + const extraArgs = [...(options['frozen-lockfile'] === true ? ['--frozen-lockfile'] : []), ...(options['prefer-offline'] === true ? ['--prefer-offline'] : [])]; + _log.log.write(_chalk2.default.bold('\nRunning installs in topological order:')); + for (const batch of batchedProjectsByWorkspace) { + for (const project of batch) { + if (project.isWorkspaceProject) { + _log.log.write(`Skipping workspace project: ${project.name}`); + continue; + } + if (project.hasDependencies()) { + yield project.installDependencies({ extraArgs }); + } + } + } + _log.log.write(_chalk2.default.bold('\nInstalls completed, linking package executables:\n')); + yield (0, _link_project_executables.linkProjectExecutables)(projects, projectGraph); + /** + * At the end of the bootstrapping process we call all `kbn:bootstrap` scripts + * in the list of projects. We do this because some projects need to be + * transpiled before they can be used. Ideally we shouldn't do this unless we + * have to, as it will slow down the bootstrapping process. + */ + _log.log.write(_chalk2.default.bold('\nLinking executables completed, running `kbn:bootstrap` scripts\n')); + yield (0, _parallelize.parallelizeBatches)(batchedProjects, (() => { + var _ref = _asyncToGenerator(function* (pkg) { + if (pkg.hasScript('kbn:bootstrap')) { + yield pkg.runScriptStreaming('kbn:bootstrap'); + } + }); - debug('comp', this); -} + return function (_x) { + return _ref.apply(this, arguments); + }; + })()); + _log.log.write(_chalk2.default.green.bold('\nBootstrapping completed!\n')); + })(); + } +}; -var ANY = {}; -Comparator.prototype.parse = function(comp) { - var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; - var m = comp.match(r); +/***/ }), +/* 175 */ +/***/ (function(module, exports, __webpack_require__) { - if (!m) - throw new TypeError('Invalid comparator: ' + comp); +"use strict"; - this.operator = m[1]; - if (this.operator === '=') - this.operator = ''; - // if it literally is just '>' or '' then allow anything. - if (!m[2]) - this.semver = ANY; - else - this.semver = new SemVer(m[2], this.loose); -}; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.linkProjectExecutables = undefined; -Comparator.prototype.toString = function() { - return this.value; -}; +/** + * Yarn does not link the executables from dependencies that are installed + * using `link:` https://github.com/yarnpkg/yarn/pull/5046 + * + * We simulate this functionality by walking through each project's project + * dependencies, and manually linking their executables if defined. The logic + * for linking was mostly adapted from lerna: https://github.com/lerna/lerna/blob/1d7eb9eeff65d5a7de64dea73613b1bf6bfa8d57/src/PackageUtilities.js#L348 + */ +let linkProjectExecutables = exports.linkProjectExecutables = (() => { + var _ref = _asyncToGenerator(function* (projectsByName, projectGraph) { + for (const [projectName, projectDeps] of projectGraph) { + const project = projectsByName.get(projectName); + const binsDir = (0, _path.resolve)(project.nodeModulesLocation, '.bin'); + for (const projectDep of projectDeps) { + const executables = projectDep.getExecutables(); + for (const name of Object.keys(executables)) { + const srcPath = executables[name]; + // existing logic from lerna -- ensure that the bin we are going to + // point to exists or ignore it + if (!(yield (0, _fs.isFile)(srcPath))) { + continue; + } + const dest = (0, _path.resolve)(binsDir, name); + // Get relative project path with normalized path separators. + const projectRelativePath = (0, _path.relative)(project.path, srcPath).split(_path.sep).join('/'); + _log.log.write(_chalk2.default`{dim [${project.name}]} ${name} -> {dim ${projectRelativePath}}`); + yield (0, _fs.mkdirp)((0, _path.dirname)(dest)); + yield (0, _fs.createSymlink)(srcPath, dest, 'exec'); + yield (0, _fs.chmod)(dest, '755'); + } + } + } + }); -Comparator.prototype.test = function(version) { - debug('Comparator.test', version, this.loose); + return function linkProjectExecutables(_x, _x2) { + return _ref.apply(this, arguments); + }; +})(); - if (this.semver === ANY) - return true; +var _path = __webpack_require__(5); - if (typeof version === 'string') - version = new SemVer(version, this.loose); +var _chalk = __webpack_require__(26); - return cmp(version, this.operator, this.semver, this.loose); -}; +var _chalk2 = _interopRequireDefault(_chalk); -Comparator.prototype.intersects = function(comp, loose) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required'); - } +var _fs = __webpack_require__(70); - var rangeTmp; +var _log = __webpack_require__(40); - if (this.operator === '') { - rangeTmp = new Range(comp.value, loose); - return satisfies(this.value, rangeTmp, loose); - } else if (comp.operator === '') { - rangeTmp = new Range(this.value, loose); - return satisfies(comp.semver, rangeTmp, loose); - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - var sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>'); - var sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<'); - var sameSemVer = this.semver.version === comp.semver.version; - var differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<='); - var oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, loose) && - ((this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<')); - var oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, loose) && - ((this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>')); +function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ - return sameDirectionIncreasing || sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || oppositeDirectionsGreaterThan; -}; +/***/ }), +/* 176 */ +/***/ (function(module, exports, __webpack_require__) { +// On windows, create a .cmd file. +// Read the #! in the file to see what it uses. The vast majority +// of the time, this will be either: +// "#!/usr/bin/env " +// or: +// "#! " +// +// Write a binroot/pkg.bin + ".cmd" file that has this line in it: +// @ %~dp0 %* -exports.Range = Range; -function Range(range, loose) { - if (range instanceof Range) { - if (range.loose === loose) { - return range; - } else { - return new Range(range.raw, loose); - } - } +module.exports = cmdShim +cmdShim.ifExists = cmdShimIfExists - if (range instanceof Comparator) { - return new Range(range.value, loose); - } +var fs = __webpack_require__(61) - if (!(this instanceof Range)) - return new Range(range, loose); +var mkdir = __webpack_require__(116) + , path = __webpack_require__(5) + , shebangExpr = /^#\!\s*(?:\/usr\/bin\/env)?\s*([^ \t]+)(.*)$/ - this.loose = loose; +function cmdShimIfExists (from, to, cb) { + fs.stat(from, function (er) { + if (er) return cb() + cmdShim(from, to, cb) + }) +} - // First, split based on boolean or || - this.raw = range; - this.set = range.split(/\s*\|\|\s*/).map(function(range) { - return this.parseRange(range.trim()); - }, this).filter(function(c) { - // throw out any that are not relevant for whatever reason - return c.length; - }); +// Try to unlink, but ignore errors. +// Any problems will surface later. +function rm (path, cb) { + fs.unlink(path, function(er) { + cb() + }) +} - if (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range); - } +function cmdShim (from, to, cb) { + fs.stat(from, function (er, stat) { + if (er) + return cb(er) - this.format(); + cmdShim_(from, to, cb) + }) } -Range.prototype.format = function() { - this.range = this.set.map(function(comps) { - return comps.join(' ').trim(); - }).join('||').trim(); - return this.range; -}; - -Range.prototype.toString = function() { - return this.range; -}; +function cmdShim_ (from, to, cb) { + var then = times(2, next, cb) + rm(to, then) + rm(to + ".cmd", then) -Range.prototype.parseRange = function(range) { - var loose = this.loose; - range = range.trim(); - debug('range', range, loose); - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; - range = range.replace(hr, hyphenReplace); - debug('hyphen replace', range); - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); - debug('comparator trim', range, re[COMPARATORTRIM]); + function next(er) { + writeShim(from, to, cb) + } +} - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[TILDETRIM], tildeTrimReplace); +function writeShim (from, to, cb) { + // make a cmd file and a sh script + // First, check if the bin is a #! of some sort. + // If not, then assume it's something that'll be compiled, or some other + // sort of script, and just call it directly. + mkdir(path.dirname(to), function (er) { + if (er) + return cb(er) + fs.readFile(from, "utf8", function (er, data) { + if (er) return writeShim_(from, to, null, null, cb) + var firstLine = data.trim().split(/\r*\n/)[0] + , shebang = firstLine.match(shebangExpr) + if (!shebang) return writeShim_(from, to, null, null, cb) + var prog = shebang[1] + , args = shebang[2] || "" + return writeShim_(from, to, prog, args, cb) + }) + }) +} - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[CARETTRIM], caretTrimReplace); +function writeShim_ (from, to, prog, args, cb) { + var shTarget = path.relative(path.dirname(to), from) + , target = shTarget.split("/").join("\\") + , longProg + , shProg = prog && prog.split("\\").join("/") + , shLongProg + shTarget = shTarget.split("\\").join("/") + args = args || "" + if (!prog) { + prog = "\"%~dp0\\" + target + "\"" + shProg = "\"$basedir/" + shTarget + "\"" + args = "" + target = "" + shTarget = "" + } else { + longProg = "\"%~dp0\\" + prog + ".exe\"" + shLongProg = "\"$basedir/" + prog + "\"" + target = "\"%~dp0\\" + target + "\"" + shTarget = "\"$basedir/" + shTarget + "\"" + } - // normalize spaces - range = range.split(/\s+/).join(' '); + // @IF EXIST "%~dp0\node.exe" ( + // "%~dp0\node.exe" "%~dp0\.\node_modules\npm\bin\npm-cli.js" %* + // ) ELSE ( + // SETLOCAL + // SET PATHEXT=%PATHEXT:;.JS;=;% + // node "%~dp0\.\node_modules\npm\bin\npm-cli.js" %* + // ) + var cmd + if (longProg) { + cmd = "@IF EXIST " + longProg + " (\r\n" + + " " + longProg + " " + args + " " + target + " %*\r\n" + + ") ELSE (\r\n" + + " @SETLOCAL\r\n" + + " @SET PATHEXT=%PATHEXT:;.JS;=;%\r\n" + + " " + prog + " " + args + " " + target + " %*\r\n" + + ")" + } else { + cmd = "@" + prog + " " + args + " " + target + " %*\r\n" + } - // At this point, the range is completely trimmed and - // ready to be split into comparators. + // #!/bin/sh + // basedir=`dirname "$0"` + // + // case `uname` in + // *CYGWIN*) basedir=`cygpath -w "$basedir"`;; + // esac + // + // if [ -x "$basedir/node.exe" ]; then + // "$basedir/node.exe" "$basedir/node_modules/npm/bin/npm-cli.js" "$@" + // ret=$? + // else + // node "$basedir/node_modules/npm/bin/npm-cli.js" "$@" + // ret=$? + // fi + // exit $ret - var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; - var set = range.split(' ').map(function(comp) { - return parseComparator(comp, loose); - }).join(' ').split(/\s+/); - if (this.loose) { - // in loose mode, throw out any that are not valid comparators - set = set.filter(function(comp) { - return !!comp.match(compRe); - }); - } - set = set.map(function(comp) { - return new Comparator(comp, loose); - }); + var sh = "#!/bin/sh\n" - return set; -}; + if (shLongProg) { + sh = sh + + "basedir=$(dirname \"$(echo \"$0\" | sed -e 's,\\\\,/,g')\")\n" + + "\n" + + "case `uname` in\n" + + " *CYGWIN*) basedir=`cygpath -w \"$basedir\"`;;\n" + + "esac\n" + + "\n" -Range.prototype.intersects = function(range, loose) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required'); + sh = sh + + "if [ -x "+shLongProg+" ]; then\n" + + " " + shLongProg + " " + args + " " + shTarget + " \"$@\"\n" + + " ret=$?\n" + + "else \n" + + " " + shProg + " " + args + " " + shTarget + " \"$@\"\n" + + " ret=$?\n" + + "fi\n" + + "exit $ret\n" + } else { + sh = shProg + " " + args + " " + shTarget + " \"$@\"\n" + + "exit $?\n" } - return this.set.some(function(thisComparators) { - return thisComparators.every(function(thisComparator) { - return range.set.some(function(rangeComparators) { - return rangeComparators.every(function(rangeComparator) { - return thisComparator.intersects(rangeComparator, loose); - }); - }); - }); - }); -}; + var then = times(2, next, cb) + fs.writeFile(to + ".cmd", cmd, "utf8", then) + fs.writeFile(to, sh, "utf8", then) + function next () { + chmodShim(to, cb) + } +} -// Mostly just for testing and legacy API reasons -exports.toComparators = toComparators; -function toComparators(range, loose) { - return new Range(range, loose).set.map(function(comp) { - return comp.map(function(c) { - return c.value; - }).join(' ').trim().split(' '); - }); +function chmodShim (to, cb) { + var then = times(2, cb, cb) + fs.chmod(to, 0755, then) + fs.chmod(to + ".cmd", 0755, then) } -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -function parseComparator(comp, loose) { - debug('comp', comp); - comp = replaceCarets(comp, loose); - debug('caret', comp); - comp = replaceTildes(comp, loose); - debug('tildes', comp); - comp = replaceXRanges(comp, loose); - debug('xrange', comp); - comp = replaceStars(comp, loose); - debug('stars', comp); - return comp; +function times(n, ok, cb) { + var errState = null + return function(er) { + if (!errState) { + if (er) + cb(errState = er) + else if (--n === 0) + ok() + } + } } -function isX(id) { - return !id || id.toLowerCase() === 'x' || id === '*'; + +/***/ }), +/* 177 */ +/***/ (function(module, exports, __webpack_require__) { + +var fs = __webpack_require__(115) +var constants = __webpack_require__(178) + +var origCwd = process.cwd +var cwd = null + +var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform + +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd } +try { + process.cwd() +} catch (er) {} -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 -function replaceTildes(comp, loose) { - return comp.trim().split(/\s+/).map(function(comp) { - return replaceTilde(comp, loose); - }).join(' '); +var chdir = process.chdir +process.chdir = function(d) { + cwd = null + chdir.call(process, d) } -function replaceTilde(comp, loose) { - var r = loose ? re[TILDELOOSE] : re[TILDE]; - return comp.replace(r, function(_, M, m, p, pr) { - debug('tilde', comp, _, M, m, p, pr); - var ret; - - if (isX(M)) - ret = ''; - else if (isX(m)) - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; - else if (isX(p)) - // ~1.2 == >=1.2.0 <1.3.0 - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; - else if (pr) { - debug('replaceTilde pr', pr); - if (pr.charAt(0) !== '-') - pr = '-' + pr; - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + M + '.' + (+m + 1) + '.0'; - } else - // ~1.2.3 == >=1.2.3 <1.3.0 - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0'; +module.exports = patch - debug('tilde return', ret); - return ret; - }); -} +function patch (fs) { + // (re-)implement some things that are known busted or missing. -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 -// ^1.2.3 --> >=1.2.3 <2.0.0 -// ^1.2.0 --> >=1.2.0 <2.0.0 -function replaceCarets(comp, loose) { - return comp.trim().split(/\s+/).map(function(comp) { - return replaceCaret(comp, loose); - }).join(' '); -} + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs) + } -function replaceCaret(comp, loose) { - debug('caret', comp, loose); - var r = loose ? re[CARETLOOSE] : re[CARET]; - return comp.replace(r, function(_, M, m, p, pr) { - debug('caret', comp, _, M, m, p, pr); - var ret; + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) + } - if (isX(M)) - ret = ''; - else if (isX(m)) - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; - else if (isX(p)) { - if (M === '0') - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; - else - ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; - } else if (pr) { - debug('replaceCaret pr', pr); - if (pr.charAt(0) !== '-') - pr = '-' + pr; - if (M === '0') { - if (m === '0') - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + M + '.' + m + '.' + (+p + 1); - else - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + M + '.' + (+m + 1) + '.0'; - } else - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + (+M + 1) + '.0.0'; - } else { - debug('no pr'); - if (M === '0') { - if (m === '0') - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + m + '.' + (+p + 1); - else - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0'; - } else - ret = '>=' + M + '.' + m + '.' + p + - ' <' + (+M + 1) + '.0.0'; - } + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. - debug('caret return', ret); - return ret; - }); -} + fs.chown = chownFix(fs.chown) + fs.fchown = chownFix(fs.fchown) + fs.lchown = chownFix(fs.lchown) -function replaceXRanges(comp, loose) { - debug('replaceXRanges', comp, loose); - return comp.split(/\s+/).map(function(comp) { - return replaceXRange(comp, loose); - }).join(' '); -} + fs.chmod = chmodFix(fs.chmod) + fs.fchmod = chmodFix(fs.fchmod) + fs.lchmod = chmodFix(fs.lchmod) -function replaceXRange(comp, loose) { - comp = comp.trim(); - var r = loose ? re[XRANGELOOSE] : re[XRANGE]; - return comp.replace(r, function(ret, gtlt, M, m, p, pr) { - debug('xRange', comp, ret, gtlt, M, m, p, pr); - var xM = isX(M); - var xm = xM || isX(m); - var xp = xm || isX(p); - var anyX = xp; + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) - if (gtlt === '=' && anyX) - gtlt = ''; + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0'; - } else { - // nothing is forbidden - ret = '*'; - } - } else if (gtlt && anyX) { - // replace X with 0 - if (xm) - m = 0; - if (xp) - p = 0; + fs.stat = statFix(fs.stat) + fs.fstat = statFix(fs.fstat) + fs.lstat = statFix(fs.lstat) - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - // >1.2.3 => >= 1.2.4 - gtlt = '>='; - if (xm) { - M = +M + 1; - m = 0; - p = 0; - } else if (xp) { - m = +m + 1; - p = 0; - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<'; - if (xm) - M = +M + 1; - else - m = +m + 1; - } + fs.statSync = statFixSync(fs.statSync) + fs.fstatSync = statFixSync(fs.fstatSync) + fs.lstatSync = statFixSync(fs.lstatSync) - ret = gtlt + M + '.' + m + '.' + p; - } else if (xm) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; - } else if (xp) { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + // if lchmod/lchown do not exist, then make them no-ops + if (!fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb) } + fs.lchmodSync = function () {} + } + if (!fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb) + } + fs.lchownSync = function () {} + } - debug('xRange return', ret); - - return ret; - }); -} - -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -function replaceStars(comp, loose) { - debug('replaceStars', comp, loose); - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re[STAR], ''); -} - -// This function is passed to string.replace(re[HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0 -function hyphenReplace($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) { + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. - if (isX(fM)) - from = ''; - else if (isX(fm)) - from = '>=' + fM + '.0.0'; - else if (isX(fp)) - from = '>=' + fM + '.' + fm + '.0'; - else - from = '>=' + from; + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform === "win32") { + fs.rename = (function (fs$rename) { return function (from, to, cb) { + var start = Date.now() + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er) + }) + }, backoff) + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er) + }) + }})(fs.rename) + } - if (isX(tM)) - to = ''; - else if (isX(tm)) - to = '<' + (+tM + 1) + '.0.0'; - else if (isX(tp)) - to = '<' + tM + '.' + (+tm + 1) + '.0'; - else if (tpr) - to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; - else - to = '<=' + to; + // if read() returns EAGAIN, then just try it again. + fs.read = (function (fs$read) { return function (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) + } + } + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + }})(fs.read) - return (from + ' ' + to).trim(); + fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue + } + throw er + } + } + }})(fs.readSync) } - -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function(version) { - if (!version) - return false; - - if (typeof version === 'string') - version = new SemVer(version, this.loose); - - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version)) - return true; +function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) + return + } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) + }) + }) + }) } - return false; -}; -function testSet(set, version) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) - return false; + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) + + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true + var ret + try { + ret = fs.fchmodSync(fd, mode) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret } +} - if (version.prerelease.length) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (var i = 0; i < set.length; i++) { - debug(set[i].semver); - if (set[i].semver === ANY) - continue; +function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK")) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) + } - if (set[i].semver.prerelease.length > 0) { - var allowed = set[i].semver; - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) - return true; + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } } + return ret } - // Version has a -pre, but it's not one of the ones we like. - return false; + } else { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} } - - return true; } -exports.satisfies = satisfies; -function satisfies(version, range, loose) { - try { - range = new Range(range, loose); - } catch (er) { - return false; +function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) } - return range.test(version); } -exports.maxSatisfying = maxSatisfying; -function maxSatisfying(versions, range, loose) { - var max = null; - var maxSV = null; - try { - var rangeObj = new Range(range, loose); - } catch (er) { - return null; - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { // satisfies(v, range, loose) - if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) - max = v; - maxSV = new SemVer(max, loose); - } +function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er } - }) - return max; + } } -exports.minSatisfying = minSatisfying; -function minSatisfying(versions, range, loose) { - var min = null; - var minSV = null; - try { - var rangeObj = new Range(range, loose); - } catch (er) { - return null; + +function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) } - versions.forEach(function (v) { - if (rangeObj.test(v)) { // satisfies(v, range, loose) - if (!min || minSV.compare(v) === 1) { // compare(min, v, true) - min = v; - minSV = new SemVer(min, loose); - } - } - }) - return min; } -exports.validRange = validRange; -function validRange(range, loose) { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, loose).range || '*'; - } catch (er) { - return null; +function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } } } -// Determine if version is less than all the versions possible in the range -exports.ltr = ltr; -function ltr(version, range, loose) { - return outside(version, range, '<', loose); + +function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, cb) { + return orig.call(fs, target, function (er, stats) { + if (!stats) return cb.apply(this, arguments) + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + if (cb) cb.apply(this, arguments) + }) + } } -// Determine if version is greater than all the versions possible in the range. -exports.gtr = gtr; -function gtr(version, range, loose) { - return outside(version, range, '>', loose); +function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target) { + var stats = orig.call(fs, target) + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + return stats; + } } -exports.outside = outside; -function outside(version, range, hilo, loose) { - version = new SemVer(version, loose); - range = new Range(range, loose); +// ENOSYS means that the fs doesn't support the op. Just ignore +// that, because it doesn't matter. +// +// if there's no getuid, or if getuid() is something other +// than 0, and the error is EINVAL or EPERM, then just ignore +// it. +// +// This specific case is a silent failure in cp, install, tar, +// and most other unix tools that manage permissions. +// +// When running as root, or if other types of errors are +// encountered, then it's strict. +function chownErOk (er) { + if (!er) + return true - var gtfn, ltefn, ltfn, comp, ecomp; - switch (hilo) { - case '>': - gtfn = gt; - ltefn = lte; - ltfn = lt; - comp = '>'; - ecomp = '>='; - break; - case '<': - gtfn = lt; - ltefn = gte; - ltfn = gt; - comp = '<'; - ecomp = '<='; - break; - default: - throw new TypeError('Must provide a hilo val of "<" or ">"'); + if (er.code === "ENOSYS") + return true + + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true } - // If it satisifes the range it is not outside - if (satisfies(version, range, loose)) { - return false; + return false +} + + +/***/ }), +/* 178 */ +/***/ (function(module, exports) { + +module.exports = require("constants"); + +/***/ }), +/* 179 */ +/***/ (function(module, exports, __webpack_require__) { + +var Stream = __webpack_require__(39).Stream + +module.exports = legacy + +function legacy (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream } - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i]; + Stream.call(this); - var high = null; - var low = null; + var self = this; - comparators.forEach(function(comparator) { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; + + this.flags = 'r'; + this.mode = 438; /*=0666*/ + this.bufferSize = 64 * 1024; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } + + if (this.encoding) this.setEncoding(this.encoding); + + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); } - high = high || comparator; - low = low || comparator; - if (gtfn(comparator.semver, high.semver, loose)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, loose)) { - low = comparator; + if (this.end === undefined) { + this.end = Infinity; + } else if ('number' !== typeof this.end) { + throw TypeError('end must be a Number'); } - }); - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false; - } + if (this.start > this.end) { + throw new Error('start must be <= end'); + } - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false; - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false; + this.pos = this.start; } - } - return true; -} - -exports.prerelease = prerelease; -function prerelease(version, loose) { - var parsed = parse(version, loose); - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null; -} -exports.intersects = intersects; -function intersects(r1, r2, loose) { - r1 = new Range(r1, loose) - r2 = new Range(r2, loose) - return r1.intersects(r2) -} + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; + } + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; + } -/***/ }), -/* 153 */ -/***/ (function(module, exports, __webpack_require__) { + self.fd = fd; + self.emit('open', fd); + self._read(); + }) + } -var parse = __webpack_require__(154); -var correct = __webpack_require__(156); + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); -var genericWarning = ( - 'license should be ' + - 'a valid SPDX license expression (without "LicenseRef"), ' + - '"UNLICENSED", or ' + - '"SEE LICENSE IN "' -); + Stream.call(this); -var fileReferenceRE = /^SEE LICEN[CS]E IN (.+)$/; + this.path = path; + this.fd = null; + this.writable = true; -function startsWith(prefix, string) { - return string.slice(0, prefix.length) === prefix; -} + this.flags = 'w'; + this.encoding = 'binary'; + this.mode = 438; /*=0666*/ + this.bytesWritten = 0; -function usesLicenseRef(ast) { - if (ast.hasOwnProperty('license')) { - var license = ast.license; - return ( - startsWith('LicenseRef', license) || - startsWith('DocumentRef', license) - ); - } else { - return ( - usesLicenseRef(ast.left) || - usesLicenseRef(ast.right) - ); - } -} + options = options || {}; -module.exports = function(argument) { - var ast; + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } - try { - ast = parse(argument); - } catch (e) { - var match - if ( - argument === 'UNLICENSED' || - argument === 'UNLICENCED' - ) { - return { - validForOldPackages: true, - validForNewPackages: true, - unlicensed: true - }; - } else if (match = fileReferenceRE.exec(argument)) { - return { - validForOldPackages: true, - validForNewPackages: true, - inFile: match[1] - }; - } else { - var result = { - validForOldPackages: false, - validForNewPackages: false, - warnings: [genericWarning] - }; - var corrected = correct(argument); - if (corrected) { - result.warnings.push( - 'license is similar to the valid expression "' + corrected + '"' - ); + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); } - return result; + if (this.start < 0) { + throw new Error('start must be >= zero'); + } + + this.pos = this.start; } - } - if (usesLicenseRef(ast)) { - return { - validForNewPackages: false, - validForOldPackages: false, - spdx: true, - warnings: [genericWarning] - }; - } else { - return { - validForNewPackages: true, - validForOldPackages: true, - spdx: true - }; + this.busy = false; + this._queue = []; + + if (this.fd === null) { + this._open = fs.open; + this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); + this.flush(); + } } -}; +} /***/ }), -/* 154 */ +/* 180 */ /***/ (function(module, exports, __webpack_require__) { -var parser = __webpack_require__(155).parser +var fs = __webpack_require__(13), + path = __webpack_require__(5); -module.exports = function (argument) { - return parser.parse(argument) -} +module.exports = ncp; +ncp.ncp = ncp; +function ncp (source, dest, options, callback) { + var cback = callback; -/***/ }), -/* 155 */ -/***/ (function(module, exports, __webpack_require__) { + if (!callback) { + cback = options; + options = {}; + } -/* WEBPACK VAR INJECTION */(function(module) {/* parser generated by jison 0.4.17 */ -/* - Returns a Parser object of the following structure: + var basePath = process.cwd(), + currentPath = path.resolve(basePath, source), + targetPath = path.resolve(basePath, dest), + filter = options.filter, + rename = options.rename, + transform = options.transform, + clobber = options.clobber !== false, + modified = options.modified, + dereference = options.dereference, + errs = null, + started = 0, + finished = 0, + running = 0, + limit = options.limit || ncp.limit || 16; - Parser: { - yy: {} + limit = (limit < 1) ? 1 : (limit > 512) ? 512 : limit; + + startCopy(currentPath); + + function startCopy(source) { + started++; + if (filter) { + if (filter instanceof RegExp) { + if (!filter.test(source)) { + return cb(true); + } + } + else if (typeof filter === 'function') { + if (!filter(source)) { + return cb(true); + } + } + } + return getStats(source); } - Parser.prototype: { - yy: {}, - trace: function(), - symbols_: {associative list: name ==> number}, - terminals_: {associative list: number ==> name}, - productions_: [...], - performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$), - table: [...], - defaultActions: {...}, - parseError: function(str, hash), - parse: function(input), + function getStats(source) { + var stat = dereference ? fs.stat : fs.lstat; + if (running >= limit) { + return setImmediate(function () { + getStats(source); + }); + } + running++; + stat(source, function (err, stats) { + var item = {}; + if (err) { + return onError(err); + } - lexer: { - EOF: 1, - parseError: function(str, hash), - setInput: function(input), - input: function(), - unput: function(str), - more: function(), - less: function(n), - pastInput: function(), - upcomingInput: function(), - showPosition: function(), - test_match: function(regex_match_array, rule_index), - next: function(), - lex: function(), - begin: function(condition), - popState: function(), - _currentRules: function(), - topState: function(), - pushState: function(condition), + // We need to get the mode from the stats object and preserve it. + item.name = source; + item.mode = stats.mode; + item.mtime = stats.mtime; //modified time + item.atime = stats.atime; //access time - options: { - ranges: boolean (optional: true ==> token location info will include a .range[] member) - flex: boolean (optional: true ==> flex-like lexing behaviour where the rules are tested exhaustively to find the longest match) - backtrack_lexer: boolean (optional: true ==> lexer regexes are tested in order and for each matching regex the action code is invoked; the lexer terminates the scan when a token is returned by the action code) - }, + if (stats.isDirectory()) { + return onDir(item); + } + else if (stats.isFile()) { + return onFile(item); + } + else if (stats.isSymbolicLink()) { + // Symlinks don't really need to know about the mode. + return onLink(source); + } + }); + } - performAction: function(yy, yy_, $avoiding_name_collisions, YY_START), - rules: [...], - conditions: {associative list: name ==> set}, + function onFile(file) { + var target = file.name.replace(currentPath, targetPath); + if(rename) { + target = rename(target); } + isWritable(target, function (writable) { + if (writable) { + return copyFile(file, target); + } + if(clobber) { + rmFile(target, function () { + copyFile(file, target); + }); + } + if (modified) { + var stat = dereference ? fs.stat : fs.lstat; + stat(target, function(err, stats) { + //if souce modified time greater to target modified time copy file + if (file.mtime.getTime()>stats.mtime.getTime()) + copyFile(file, target); + else return cb(); + }); + } + else { + return cb(); + } + }); } + function copyFile(file, target) { + var readStream = fs.createReadStream(file.name), + writeStream = fs.createWriteStream(target, { mode: file.mode }); + + readStream.on('error', onError); + writeStream.on('error', onError); + + if(transform) { + transform(readStream, writeStream, file); + } else { + writeStream.on('open', function() { + readStream.pipe(writeStream); + }); + } + writeStream.once('finish', function() { + if (modified) { + //target file modified date sync. + fs.utimesSync(target, file.atime, file.mtime); + cb(); + } + else cb(); + }); + } - token location info (@$, _$, etc.): { - first_line: n, - last_line: n, - first_column: n, - last_column: n, - range: [start_number, end_number] (where the numbers are indexes into the input string, regular zero-based) + function rmFile(file, done) { + fs.unlink(file, function (err) { + if (err) { + return onError(err); + } + return done(); + }); } + function onDir(dir) { + var target = dir.name.replace(currentPath, targetPath); + isWritable(target, function (writable) { + if (writable) { + return mkDir(dir, target); + } + copyDir(dir.name); + }); + } - the parseError function receives a 'hash' object with these members for lexer and parser errors: { - text: (matched text) - token: (the produced terminal token, if any) - line: (yylineno) + function mkDir(dir, target) { + fs.mkdir(target, dir.mode, function (err) { + if (err) { + return onError(err); + } + copyDir(dir.name); + }); } - while parser (grammar) errors will also provide these members, i.e. parser errors deliver a superset of attributes: { - loc: (yylloc) - expected: (string describing the set of expected tokens) - recoverable: (boolean: TRUE when the parser has a error recovery rule available for this particular error) + + function copyDir(dir) { + fs.readdir(dir, function (err, items) { + if (err) { + return onError(err); + } + items.forEach(function (item) { + startCopy(path.join(dir, item)); + }); + return cb(); + }); } -*/ -var spdxparse = (function(){ -var o=function(k,v,o,l){for(o=o||{},l=k.length;l--;o[k[l]]=v);return o},$V0=[1,5],$V1=[1,6],$V2=[1,7],$V3=[1,4],$V4=[1,9],$V5=[1,10],$V6=[5,14,15,17],$V7=[5,12,14,15,17]; -var parser = {trace: function trace() { }, -yy: {}, -symbols_: {"error":2,"start":3,"expression":4,"EOS":5,"simpleExpression":6,"LICENSE":7,"PLUS":8,"LICENSEREF":9,"DOCUMENTREF":10,"COLON":11,"WITH":12,"EXCEPTION":13,"AND":14,"OR":15,"OPEN":16,"CLOSE":17,"$accept":0,"$end":1}, -terminals_: {2:"error",5:"EOS",7:"LICENSE",8:"PLUS",9:"LICENSEREF",10:"DOCUMENTREF",11:"COLON",12:"WITH",13:"EXCEPTION",14:"AND",15:"OR",16:"OPEN",17:"CLOSE"}, -productions_: [0,[3,2],[6,1],[6,2],[6,1],[6,3],[4,1],[4,3],[4,3],[4,3],[4,3]], -performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate /* action[1] */, $$ /* vstack */, _$ /* lstack */) { -/* this == yyval */ -var $0 = $$.length - 1; -switch (yystate) { -case 1: -return this.$ = $$[$0-1] -break; -case 2: case 4: case 5: -this.$ = {license: yytext} -break; -case 3: -this.$ = {license: $$[$0-1], plus: true} -break; -case 6: -this.$ = $$[$0] -break; -case 7: -this.$ = {exception: $$[$0]} -this.$.license = $$[$0-2].license -if ($$[$0-2].hasOwnProperty('plus')) { - this.$.plus = $$[$0-2].plus -} -break; -case 8: -this.$ = {conjunction: 'and', left: $$[$0-2], right: $$[$0]} -break; -case 9: -this.$ = {conjunction: 'or', left: $$[$0-2], right: $$[$0]} -break; -case 10: -this.$ = $$[$0-1] -break; -} -}, -table: [{3:1,4:2,6:3,7:$V0,9:$V1,10:$V2,16:$V3},{1:[3]},{5:[1,8],14:$V4,15:$V5},o($V6,[2,6],{12:[1,11]}),{4:12,6:3,7:$V0,9:$V1,10:$V2,16:$V3},o($V7,[2,2],{8:[1,13]}),o($V7,[2,4]),{11:[1,14]},{1:[2,1]},{4:15,6:3,7:$V0,9:$V1,10:$V2,16:$V3},{4:16,6:3,7:$V0,9:$V1,10:$V2,16:$V3},{13:[1,17]},{14:$V4,15:$V5,17:[1,18]},o($V7,[2,3]),{9:[1,19]},o($V6,[2,8]),o([5,15,17],[2,9],{14:$V4}),o($V6,[2,7]),o($V6,[2,10]),o($V7,[2,5])], -defaultActions: {8:[2,1]}, -parseError: function parseError(str, hash) { - if (hash.recoverable) { - this.trace(str); - } else { - function _parseError (msg, hash) { - this.message = msg; - this.hash = hash; - } - _parseError.prototype = Error; + function onLink(link) { + var target = link.replace(currentPath, targetPath); + fs.readlink(link, function (err, resolvedPath) { + if (err) { + return onError(err); + } + checkLink(resolvedPath, target); + }); + } - throw new _parseError(str, hash); + function checkLink(resolvedPath, target) { + if (dereference) { + resolvedPath = path.resolve(basePath, resolvedPath); } -}, -parse: function parse(input) { - var self = this, stack = [0], tstack = [], vstack = [null], lstack = [], table = this.table, yytext = '', yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1; - var args = lstack.slice.call(arguments, 1); - var lexer = Object.create(this.lexer); - var sharedState = { yy: {} }; - for (var k in this.yy) { - if (Object.prototype.hasOwnProperty.call(this.yy, k)) { - sharedState.yy[k] = this.yy[k]; + isWritable(target, function (writable) { + if (writable) { + return makeLink(resolvedPath, target); + } + fs.readlink(target, function (err, targetDest) { + if (err) { + return onError(err); + } + if (dereference) { + targetDest = path.resolve(basePath, targetDest); + } + if (targetDest === resolvedPath) { + return cb(); } + return rmFile(target, function () { + makeLink(resolvedPath, target); + }); + }); + }); + } + + function makeLink(linkPath, target) { + fs.symlink(linkPath, target, function (err) { + if (err) { + return onError(err); + } + return cb(); + }); + } + + function isWritable(path, done) { + fs.lstat(path, function (err) { + if (err) { + if (err.code === 'ENOENT') return done(true); + return done(false); + } + return done(false); + }); + } + + function onError(err) { + if (options.stopOnError) { + return cback(err); } - lexer.setInput(input, sharedState.yy); - sharedState.yy.lexer = lexer; - sharedState.yy.parser = this; - if (typeof lexer.yylloc == 'undefined') { - lexer.yylloc = {}; + else if (!errs && options.errs) { + errs = fs.createWriteStream(options.errs); } - var yyloc = lexer.yylloc; - lstack.push(yyloc); - var ranges = lexer.options && lexer.options.ranges; - if (typeof sharedState.yy.parseError === 'function') { - this.parseError = sharedState.yy.parseError; - } else { - this.parseError = Object.getPrototypeOf(this).parseError; + else if (!errs) { + errs = []; } - function popStack(n) { - stack.length = stack.length - 2 * n; - vstack.length = vstack.length - n; - lstack.length = lstack.length - n; + if (typeof errs.write === 'undefined') { + errs.push(err); } - _token_stack: - var lex = function () { - var token; - token = lexer.lex() || EOF; - if (typeof token !== 'number') { - token = self.symbols_[token] || token; - } - return token; - }; - var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected; - while (true) { - state = stack[stack.length - 1]; - if (this.defaultActions[state]) { - action = this.defaultActions[state]; - } else { - if (symbol === null || typeof symbol == 'undefined') { - symbol = lex(); - } - action = table[state] && table[state][symbol]; - } - if (typeof action === 'undefined' || !action.length || !action[0]) { - var errStr = ''; - expected = []; - for (p in table[state]) { - if (this.terminals_[p] && p > TERROR) { - expected.push('\'' + this.terminals_[p] + '\''); - } - } - if (lexer.showPosition) { - errStr = 'Parse error on line ' + (yylineno + 1) + ':\n' + lexer.showPosition() + '\nExpecting ' + expected.join(', ') + ', got \'' + (this.terminals_[symbol] || symbol) + '\''; - } else { - errStr = 'Parse error on line ' + (yylineno + 1) + ': Unexpected ' + (symbol == EOF ? 'end of input' : '\'' + (this.terminals_[symbol] || symbol) + '\''); - } - this.parseError(errStr, { - text: lexer.match, - token: this.terminals_[symbol] || symbol, - line: lexer.yylineno, - loc: yyloc, - expected: expected - }); - } - if (action[0] instanceof Array && action.length > 1) { - throw new Error('Parse Error: multiple actions possible at state: ' + state + ', token: ' + symbol); - } - switch (action[0]) { - case 1: - stack.push(symbol); - vstack.push(lexer.yytext); - lstack.push(lexer.yylloc); - stack.push(action[1]); - symbol = null; - if (!preErrorSymbol) { - yyleng = lexer.yyleng; - yytext = lexer.yytext; - yylineno = lexer.yylineno; - yyloc = lexer.yylloc; - if (recovering > 0) { - recovering--; - } - } else { - symbol = preErrorSymbol; - preErrorSymbol = null; - } - break; - case 2: - len = this.productions_[action[1]][1]; - yyval.$ = vstack[vstack.length - len]; - yyval._$ = { - first_line: lstack[lstack.length - (len || 1)].first_line, - last_line: lstack[lstack.length - 1].last_line, - first_column: lstack[lstack.length - (len || 1)].first_column, - last_column: lstack[lstack.length - 1].last_column - }; - if (ranges) { - yyval._$.range = [ - lstack[lstack.length - (len || 1)].range[0], - lstack[lstack.length - 1].range[1] - ]; - } - r = this.performAction.apply(yyval, [ - yytext, - yyleng, - yylineno, - sharedState.yy, - action[1], - vstack, - lstack - ].concat(args)); - if (typeof r !== 'undefined') { - return r; - } - if (len) { - stack = stack.slice(0, -1 * len * 2); - vstack = vstack.slice(0, -1 * len); - lstack = lstack.slice(0, -1 * len); - } - stack.push(this.productions_[action[1]][0]); - vstack.push(yyval.$); - lstack.push(yyval._$); - newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; - stack.push(newState); - break; - case 3: - return true; - } + else { + errs.write(err.stack + '\n\n'); } - return true; -}}; -/* generated by jison-lex 0.3.4 */ -var lexer = (function(){ -var lexer = ({ - -EOF:1, + return cb(); + } -parseError:function parseError(str, hash) { - if (this.yy.parser) { - this.yy.parser.parseError(str, hash); - } else { - throw new Error(str); - } - }, + function cb(skipped) { + if (!skipped) running--; + finished++; + if ((started === finished) && (running === 0)) { + if (cback !== undefined ) { + return errs ? cback(errs) : cback(null); + } + } + } +} -// resets the lexer, sets new input -setInput:function (input, yy) { - this.yy = yy || this.yy || {}; - this._input = input; - this._more = this._backtrack = this.done = false; - this.yylineno = this.yyleng = 0; - this.yytext = this.matched = this.match = ''; - this.conditionStack = ['INITIAL']; - this.yylloc = { - first_line: 1, - first_column: 0, - last_line: 1, - last_column: 0 - }; - if (this.options.ranges) { - this.yylloc.range = [0,0]; - } - this.offset = 0; - return this; - }, -// consumes and returns one char from the input -input:function () { - var ch = this._input[0]; - this.yytext += ch; - this.yyleng++; - this.offset++; - this.match += ch; - this.matched += ch; - var lines = ch.match(/(?:\r\n?|\n).*/g); - if (lines) { - this.yylineno++; - this.yylloc.last_line++; - } else { - this.yylloc.last_column++; - } - if (this.options.ranges) { - this.yylloc.range[1]++; - } - this._input = this._input.slice(1); - return ch; - }, -// unshifts one char (or a string) into the input -unput:function (ch) { - var len = ch.length; - var lines = ch.split(/(?:\r\n?|\n)/g); +/***/ }), +/* 181 */ +/***/ (function(module, exports, __webpack_require__) { - this._input = ch + this._input; - this.yytext = this.yytext.substr(0, this.yytext.length - len); - //this.yyleng -= len; - this.offset -= len; - var oldLines = this.match.split(/(?:\r\n?|\n)/g); - this.match = this.match.substr(0, this.match.length - 1); - this.matched = this.matched.substr(0, this.matched.length - 1); +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - if (lines.length - 1) { - this.yylineno -= lines.length - 1; - } - var r = this.yylloc.range; +var pathModule = __webpack_require__(5); +var isWindows = process.platform === 'win32'; +var fs = __webpack_require__(13); - this.yylloc = { - first_line: this.yylloc.first_line, - last_line: this.yylineno + 1, - first_column: this.yylloc.first_column, - last_column: lines ? - (lines.length === oldLines.length ? this.yylloc.first_column : 0) - + oldLines[oldLines.length - lines.length].length - lines[0].length : - this.yylloc.first_column - len - }; +// JavaScript implementation of realpath, ported from node pre-v6 - if (this.options.ranges) { - this.yylloc.range = [r[0], r[0] + this.yyleng - len]; - } - this.yyleng = this.yytext.length; - return this; - }, +var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); -// When called from action, caches matched text and appends it on next action -more:function () { - this._more = true; - return this; - }, +function rethrow() { + // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and + // is fairly slow to generate. + var callback; + if (DEBUG) { + var backtrace = new Error; + callback = debugCallback; + } else + callback = missingCallback; -// When called from action, signals the lexer that this rule fails to match the input, so the next matching rule (regex) should be tested instead. -reject:function () { - if (this.options.backtrack_lexer) { - this._backtrack = true; - } else { - return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n' + this.showPosition(), { - text: "", - token: null, - line: this.yylineno - }); + return callback; - } - return this; - }, + function debugCallback(err) { + if (err) { + backtrace.message = err.message; + err = backtrace; + missingCallback(err); + } + } -// retain first n characters of the match -less:function (n) { - this.unput(this.match.slice(n)); - }, + function missingCallback(err) { + if (err) { + if (process.throwDeprecation) + throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs + else if (!process.noDeprecation) { + var msg = 'fs: missing callback ' + (err.stack || err.message); + if (process.traceDeprecation) + console.trace(msg); + else + console.error(msg); + } + } + } +} -// displays already matched input, i.e. for error messages -pastInput:function () { - var past = this.matched.substr(0, this.matched.length - this.match.length); - return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, ""); - }, +function maybeCallback(cb) { + return typeof cb === 'function' ? cb : rethrow(); +} -// displays upcoming input, i.e. for error messages -upcomingInput:function () { - var next = this.match; - if (next.length < 20) { - next += this._input.substr(0, 20-next.length); - } - return (next.substr(0,20) + (next.length > 20 ? '...' : '')).replace(/\n/g, ""); - }, +var normalize = pathModule.normalize; -// displays the character position where the lexing error occurred, i.e. for error messages -showPosition:function () { - var pre = this.pastInput(); - var c = new Array(pre.length + 1).join("-"); - return pre + this.upcomingInput() + "\n" + c + "^"; - }, +// Regexp that finds the next partion of a (partial) path +// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] +if (isWindows) { + var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; +} else { + var nextPartRe = /(.*?)(?:[\/]+|$)/g; +} -// test the lexed token: return FALSE when not a match, otherwise return token -test_match:function (match, indexed_rule) { - var token, - lines, - backup; +// Regex to find the device root, including trailing slash. E.g. 'c:\\'. +if (isWindows) { + var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; +} else { + var splitRootRe = /^[\/]*/; +} - if (this.options.backtrack_lexer) { - // save context - backup = { - yylineno: this.yylineno, - yylloc: { - first_line: this.yylloc.first_line, - last_line: this.last_line, - first_column: this.yylloc.first_column, - last_column: this.yylloc.last_column - }, - yytext: this.yytext, - match: this.match, - matches: this.matches, - matched: this.matched, - yyleng: this.yyleng, - offset: this.offset, - _more: this._more, - _input: this._input, - yy: this.yy, - conditionStack: this.conditionStack.slice(0), - done: this.done - }; - if (this.options.ranges) { - backup.yylloc.range = this.yylloc.range.slice(0); - } - } +exports.realpathSync = function realpathSync(p, cache) { + // make p is absolute + p = pathModule.resolve(p); - lines = match[0].match(/(?:\r\n?|\n).*/g); - if (lines) { - this.yylineno += lines.length; - } - this.yylloc = { - first_line: this.yylloc.last_line, - last_line: this.yylineno + 1, - first_column: this.yylloc.last_column, - last_column: lines ? - lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : - this.yylloc.last_column + match[0].length - }; - this.yytext += match[0]; - this.match += match[0]; - this.matches = match; - this.yyleng = this.yytext.length; - if (this.options.ranges) { - this.yylloc.range = [this.offset, this.offset += this.yyleng]; - } - this._more = false; - this._backtrack = false; - this._input = this._input.slice(match[0].length); - this.matched += match[0]; - token = this.performAction.call(this, this.yy, this, indexed_rule, this.conditionStack[this.conditionStack.length - 1]); - if (this.done && this._input) { - this.done = false; - } - if (token) { - return token; - } else if (this._backtrack) { - // recover context - for (var k in backup) { - this[k] = backup[k]; - } - return false; // rule action called reject() implying the next rule should be tested instead. - } - return false; - }, + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return cache[p]; + } -// return next match in input -next:function () { - if (this.done) { - return this.EOF; - } - if (!this._input) { - this.done = true; - } + var original = p, + seenLinks = {}, + knownHard = {}; - var token, - match, - tempMatch, - index; - if (!this._more) { - this.yytext = ''; - this.match = ''; - } - var rules = this._currentRules(); - for (var i = 0; i < rules.length; i++) { - tempMatch = this._input.match(this.rules[rules[i]]); - if (tempMatch && (!match || tempMatch[0].length > match[0].length)) { - match = tempMatch; - index = i; - if (this.options.backtrack_lexer) { - token = this.test_match(tempMatch, rules[i]); - if (token !== false) { - return token; - } else if (this._backtrack) { - match = false; - continue; // rule action called reject() implying a rule MISmatch. - } else { - // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace) - return false; - } - } else if (!this.options.flex) { - break; - } - } - } - if (match) { - token = this.test_match(match, rules[index]); - if (token !== false) { - return token; - } - // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace) - return false; - } - if (this._input === "") { - return this.EOF; - } else { - return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { - text: "", - token: null, - line: this.yylineno - }); - } - }, + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; -// return next match that has a token -lex:function lex() { - var r = this.next(); - if (r) { - return r; - } else { - return this.lex(); - } - }, + start(); -// activates a new lexer condition state (pushes the new lexer condition state onto the condition stack) -begin:function begin(condition) { - this.conditionStack.push(condition); - }, + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; -// pop the previously active lexer condition state off the condition stack -popState:function popState() { - var n = this.conditionStack.length - 1; - if (n > 0) { - return this.conditionStack.pop(); - } else { - return this.conditionStack[0]; - } - }, + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstatSync(base); + knownHard[base] = true; + } + } -// produce the lexer rule set which is active for the currently active lexer condition state -_currentRules:function _currentRules() { - if (this.conditionStack.length && this.conditionStack[this.conditionStack.length - 1]) { - return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules; - } else { - return this.conditions["INITIAL"].rules; + // walk down the path, swapping out linked pathparts for their real + // values + // NB: p.length changes. + while (pos < p.length) { + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; + + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + continue; + } + + var resolvedLink; + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // some known symbolic link. no need to stat again. + resolvedLink = cache[base]; + } else { + var stat = fs.lstatSync(base); + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + continue; + } + + // read the link if it wasn't read before + // dev/ino always return 0 on windows, so skip the check. + var linkTarget = null; + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + linkTarget = seenLinks[id]; } - }, + } + if (linkTarget === null) { + fs.statSync(base); + linkTarget = fs.readlinkSync(base); + } + resolvedLink = pathModule.resolve(previous, linkTarget); + // track this, if given a cache. + if (cache) cache[base] = resolvedLink; + if (!isWindows) seenLinks[id] = linkTarget; + } -// return the currently active lexer condition state; when an index argument is provided it produces the N-th previous condition state, if available -topState:function topState(n) { - n = this.conditionStack.length - 1 - Math.abs(n || 0); - if (n >= 0) { - return this.conditionStack[n]; - } else { - return "INITIAL"; + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } + + if (cache) cache[original] = p; + + return p; +}; + + +exports.realpath = function realpath(p, cache, cb) { + if (typeof cb !== 'function') { + cb = maybeCallback(cache); + cache = null; + } + + // make p is absolute + p = pathModule.resolve(p); + + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return process.nextTick(cb.bind(null, null, cache[p])); + } + + var original = p, + seenLinks = {}, + knownHard = {}; + + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; + + start(); + + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; + + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstat(base, function(err) { + if (err) return cb(err); + knownHard[base] = true; + LOOP(); + }); + } else { + process.nextTick(LOOP); + } + } + + // walk down the path, swapping out linked pathparts for their real + // values + function LOOP() { + // stop if scanned past end of path + if (pos >= p.length) { + if (cache) cache[original] = p; + return cb(null, p); + } + + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; + + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + return process.nextTick(LOOP); + } + + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // known symbolic link. no need to stat again. + return gotResolvedLink(cache[base]); + } + + return fs.lstat(base, gotStat); + } + + function gotStat(err, stat) { + if (err) return cb(err); + + // if not a symlink, skip to the next path part + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + return process.nextTick(LOOP); + } + + // stat & read the link if not read before + // call gotTarget as soon as the link target is known + // dev/ino always return 0 on windows, so skip the check. + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + return gotTarget(null, seenLinks[id], base); + } + } + fs.stat(base, function(err) { + if (err) return cb(err); + + fs.readlink(base, function(err, target) { + if (!isWindows) seenLinks[id] = target; + gotTarget(err, target); + }); + }); + } + + function gotTarget(err, target, base) { + if (err) return cb(err); + + var resolvedLink = pathModule.resolve(previous, target); + if (cache) cache[base] = resolvedLink; + gotResolvedLink(resolvedLink); + } + + function gotResolvedLink(resolvedLink) { + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } +}; + + +/***/ }), +/* 182 */ +/***/ (function(module, exports, __webpack_require__) { + +var concatMap = __webpack_require__(183); +var balanced = __webpack_require__(184); + +module.exports = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function identity(e) { + return e; +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; + + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } } - }, + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); + } -// alias for begin(condition) -pushState:function pushState(condition) { - this.begin(condition); - }, + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } -// return the number of states currently on the stack -stateStackSize:function stateStackSize() { - return this.conditionStack.length; - }, -options: {}, -performAction: function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) { -var YYSTATE=YY_START; -switch($avoiding_name_collisions) { -case 0:return 5 -break; -case 1:/* skip whitespace */ -break; -case 2:return 8 -break; + return expansions; +} + + + +/***/ }), +/* 183 */ +/***/ (function(module, exports) { + +module.exports = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray(x)) res.push.apply(res, x); + else res.push(x); + } + return res; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + + +/***/ }), +/* 184 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + + var r = range(a, b, str); + + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} + +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} + +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; + + if (ai >= 0 && bi > 0) { + begs = []; + left = str.length; + + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } + + bi = str.indexOf(b, i + 1); + } + + i = ai < bi && ai >= 0 ? ai : bi; + } + + if (begs.length) { + result = [ left, right ]; + } + } + + return result; +} + + +/***/ }), +/* 185 */ +/***/ (function(module, exports) { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + + +/***/ }), +/* 186 */ +/***/ (function(module, exports, __webpack_require__) { + +module.exports = globSync +globSync.GlobSync = GlobSync + +var fs = __webpack_require__(13) +var rp = __webpack_require__(117) +var minimatch = __webpack_require__(99) +var Minimatch = minimatch.Minimatch +var Glob = __webpack_require__(48).Glob +var util = __webpack_require__(14) +var path = __webpack_require__(5) +var assert = __webpack_require__(62) +var isAbsolute = __webpack_require__(100) +var common = __webpack_require__(119) +var alphasort = common.alphasort +var alphasorti = common.alphasorti +var setopts = common.setopts +var ownProp = common.ownProp +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored + +function globSync (pattern, options) { + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + return new GlobSync(pattern, options).found +} + +function GlobSync (pattern, options) { + if (!pattern) + throw new Error('must provide pattern') + + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + if (!(this instanceof GlobSync)) + return new GlobSync(pattern, options) + + setopts(this, pattern, options) + + if (this.noprocess) + return this + + var n = this.minimatch.set.length + this.matches = new Array(n) + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false) + } + this._finish() +} + +GlobSync.prototype._finish = function () { + assert(this instanceof GlobSync) + if (this.realpath) { + var self = this + this.matches.forEach(function (matchset, index) { + var set = self.matches[index] = Object.create(null) + for (var p in matchset) { + try { + p = self._makeAbs(p) + var real = rp.realpathSync(p, self.realpathCache) + set[real] = true + } catch (er) { + if (er.syscall === 'stat') + set[self._makeAbs(p)] = true + else + throw er + } + } + }) + } + common.finish(this) +} + + +GlobSync.prototype._process = function (pattern, index, inGlobStar) { + assert(this instanceof GlobSync) + + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ + } + // now n is the index of the first one that is *not* a string. + + // See if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index) + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break + } + + var remain = pattern.slice(n) + + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix + + var abs = this._makeAbs(read) + + //if ignored, skip processing + if (childrenIgnored(this, read)) + return + + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar) +} + + +GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { + var entries = this._readdir(abs, inGlobStar) + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' + + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } + } + + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix.slice(-1) !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) + } + // This was the last one, and no stats were needed + return + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) + newPattern = [prefix, e] + else + newPattern = [e] + this._process(newPattern.concat(remain), index, inGlobStar) + } +} + + +GlobSync.prototype._emitMatch = function (index, e) { + if (isIgnored(this, e)) + return + + var abs = this._makeAbs(e) + + if (this.mark) + e = this._mark(e) + + if (this.absolute) { + e = abs + } + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true + + if (this.stat) + this._stat(e) +} + + +GlobSync.prototype._readdirInGlobStar = function (abs) { + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false) + + var entries + var lstat + var stat + try { + lstat = fs.lstatSync(abs) + } catch (er) { + if (er.code === 'ENOENT') { + // lstat failed, doesn't exist + return null + } + } + + var isSym = lstat && lstat.isSymbolicLink() + this.symlinks[abs] = isSym + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) + this.cache[abs] = 'FILE' + else + entries = this._readdir(abs, false) + + return entries +} + +GlobSync.prototype._readdir = function (abs, inGlobStar) { + var entries + + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs) + + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return null + + if (Array.isArray(c)) + return c + } + + try { + return this._readdirEntries(abs, fs.readdirSync(abs)) + } catch (er) { + this._readdirError(abs, er) + return null + } +} + +GlobSync.prototype._readdirEntries = function (abs, entries) { + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } + } + + this.cache[abs] = entries + + // mark and cache dir-ness + return entries +} + +GlobSync.prototype._readdirError = function (f, er) { + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f) + this.cache[abs] = 'FILE' + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd) + error.path = this.cwd + error.code = er.code + throw error + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) + throw er + if (!this.silent) + console.error('glob error', er) + break + } +} + +GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { + + var entries = this._readdir(abs, inGlobStar) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false) + + var len = entries.length + var isSym = this.symlinks[abs] + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return + + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true) + + var below = gspref.concat(entries[i], remain) + this._process(below, index, true) + } +} + +GlobSync.prototype._processSimple = function (prefix, index) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var exists = this._stat(prefix) + + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') + + // Mark this as a match + this._emitMatch(index, prefix) +} + +// Returns either 'DIR', 'FILE', or false +GlobSync.prototype._stat = function (f) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' + + if (f.length > this.maxLength) + return false + + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] + + if (Array.isArray(c)) + c = 'DIR' + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return c + + if (needDir && c === 'FILE') + return false + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + + var exists + var stat = this.statCache[abs] + if (!stat) { + var lstat + try { + lstat = fs.lstatSync(abs) + } catch (er) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return false + } + } + + if (lstat && lstat.isSymbolicLink()) { + try { + stat = fs.statSync(abs) + } catch (er) { + stat = lstat + } + } else { + stat = lstat + } + } + + this.statCache[abs] = stat + + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' + + this.cache[abs] = this.cache[abs] || c + + if (needDir && c === 'FILE') + return false + + return c +} + +GlobSync.prototype._mark = function (p) { + return common.mark(this, p) +} + +GlobSync.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) +} + + +/***/ }), +/* 187 */ +/***/ (function(module, exports, __webpack_require__) { + +var wrappy = __webpack_require__(120) +var reqs = Object.create(null) +var once = __webpack_require__(71) + +module.exports = wrappy(inflight) + +function inflight (key, cb) { + if (reqs[key]) { + reqs[key].push(cb) + return null + } else { + reqs[key] = [cb] + return makeres(key) + } +} + +function makeres (key) { + return once(function RES () { + var cbs = reqs[key] + var len = cbs.length + var args = slice(arguments) + + // XXX It's somewhat ambiguous whether a new callback added in this + // pass should be queued for later execution if something in the + // list of callbacks throws, or if it should just be discarded. + // However, it's such an edge case that it hardly matters, and either + // choice is likely as surprising as the other. + // As it happens, we do go ahead and schedule it for later execution. + try { + for (var i = 0; i < len; i++) { + cbs[i].apply(null, args) + } + } finally { + if (cbs.length > len) { + // added more in the interim. + // de-zalgo, just in case, but don't call again. + cbs.splice(0, len) + process.nextTick(function () { + RES.apply(null, args) + }) + } else { + delete reqs[key] + } + } + }) +} + +function slice (args) { + var length = args.length + var array = [] + + for (var i = 0; i < length; i++) array[i] = args[i] + return array +} + + +/***/ }), +/* 188 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const path = __webpack_require__(5); +const loadJsonFile = __webpack_require__(189); +const pathType = __webpack_require__(122); + +module.exports = (fp, opts) => { + if (typeof fp !== 'string') { + opts = fp; + fp = '.'; + } + + opts = opts || {}; + + return pathType.dir(fp) + .then(isDir => { + if (isDir) { + fp = path.join(fp, 'package.json'); + } + + return loadJsonFile(fp); + }) + .then(x => { + if (opts.normalize !== false) { + __webpack_require__(123)(x); + } + + return x; + }); +}; + +module.exports.sync = (fp, opts) => { + if (typeof fp !== 'string') { + opts = fp; + fp = '.'; + } + + opts = opts || {}; + fp = pathType.dirSync(fp) ? path.join(fp, 'package.json') : fp; + + const x = loadJsonFile.sync(fp); + + if (opts.normalize !== false) { + __webpack_require__(123)(x); + } + + return x; +}; + + +/***/ }), +/* 189 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const path = __webpack_require__(5); +const fs = __webpack_require__(61); +const stripBom = __webpack_require__(190); +const parseJson = __webpack_require__(191); +const pify = __webpack_require__(195); + +const parse = (data, fp) => parseJson(stripBom(data), path.relative('.', fp)); + +module.exports = fp => pify(fs.readFile)(fp, 'utf8').then(data => parse(data, fp)); +module.exports.sync = fp => parse(fs.readFileSync(fp, 'utf8'), fp); + + +/***/ }), +/* 190 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = x => { + if (typeof x !== 'string') { + throw new TypeError('Expected a string, got ' + typeof x); + } + + // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string + // conversion translates it to FEFF (UTF-16 BOM) + if (x.charCodeAt(0) === 0xFEFF) { + return x.slice(1); + } + + return x; +}; + + +/***/ }), +/* 191 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const errorEx = __webpack_require__(192); +const fallback = __webpack_require__(194); + +const JSONError = errorEx('JSONError', { + fileName: errorEx.append('in %s') +}); + +module.exports = (input, reviver, filename) => { + if (typeof reviver === 'string') { + filename = reviver; + reviver = null; + } + + try { + try { + return JSON.parse(input, reviver); + } catch (err) { + fallback(input, reviver); + + throw err; + } + } catch (err) { + err.message = err.message.replace(/\n/g, ''); + + const jsonErr = new JSONError(err); + if (filename) { + jsonErr.fileName = filename; + } + + throw jsonErr; + } +}; + + +/***/ }), +/* 192 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var util = __webpack_require__(14); +var isArrayish = __webpack_require__(193); + +var errorEx = function errorEx(name, properties) { + if (!name || name.constructor !== String) { + properties = name || {}; + name = Error.name; + } + + var errorExError = function ErrorEXError(message) { + if (!this) { + return new ErrorEXError(message); + } + + message = message instanceof Error + ? message.message + : (message || this.message); + + Error.call(this, message); + Error.captureStackTrace(this, errorExError); + + this.name = name; + + Object.defineProperty(this, 'message', { + configurable: true, + enumerable: false, + get: function () { + var newMessage = message.split(/\r?\n/g); + + for (var key in properties) { + if (!properties.hasOwnProperty(key)) { + continue; + } + + var modifier = properties[key]; + + if ('message' in modifier) { + newMessage = modifier.message(this[key], newMessage) || newMessage; + if (!isArrayish(newMessage)) { + newMessage = [newMessage]; + } + } + } + + return newMessage.join('\n'); + }, + set: function (v) { + message = v; + } + }); + + var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack'); + var stackGetter = stackDescriptor.get; + var stackValue = stackDescriptor.value; + delete stackDescriptor.value; + delete stackDescriptor.writable; + + stackDescriptor.get = function () { + var stack = (stackGetter) + ? stackGetter.call(this).split(/\r?\n+/g) + : stackValue.split(/\r?\n+/g); + + // starting in Node 7, the stack builder caches the message. + // just replace it. + stack[0] = this.name + ': ' + this.message; + + var lineCount = 1; + for (var key in properties) { + if (!properties.hasOwnProperty(key)) { + continue; + } + + var modifier = properties[key]; + + if ('line' in modifier) { + var line = modifier.line(this[key]); + if (line) { + stack.splice(lineCount++, 0, ' ' + line); + } + } + + if ('stack' in modifier) { + modifier.stack(this[key], stack); + } + } + + return stack.join('\n'); + }; + + Object.defineProperty(this, 'stack', stackDescriptor); + }; + + if (Object.setPrototypeOf) { + Object.setPrototypeOf(errorExError.prototype, Error.prototype); + Object.setPrototypeOf(errorExError, Error); + } else { + util.inherits(errorExError, Error); + } + + return errorExError; +}; + +errorEx.append = function (str, def) { + return { + message: function (v, message) { + v = v || def; + + if (v) { + message[0] += ' ' + str.replace('%s', v.toString()); + } + + return message; + } + }; +}; + +errorEx.line = function (str, def) { + return { + line: function (v) { + v = v || def; + + if (v) { + return str.replace('%s', v.toString()); + } + + return null; + } + }; +}; + +module.exports = errorEx; + + +/***/ }), +/* 193 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = function isArrayish(obj) { + if (!obj) { + return false; + } + + return obj instanceof Array || Array.isArray(obj) || + (obj.length >= 0 && obj.splice instanceof Function); +}; + + +/***/ }), +/* 194 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = parseJson +function parseJson (txt, reviver, context) { + context = context || 20 + try { + return JSON.parse(txt, reviver) + } catch (e) { + const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i) + const errIdx = syntaxErr + ? +syntaxErr[1] + : e.message.match(/^Unexpected end of JSON.*/i) + ? txt.length - 1 + : null + if (errIdx != null) { + const start = errIdx <= context + ? 0 + : errIdx - context + const end = errIdx + context >= txt.length + ? txt.length + : errIdx + context + e.message += ` while parsing near '${ + start === 0 ? '' : '...' + }${txt.slice(start, end)}${ + end === txt.length ? '' : '...' + }'` + } else { + e.message += ` while parsing '${txt.slice(0, context * 2)}'` + } + throw e + } +} + + +/***/ }), +/* 195 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const processFn = (fn, opts) => function () { + const P = opts.promiseModule; + const args = new Array(arguments.length); + + for (let i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + + return new P((resolve, reject) => { + if (opts.errorFirst) { + args.push(function (err, result) { + if (opts.multiArgs) { + const results = new Array(arguments.length - 1); + + for (let i = 1; i < arguments.length; i++) { + results[i - 1] = arguments[i]; + } + + if (err) { + results.unshift(err); + reject(results); + } else { + resolve(results); + } + } else if (err) { + reject(err); + } else { + resolve(result); + } + }); + } else { + args.push(function (result) { + if (opts.multiArgs) { + const results = new Array(arguments.length - 1); + + for (let i = 0; i < arguments.length; i++) { + results[i] = arguments[i]; + } + + resolve(results); + } else { + resolve(result); + } + }); + } + + fn.apply(this, args); + }); +}; + +module.exports = (obj, opts) => { + opts = Object.assign({ + exclude: [/.+(Sync|Stream)$/], + errorFirst: true, + promiseModule: Promise + }, opts); + + const filter = key => { + const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key); + return opts.include ? opts.include.some(match) : !opts.exclude.some(match); + }; + + let ret; + if (typeof obj === 'function') { + ret = function () { + if (opts.excludeMain) { + return obj.apply(this, arguments); + } + + return processFn(obj, opts).apply(this, arguments); + }; + } else { + ret = Object.create(Object.getPrototypeOf(obj)); + } + + for (const key in obj) { // eslint-disable-line guard-for-in + const x = obj[key]; + ret[key] = typeof x === 'function' && filter(key) ? processFn(x, opts) : x; + } + + return ret; +}; + + +/***/ }), +/* 196 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const processFn = (fn, opts) => function () { + const P = opts.promiseModule; + const args = new Array(arguments.length); + + for (let i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + + return new P((resolve, reject) => { + if (opts.errorFirst) { + args.push(function (err, result) { + if (opts.multiArgs) { + const results = new Array(arguments.length - 1); + + for (let i = 1; i < arguments.length; i++) { + results[i - 1] = arguments[i]; + } + + if (err) { + results.unshift(err); + reject(results); + } else { + resolve(results); + } + } else if (err) { + reject(err); + } else { + resolve(result); + } + }); + } else { + args.push(function (result) { + if (opts.multiArgs) { + const results = new Array(arguments.length - 1); + + for (let i = 0; i < arguments.length; i++) { + results[i] = arguments[i]; + } + + resolve(results); + } else { + resolve(result); + } + }); + } + + fn.apply(this, args); + }); +}; + +module.exports = (obj, opts) => { + opts = Object.assign({ + exclude: [/.+(Sync|Stream)$/], + errorFirst: true, + promiseModule: Promise + }, opts); + + const filter = key => { + const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key); + return opts.include ? opts.include.some(match) : !opts.exclude.some(match); + }; + + let ret; + if (typeof obj === 'function') { + ret = function () { + if (opts.excludeMain) { + return obj.apply(this, arguments); + } + + return processFn(obj, opts).apply(this, arguments); + }; + } else { + ret = Object.create(Object.getPrototypeOf(obj)); + } + + for (const key in obj) { // eslint-disable-line guard-for-in + const x = obj[key]; + ret[key] = typeof x === 'function' && filter(key) ? processFn(x, opts) : x; + } + + return ret; +}; + + +/***/ }), +/* 197 */ +/***/ (function(module, exports, __webpack_require__) { + +var semver = __webpack_require__(198) +var validateLicense = __webpack_require__(199); +var hostedGitInfo = __webpack_require__(204) +var isBuiltinModule = __webpack_require__(206) +var depTypes = ["dependencies","devDependencies","optionalDependencies"] +var extractDescription = __webpack_require__(208) +var url = __webpack_require__(102) +var typos = __webpack_require__(209) + +var fixer = module.exports = { + // default warning function + warn: function() {}, + + fixRepositoryField: function(data) { + if (data.repositories) { + this.warn("repositories"); + data.repository = data.repositories[0] + } + if (!data.repository) return this.warn("missingRepository") + if (typeof data.repository === "string") { + data.repository = { + type: "git", + url: data.repository + } + } + var r = data.repository.url || "" + if (r) { + var hosted = hostedGitInfo.fromUrl(r) + if (hosted) { + r = data.repository.url + = hosted.getDefaultRepresentation() == "shortcut" ? hosted.https() : hosted.toString() + } + } + + if (r.match(/github.com\/[^\/]+\/[^\/]+\.git\.git$/)) { + this.warn("brokenGitUrl", r) + } + } + +, fixTypos: function(data) { + Object.keys(typos.topLevel).forEach(function (d) { + if (data.hasOwnProperty(d)) { + this.warn("typo", d, typos.topLevel[d]) + } + }, this) + } + +, fixScriptsField: function(data) { + if (!data.scripts) return + if (typeof data.scripts !== "object") { + this.warn("nonObjectScripts") + delete data.scripts + return + } + Object.keys(data.scripts).forEach(function (k) { + if (typeof data.scripts[k] !== "string") { + this.warn("nonStringScript") + delete data.scripts[k] + } else if (typos.script[k] && !data.scripts[typos.script[k]]) { + this.warn("typo", k, typos.script[k], "scripts") + } + }, this) + } + +, fixFilesField: function(data) { + var files = data.files + if (files && !Array.isArray(files)) { + this.warn("nonArrayFiles") + delete data.files + } else if (data.files) { + data.files = data.files.filter(function(file) { + if (!file || typeof file !== "string") { + this.warn("invalidFilename", file) + return false + } else { + return true + } + }, this) + } + } + +, fixBinField: function(data) { + if (!data.bin) return; + if (typeof data.bin === "string") { + var b = {} + var match + if (match = data.name.match(/^@[^/]+[/](.*)$/)) { + b[match[1]] = data.bin + } else { + b[data.name] = data.bin + } + data.bin = b + } + } + +, fixManField: function(data) { + if (!data.man) return; + if (typeof data.man === "string") { + data.man = [ data.man ] + } + } +, fixBundleDependenciesField: function(data) { + var bdd = "bundledDependencies" + var bd = "bundleDependencies" + if (data[bdd] && !data[bd]) { + data[bd] = data[bdd] + delete data[bdd] + } + if (data[bd] && !Array.isArray(data[bd])) { + this.warn("nonArrayBundleDependencies") + delete data[bd] + } else if (data[bd]) { + data[bd] = data[bd].filter(function(bd) { + if (!bd || typeof bd !== 'string') { + this.warn("nonStringBundleDependency", bd) + return false + } else { + if (!data.dependencies) { + data.dependencies = {} + } + if (!data.dependencies.hasOwnProperty(bd)) { + this.warn("nonDependencyBundleDependency", bd) + data.dependencies[bd] = "*" + } + return true + } + }, this) + } + } + +, fixDependencies: function(data, strict) { + var loose = !strict + objectifyDeps(data, this.warn) + addOptionalDepsToDeps(data, this.warn) + this.fixBundleDependenciesField(data) + + ;['dependencies','devDependencies'].forEach(function(deps) { + if (!(deps in data)) return + if (!data[deps] || typeof data[deps] !== "object") { + this.warn("nonObjectDependencies", deps) + delete data[deps] + return + } + Object.keys(data[deps]).forEach(function (d) { + var r = data[deps][d] + if (typeof r !== 'string') { + this.warn("nonStringDependency", d, JSON.stringify(r)) + delete data[deps][d] + } + var hosted = hostedGitInfo.fromUrl(data[deps][d]) + if (hosted) data[deps][d] = hosted.toString() + }, this) + }, this) + } + +, fixModulesField: function (data) { + if (data.modules) { + this.warn("deprecatedModules") + delete data.modules + } + } + +, fixKeywordsField: function (data) { + if (typeof data.keywords === "string") { + data.keywords = data.keywords.split(/,\s+/) + } + if (data.keywords && !Array.isArray(data.keywords)) { + delete data.keywords + this.warn("nonArrayKeywords") + } else if (data.keywords) { + data.keywords = data.keywords.filter(function(kw) { + if (typeof kw !== "string" || !kw) { + this.warn("nonStringKeyword"); + return false + } else { + return true + } + }, this) + } + } + +, fixVersionField: function(data, strict) { + // allow "loose" semver 1.0 versions in non-strict mode + // enforce strict semver 2.0 compliance in strict mode + var loose = !strict + if (!data.version) { + data.version = "" + return true + } + if (!semver.valid(data.version, loose)) { + throw new Error('Invalid version: "'+ data.version + '"') + } + data.version = semver.clean(data.version, loose) + return true + } + +, fixPeople: function(data) { + modifyPeople(data, unParsePerson) + modifyPeople(data, parsePerson) + } + +, fixNameField: function(data, options) { + if (typeof options === "boolean") options = {strict: options} + else if (typeof options === "undefined") options = {} + var strict = options.strict + if (!data.name && !strict) { + data.name = "" + return + } + if (typeof data.name !== "string") { + throw new Error("name field must be a string.") + } + if (!strict) + data.name = data.name.trim() + ensureValidName(data.name, strict, options.allowLegacyCase) + if (isBuiltinModule(data.name)) + this.warn("conflictingName", data.name) + } + + +, fixDescriptionField: function (data) { + if (data.description && typeof data.description !== 'string') { + this.warn("nonStringDescription") + delete data.description + } + if (data.readme && !data.description) + data.description = extractDescription(data.readme) + if(data.description === undefined) delete data.description; + if (!data.description) this.warn("missingDescription") + } + +, fixReadmeField: function (data) { + if (!data.readme) { + this.warn("missingReadme") + data.readme = "ERROR: No README data found!" + } + } + +, fixBugsField: function(data) { + if (!data.bugs && data.repository && data.repository.url) { + var hosted = hostedGitInfo.fromUrl(data.repository.url) + if(hosted && hosted.bugs()) { + data.bugs = {url: hosted.bugs()} + } + } + else if(data.bugs) { + var emailRe = /^.+@.*\..+$/ + if(typeof data.bugs == "string") { + if(emailRe.test(data.bugs)) + data.bugs = {email:data.bugs} + else if(url.parse(data.bugs).protocol) + data.bugs = {url: data.bugs} + else + this.warn("nonEmailUrlBugsString") + } + else { + bugsTypos(data.bugs, this.warn) + var oldBugs = data.bugs + data.bugs = {} + if(oldBugs.url) { + if(typeof(oldBugs.url) == "string" && url.parse(oldBugs.url).protocol) + data.bugs.url = oldBugs.url + else + this.warn("nonUrlBugsUrlField") + } + if(oldBugs.email) { + if(typeof(oldBugs.email) == "string" && emailRe.test(oldBugs.email)) + data.bugs.email = oldBugs.email + else + this.warn("nonEmailBugsEmailField") + } + } + if(!data.bugs.email && !data.bugs.url) { + delete data.bugs + this.warn("emptyNormalizedBugs") + } + } + } + +, fixHomepageField: function(data) { + if (!data.homepage && data.repository && data.repository.url) { + var hosted = hostedGitInfo.fromUrl(data.repository.url) + if (hosted && hosted.docs()) data.homepage = hosted.docs() + } + if (!data.homepage) return + + if(typeof data.homepage !== "string") { + this.warn("nonUrlHomepage") + return delete data.homepage + } + if(!url.parse(data.homepage).protocol) { + data.homepage = "http://" + data.homepage + } + } + +, fixLicenseField: function(data) { + if (!data.license) { + return this.warn("missingLicense") + } else{ + if ( + typeof(data.license) !== 'string' || + data.license.length < 1 + ) { + this.warn("invalidLicense") + } else { + if (!validateLicense(data.license).validForNewPackages) + this.warn("invalidLicense") + } + } + } +} + +function isValidScopedPackageName(spec) { + if (spec.charAt(0) !== '@') return false + + var rest = spec.slice(1).split('/') + if (rest.length !== 2) return false + + return rest[0] && rest[1] && + rest[0] === encodeURIComponent(rest[0]) && + rest[1] === encodeURIComponent(rest[1]) +} + +function isCorrectlyEncodedName(spec) { + return !spec.match(/[\/@\s\+%:]/) && + spec === encodeURIComponent(spec) +} + +function ensureValidName (name, strict, allowLegacyCase) { + if (name.charAt(0) === "." || + !(isValidScopedPackageName(name) || isCorrectlyEncodedName(name)) || + (strict && (!allowLegacyCase) && name !== name.toLowerCase()) || + name.toLowerCase() === "node_modules" || + name.toLowerCase() === "favicon.ico") { + throw new Error("Invalid name: " + JSON.stringify(name)) + } +} + +function modifyPeople (data, fn) { + if (data.author) data.author = fn(data.author) + ;["maintainers", "contributors"].forEach(function (set) { + if (!Array.isArray(data[set])) return; + data[set] = data[set].map(fn) + }) + return data +} + +function unParsePerson (person) { + if (typeof person === "string") return person + var name = person.name || "" + var u = person.url || person.web + var url = u ? (" ("+u+")") : "" + var e = person.email || person.mail + var email = e ? (" <"+e+">") : "" + return name+email+url +} + +function parsePerson (person) { + if (typeof person !== "string") return person + var name = person.match(/^([^\(<]+)/) + var url = person.match(/\(([^\)]+)\)/) + var email = person.match(/<([^>]+)>/) + var obj = {} + if (name && name[0].trim()) obj.name = name[0].trim() + if (email) obj.email = email[1]; + if (url) obj.url = url[1]; + return obj +} + +function addOptionalDepsToDeps (data, warn) { + var o = data.optionalDependencies + if (!o) return; + var d = data.dependencies || {} + Object.keys(o).forEach(function (k) { + d[k] = o[k] + }) + data.dependencies = d +} + +function depObjectify (deps, type, warn) { + if (!deps) return {} + if (typeof deps === "string") { + deps = deps.trim().split(/[\n\r\s\t ,]+/) + } + if (!Array.isArray(deps)) return deps + warn("deprecatedArrayDependencies", type) + var o = {} + deps.filter(function (d) { + return typeof d === "string" + }).forEach(function(d) { + d = d.trim().split(/(:?[@\s><=])/) + var dn = d.shift() + var dv = d.join("") + dv = dv.trim() + dv = dv.replace(/^@/, "") + o[dn] = dv + }) + return o +} + +function objectifyDeps (data, warn) { + depTypes.forEach(function (type) { + if (!data[type]) return; + data[type] = depObjectify(data[type], type, warn) + }) +} + +function bugsTypos(bugs, warn) { + if (!bugs) return + Object.keys(bugs).forEach(function (k) { + if (typos.bugs[k]) { + warn("typo", k, typos.bugs[k], "bugs") + bugs[typos.bugs[k]] = bugs[k] + delete bugs[k] + } + }) +} + + +/***/ }), +/* 198 */ +/***/ (function(module, exports) { + +exports = module.exports = SemVer; + +// The debug function is excluded entirely from the minified version. +/* nomin */ var debug; +/* nomin */ if (typeof process === 'object' && + /* nomin */ process.env && + /* nomin */ process.env.NODE_DEBUG && + /* nomin */ /\bsemver\b/i.test(process.env.NODE_DEBUG)) + /* nomin */ debug = function() { + /* nomin */ var args = Array.prototype.slice.call(arguments, 0); + /* nomin */ args.unshift('SEMVER'); + /* nomin */ console.log.apply(console, args); + /* nomin */ }; +/* nomin */ else + /* nomin */ debug = function() {}; + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0'; + +var MAX_LENGTH = 256; +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; + +// The actual regexps go on exports.re +var re = exports.re = []; +var src = exports.src = []; +var R = 0; + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +var NUMERICIDENTIFIER = R++; +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; +var NUMERICIDENTIFIERLOOSE = R++; +src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; + + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +var NONNUMERICIDENTIFIER = R++; +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; + + +// ## Main Version +// Three dot-separated numeric identifiers. + +var MAINVERSION = R++; +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')'; + +var MAINVERSIONLOOSE = R++; +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +var PRERELEASEIDENTIFIER = R++; +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + + '|' + src[NONNUMERICIDENTIFIER] + ')'; + +var PRERELEASEIDENTIFIERLOOSE = R++; +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + + '|' + src[NONNUMERICIDENTIFIER] + ')'; + + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +var PRERELEASE = R++; +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; + +var PRERELEASELOOSE = R++; +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +var BUILDIDENTIFIER = R++; +src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +var BUILD = R++; +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; + + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +var FULL = R++; +var FULLPLAIN = 'v?' + src[MAINVERSION] + + src[PRERELEASE] + '?' + + src[BUILD] + '?'; + +src[FULL] = '^' + FULLPLAIN + '$'; + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + + src[PRERELEASELOOSE] + '?' + + src[BUILD] + '?'; + +var LOOSE = R++; +src[LOOSE] = '^' + LOOSEPLAIN + '$'; + +var GTLT = R++; +src[GTLT] = '((?:<|>)?=?)'; + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +var XRANGEIDENTIFIERLOOSE = R++; +src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; +var XRANGEIDENTIFIER = R++; +src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; + +var XRANGEPLAIN = R++; +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:' + src[PRERELEASE] + ')?' + + src[BUILD] + '?' + + ')?)?'; + +var XRANGEPLAINLOOSE = R++; +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[PRERELEASELOOSE] + ')?' + + src[BUILD] + '?' + + ')?)?'; + +var XRANGE = R++; +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; +var XRANGELOOSE = R++; +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +var LONETILDE = R++; +src[LONETILDE] = '(?:~>?)'; + +var TILDETRIM = R++; +src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; +re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); +var tildeTrimReplace = '$1~'; + +var TILDE = R++; +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; +var TILDELOOSE = R++; +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +var LONECARET = R++; +src[LONECARET] = '(?:\\^)'; + +var CARETTRIM = R++; +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); +var caretTrimReplace = '$1^'; + +var CARET = R++; +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; +var CARETLOOSE = R++; +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +var COMPARATORLOOSE = R++; +src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; +var COMPARATOR = R++; +src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; + + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +var COMPARATORTRIM = R++; +src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; + +// this one has to use the /g flag +re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); +var comparatorTrimReplace = '$1$2$3'; + + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +var HYPHENRANGE = R++; +src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAIN] + ')' + + '\\s*$'; + +var HYPHENRANGELOOSE = R++; +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s*$'; + +// Star ranges basically just allow anything at all. +var STAR = R++; +src[STAR] = '(<|>)?=?\\s*\\*'; + +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]); + if (!re[i]) + re[i] = new RegExp(src[i]); +} + +exports.parse = parse; +function parse(version, loose) { + if (version instanceof SemVer) + return version; + + if (typeof version !== 'string') + return null; + + if (version.length > MAX_LENGTH) + return null; + + var r = loose ? re[LOOSE] : re[FULL]; + if (!r.test(version)) + return null; + + try { + return new SemVer(version, loose); + } catch (er) { + return null; + } +} + +exports.valid = valid; +function valid(version, loose) { + var v = parse(version, loose); + return v ? v.version : null; +} + + +exports.clean = clean; +function clean(version, loose) { + var s = parse(version.trim().replace(/^[=v]+/, ''), loose); + return s ? s.version : null; +} + +exports.SemVer = SemVer; + +function SemVer(version, loose) { + if (version instanceof SemVer) { + if (version.loose === loose) + return version; + else + version = version.version; + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version); + } + + if (version.length > MAX_LENGTH) + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + + if (!(this instanceof SemVer)) + return new SemVer(version, loose); + + debug('SemVer', version, loose); + this.loose = loose; + var m = version.trim().match(loose ? re[LOOSE] : re[FULL]); + + if (!m) + throw new TypeError('Invalid Version: ' + version); + + this.raw = version; + + // these are actually numbers + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) + throw new TypeError('Invalid major version') + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) + throw new TypeError('Invalid minor version') + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) + throw new TypeError('Invalid patch version') + + // numberify any prerelease numeric ids + if (!m[4]) + this.prerelease = []; + else + this.prerelease = m[4].split('.').map(function(id) { + if (/^[0-9]+$/.test(id)) { + var num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) + return num; + } + return id; + }); + + this.build = m[5] ? m[5].split('.') : []; + this.format(); +} + +SemVer.prototype.format = function() { + this.version = this.major + '.' + this.minor + '.' + this.patch; + if (this.prerelease.length) + this.version += '-' + this.prerelease.join('.'); + return this.version; +}; + +SemVer.prototype.toString = function() { + return this.version; +}; + +SemVer.prototype.compare = function(other) { + debug('SemVer.compare', this.version, this.loose, other); + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + return this.compareMain(other) || this.comparePre(other); +}; + +SemVer.prototype.compareMain = function(other) { + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch); +}; + +SemVer.prototype.comparePre = function(other) { + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) + return -1; + else if (!this.prerelease.length && other.prerelease.length) + return 1; + else if (!this.prerelease.length && !other.prerelease.length) + return 0; + + var i = 0; + do { + var a = this.prerelease[i]; + var b = other.prerelease[i]; + debug('prerelease compare', i, a, b); + if (a === undefined && b === undefined) + return 0; + else if (b === undefined) + return 1; + else if (a === undefined) + return -1; + else if (a === b) + continue; + else + return compareIdentifiers(a, b); + } while (++i); +}; + +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function(release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break; + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break; + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) + this.major++; + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) + this.minor++; + this.patch = 0; + this.prerelease = []; + break; + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) + this.patch++; + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) + this.prerelease = [0]; + else { + var i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + if (i === -1) // didn't increment anything + this.prerelease.push(0); + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) + this.prerelease = [identifier, 0]; + } else + this.prerelease = [identifier, 0]; + } + break; + + default: + throw new Error('invalid increment argument: ' + release); + } + this.format(); + this.raw = this.version; + return this; +}; + +exports.inc = inc; +function inc(version, release, loose, identifier) { + if (typeof(loose) === 'string') { + identifier = loose; + loose = undefined; + } + + try { + return new SemVer(version, loose).inc(release, identifier).version; + } catch (er) { + return null; + } +} + +exports.diff = diff; +function diff(version1, version2) { + if (eq(version1, version2)) { + return null; + } else { + var v1 = parse(version1); + var v2 = parse(version2); + if (v1.prerelease.length || v2.prerelease.length) { + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return 'pre'+key; + } + } + } + return 'prerelease'; + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return key; + } + } + } + } +} + +exports.compareIdentifiers = compareIdentifiers; + +var numeric = /^[0-9]+$/; +function compareIdentifiers(a, b) { + var anum = numeric.test(a); + var bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return (anum && !bnum) ? -1 : + (bnum && !anum) ? 1 : + a < b ? -1 : + a > b ? 1 : + 0; +} + +exports.rcompareIdentifiers = rcompareIdentifiers; +function rcompareIdentifiers(a, b) { + return compareIdentifiers(b, a); +} + +exports.major = major; +function major(a, loose) { + return new SemVer(a, loose).major; +} + +exports.minor = minor; +function minor(a, loose) { + return new SemVer(a, loose).minor; +} + +exports.patch = patch; +function patch(a, loose) { + return new SemVer(a, loose).patch; +} + +exports.compare = compare; +function compare(a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)); +} + +exports.compareLoose = compareLoose; +function compareLoose(a, b) { + return compare(a, b, true); +} + +exports.rcompare = rcompare; +function rcompare(a, b, loose) { + return compare(b, a, loose); +} + +exports.sort = sort; +function sort(list, loose) { + return list.sort(function(a, b) { + return exports.compare(a, b, loose); + }); +} + +exports.rsort = rsort; +function rsort(list, loose) { + return list.sort(function(a, b) { + return exports.rcompare(a, b, loose); + }); +} + +exports.gt = gt; +function gt(a, b, loose) { + return compare(a, b, loose) > 0; +} + +exports.lt = lt; +function lt(a, b, loose) { + return compare(a, b, loose) < 0; +} + +exports.eq = eq; +function eq(a, b, loose) { + return compare(a, b, loose) === 0; +} + +exports.neq = neq; +function neq(a, b, loose) { + return compare(a, b, loose) !== 0; +} + +exports.gte = gte; +function gte(a, b, loose) { + return compare(a, b, loose) >= 0; +} + +exports.lte = lte; +function lte(a, b, loose) { + return compare(a, b, loose) <= 0; +} + +exports.cmp = cmp; +function cmp(a, op, b, loose) { + var ret; + switch (op) { + case '===': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + ret = a === b; + break; + case '!==': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + ret = a !== b; + break; + case '': case '=': case '==': ret = eq(a, b, loose); break; + case '!=': ret = neq(a, b, loose); break; + case '>': ret = gt(a, b, loose); break; + case '>=': ret = gte(a, b, loose); break; + case '<': ret = lt(a, b, loose); break; + case '<=': ret = lte(a, b, loose); break; + default: throw new TypeError('Invalid operator: ' + op); + } + return ret; +} + +exports.Comparator = Comparator; +function Comparator(comp, loose) { + if (comp instanceof Comparator) { + if (comp.loose === loose) + return comp; + else + comp = comp.value; + } + + if (!(this instanceof Comparator)) + return new Comparator(comp, loose); + + debug('comparator', comp, loose); + this.loose = loose; + this.parse(comp); + + if (this.semver === ANY) + this.value = ''; + else + this.value = this.operator + this.semver.version; + + debug('comp', this); +} + +var ANY = {}; +Comparator.prototype.parse = function(comp) { + var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var m = comp.match(r); + + if (!m) + throw new TypeError('Invalid comparator: ' + comp); + + this.operator = m[1]; + if (this.operator === '=') + this.operator = ''; + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) + this.semver = ANY; + else + this.semver = new SemVer(m[2], this.loose); +}; + +Comparator.prototype.toString = function() { + return this.value; +}; + +Comparator.prototype.test = function(version) { + debug('Comparator.test', version, this.loose); + + if (this.semver === ANY) + return true; + + if (typeof version === 'string') + version = new SemVer(version, this.loose); + + return cmp(version, this.operator, this.semver, this.loose); +}; + +Comparator.prototype.intersects = function(comp, loose) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required'); + } + + var rangeTmp; + + if (this.operator === '') { + rangeTmp = new Range(comp.value, loose); + return satisfies(this.value, rangeTmp, loose); + } else if (comp.operator === '') { + rangeTmp = new Range(this.value, loose); + return satisfies(comp.semver, rangeTmp, loose); + } + + var sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>'); + var sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<'); + var sameSemVer = this.semver.version === comp.semver.version; + var differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<='); + var oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, loose) && + ((this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<')); + var oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, loose) && + ((this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>')); + + return sameDirectionIncreasing || sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || oppositeDirectionsGreaterThan; +}; + + +exports.Range = Range; +function Range(range, loose) { + if (range instanceof Range) { + if (range.loose === loose) { + return range; + } else { + return new Range(range.raw, loose); + } + } + + if (range instanceof Comparator) { + return new Range(range.value, loose); + } + + if (!(this instanceof Range)) + return new Range(range, loose); + + this.loose = loose; + + // First, split based on boolean or || + this.raw = range; + this.set = range.split(/\s*\|\|\s*/).map(function(range) { + return this.parseRange(range.trim()); + }, this).filter(function(c) { + // throw out any that are not relevant for whatever reason + return c.length; + }); + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range); + } + + this.format(); +} + +Range.prototype.format = function() { + this.range = this.set.map(function(comps) { + return comps.join(' ').trim(); + }).join('||').trim(); + return this.range; +}; + +Range.prototype.toString = function() { + return this.range; +}; + +Range.prototype.parseRange = function(range) { + var loose = this.loose; + range = range.trim(); + debug('range', range, loose); + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; + range = range.replace(hr, hyphenReplace); + debug('hyphen replace', range); + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); + debug('comparator trim', range, re[COMPARATORTRIM]); + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[TILDETRIM], tildeTrimReplace); + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[CARETTRIM], caretTrimReplace); + + // normalize spaces + range = range.split(/\s+/).join(' '); + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var set = range.split(' ').map(function(comp) { + return parseComparator(comp, loose); + }).join(' ').split(/\s+/); + if (this.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function(comp) { + return !!comp.match(compRe); + }); + } + set = set.map(function(comp) { + return new Comparator(comp, loose); + }); + + return set; +}; + +Range.prototype.intersects = function(range, loose) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required'); + } + + return this.set.some(function(thisComparators) { + return thisComparators.every(function(thisComparator) { + return range.set.some(function(rangeComparators) { + return rangeComparators.every(function(rangeComparator) { + return thisComparator.intersects(rangeComparator, loose); + }); + }); + }); + }); +}; + +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators; +function toComparators(range, loose) { + return new Range(range, loose).set.map(function(comp) { + return comp.map(function(c) { + return c.value; + }).join(' ').trim().split(' '); + }); +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator(comp, loose) { + debug('comp', comp); + comp = replaceCarets(comp, loose); + debug('caret', comp); + comp = replaceTildes(comp, loose); + debug('tildes', comp); + comp = replaceXRanges(comp, loose); + debug('xrange', comp); + comp = replaceStars(comp, loose); + debug('stars', comp); + return comp; +} + +function isX(id) { + return !id || id.toLowerCase() === 'x' || id === '*'; +} + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes(comp, loose) { + return comp.trim().split(/\s+/).map(function(comp) { + return replaceTilde(comp, loose); + }).join(' '); +} + +function replaceTilde(comp, loose) { + var r = loose ? re[TILDELOOSE] : re[TILDE]; + return comp.replace(r, function(_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) + ret = ''; + else if (isX(m)) + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + else if (isX(p)) + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + else if (pr) { + debug('replaceTilde pr', pr); + if (pr.charAt(0) !== '-') + pr = '-' + pr; + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; + + debug('tilde return', ret); + return ret; + }); +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets(comp, loose) { + return comp.trim().split(/\s+/).map(function(comp) { + return replaceCaret(comp, loose); + }).join(' '); +} + +function replaceCaret(comp, loose) { + debug('caret', comp, loose); + var r = loose ? re[CARETLOOSE] : re[CARET]; + return comp.replace(r, function(_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) + ret = ''; + else if (isX(m)) + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + else if (isX(p)) { + if (M === '0') + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + else + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; + } else if (pr) { + debug('replaceCaret pr', pr); + if (pr.charAt(0) !== '-') + pr = '-' + pr; + if (M === '0') { + if (m === '0') + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + m + '.' + (+p + 1); + else + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + (+M + 1) + '.0.0'; + } else { + debug('no pr'); + if (M === '0') { + if (m === '0') + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1); + else + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0'; + } + + debug('caret return', ret); + return ret; + }); +} + +function replaceXRanges(comp, loose) { + debug('replaceXRanges', comp, loose); + return comp.split(/\s+/).map(function(comp) { + return replaceXRange(comp, loose); + }).join(' '); +} + +function replaceXRange(comp, loose) { + comp = comp.trim(); + var r = loose ? re[XRANGELOOSE] : re[XRANGE]; + return comp.replace(r, function(ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr); + var xM = isX(M); + var xm = xM || isX(m); + var xp = xm || isX(p); + var anyX = xp; + + if (gtlt === '=' && anyX) + gtlt = ''; + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // replace X with 0 + if (xm) + m = 0; + if (xp) + p = 0; + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>='; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else if (xp) { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<'; + if (xm) + M = +M + 1; + else + m = +m + 1; + } + + ret = gtlt + M + '.' + m + '.' + p; + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + } + + debug('xRange return', ret); + + return ret; + }); +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars(comp, loose) { + debug('replaceStars', comp, loose); + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[STAR], ''); +} + +// This function is passed to string.replace(re[HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + + if (isX(fM)) + from = ''; + else if (isX(fm)) + from = '>=' + fM + '.0.0'; + else if (isX(fp)) + from = '>=' + fM + '.' + fm + '.0'; + else + from = '>=' + from; + + if (isX(tM)) + to = ''; + else if (isX(tm)) + to = '<' + (+tM + 1) + '.0.0'; + else if (isX(tp)) + to = '<' + tM + '.' + (+tm + 1) + '.0'; + else if (tpr) + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; + else + to = '<=' + to; + + return (from + ' ' + to).trim(); +} + + +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function(version) { + if (!version) + return false; + + if (typeof version === 'string') + version = new SemVer(version, this.loose); + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version)) + return true; + } + return false; +}; + +function testSet(set, version) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) + return false; + } + + if (version.prerelease.length) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (var i = 0; i < set.length; i++) { + debug(set[i].semver); + if (set[i].semver === ANY) + continue; + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver; + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) + return true; + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false; + } + + return true; +} + +exports.satisfies = satisfies; +function satisfies(version, range, loose) { + try { + range = new Range(range, loose); + } catch (er) { + return false; + } + return range.test(version); +} + +exports.maxSatisfying = maxSatisfying; +function maxSatisfying(versions, range, loose) { + var max = null; + var maxSV = null; + try { + var rangeObj = new Range(range, loose); + } catch (er) { + return null; + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { // satisfies(v, range, loose) + if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) + max = v; + maxSV = new SemVer(max, loose); + } + } + }) + return max; +} + +exports.minSatisfying = minSatisfying; +function minSatisfying(versions, range, loose) { + var min = null; + var minSV = null; + try { + var rangeObj = new Range(range, loose); + } catch (er) { + return null; + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { // satisfies(v, range, loose) + if (!min || minSV.compare(v) === 1) { // compare(min, v, true) + min = v; + minSV = new SemVer(min, loose); + } + } + }) + return min; +} + +exports.validRange = validRange; +function validRange(range, loose) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, loose).range || '*'; + } catch (er) { + return null; + } +} + +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr; +function ltr(version, range, loose) { + return outside(version, range, '<', loose); +} + +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr; +function gtr(version, range, loose) { + return outside(version, range, '>', loose); +} + +exports.outside = outside; +function outside(version, range, hilo, loose) { + version = new SemVer(version, loose); + range = new Range(range, loose); + + var gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break; + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break; + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } + + // If it satisifes the range it is not outside + if (satisfies(version, range, loose)) { + return false; + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i]; + + var high = null; + var low = null; + + comparators.forEach(function(comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, loose)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, loose)) { + low = comparator; + } + }); + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false; + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false; + } + } + return true; +} + +exports.prerelease = prerelease; +function prerelease(version, loose) { + var parsed = parse(version, loose); + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null; +} + +exports.intersects = intersects; +function intersects(r1, r2, loose) { + r1 = new Range(r1, loose) + r2 = new Range(r2, loose) + return r1.intersects(r2) +} + + +/***/ }), +/* 199 */ +/***/ (function(module, exports, __webpack_require__) { + +var parse = __webpack_require__(200); +var correct = __webpack_require__(202); + +var genericWarning = ( + 'license should be ' + + 'a valid SPDX license expression (without "LicenseRef"), ' + + '"UNLICENSED", or ' + + '"SEE LICENSE IN "' +); + +var fileReferenceRE = /^SEE LICEN[CS]E IN (.+)$/; + +function startsWith(prefix, string) { + return string.slice(0, prefix.length) === prefix; +} + +function usesLicenseRef(ast) { + if (ast.hasOwnProperty('license')) { + var license = ast.license; + return ( + startsWith('LicenseRef', license) || + startsWith('DocumentRef', license) + ); + } else { + return ( + usesLicenseRef(ast.left) || + usesLicenseRef(ast.right) + ); + } +} + +module.exports = function(argument) { + var ast; + + try { + ast = parse(argument); + } catch (e) { + var match + if ( + argument === 'UNLICENSED' || + argument === 'UNLICENCED' + ) { + return { + validForOldPackages: true, + validForNewPackages: true, + unlicensed: true + }; + } else if (match = fileReferenceRE.exec(argument)) { + return { + validForOldPackages: true, + validForNewPackages: true, + inFile: match[1] + }; + } else { + var result = { + validForOldPackages: false, + validForNewPackages: false, + warnings: [genericWarning] + }; + var corrected = correct(argument); + if (corrected) { + result.warnings.push( + 'license is similar to the valid expression "' + corrected + '"' + ); + } + return result; + } + } + + if (usesLicenseRef(ast)) { + return { + validForNewPackages: false, + validForOldPackages: false, + spdx: true, + warnings: [genericWarning] + }; + } else { + return { + validForNewPackages: true, + validForOldPackages: true, + spdx: true + }; + } +}; + + +/***/ }), +/* 200 */ +/***/ (function(module, exports, __webpack_require__) { + +var parser = __webpack_require__(201).parser + +module.exports = function (argument) { + return parser.parse(argument) +} + + +/***/ }), +/* 201 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(module) {/* parser generated by jison 0.4.17 */ +/* + Returns a Parser object of the following structure: + + Parser: { + yy: {} + } + + Parser.prototype: { + yy: {}, + trace: function(), + symbols_: {associative list: name ==> number}, + terminals_: {associative list: number ==> name}, + productions_: [...], + performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$), + table: [...], + defaultActions: {...}, + parseError: function(str, hash), + parse: function(input), + + lexer: { + EOF: 1, + parseError: function(str, hash), + setInput: function(input), + input: function(), + unput: function(str), + more: function(), + less: function(n), + pastInput: function(), + upcomingInput: function(), + showPosition: function(), + test_match: function(regex_match_array, rule_index), + next: function(), + lex: function(), + begin: function(condition), + popState: function(), + _currentRules: function(), + topState: function(), + pushState: function(condition), + + options: { + ranges: boolean (optional: true ==> token location info will include a .range[] member) + flex: boolean (optional: true ==> flex-like lexing behaviour where the rules are tested exhaustively to find the longest match) + backtrack_lexer: boolean (optional: true ==> lexer regexes are tested in order and for each matching regex the action code is invoked; the lexer terminates the scan when a token is returned by the action code) + }, + + performAction: function(yy, yy_, $avoiding_name_collisions, YY_START), + rules: [...], + conditions: {associative list: name ==> set}, + } + } + + + token location info (@$, _$, etc.): { + first_line: n, + last_line: n, + first_column: n, + last_column: n, + range: [start_number, end_number] (where the numbers are indexes into the input string, regular zero-based) + } + + + the parseError function receives a 'hash' object with these members for lexer and parser errors: { + text: (matched text) + token: (the produced terminal token, if any) + line: (yylineno) + } + while parser (grammar) errors will also provide these members, i.e. parser errors deliver a superset of attributes: { + loc: (yylloc) + expected: (string describing the set of expected tokens) + recoverable: (boolean: TRUE when the parser has a error recovery rule available for this particular error) + } +*/ +var spdxparse = (function(){ +var o=function(k,v,o,l){for(o=o||{},l=k.length;l--;o[k[l]]=v);return o},$V0=[1,5],$V1=[1,6],$V2=[1,7],$V3=[1,4],$V4=[1,9],$V5=[1,10],$V6=[5,14,15,17],$V7=[5,12,14,15,17]; +var parser = {trace: function trace() { }, +yy: {}, +symbols_: {"error":2,"start":3,"expression":4,"EOS":5,"simpleExpression":6,"LICENSE":7,"PLUS":8,"LICENSEREF":9,"DOCUMENTREF":10,"COLON":11,"WITH":12,"EXCEPTION":13,"AND":14,"OR":15,"OPEN":16,"CLOSE":17,"$accept":0,"$end":1}, +terminals_: {2:"error",5:"EOS",7:"LICENSE",8:"PLUS",9:"LICENSEREF",10:"DOCUMENTREF",11:"COLON",12:"WITH",13:"EXCEPTION",14:"AND",15:"OR",16:"OPEN",17:"CLOSE"}, +productions_: [0,[3,2],[6,1],[6,2],[6,1],[6,3],[4,1],[4,3],[4,3],[4,3],[4,3]], +performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate /* action[1] */, $$ /* vstack */, _$ /* lstack */) { +/* this == yyval */ + +var $0 = $$.length - 1; +switch (yystate) { +case 1: +return this.$ = $$[$0-1] +break; +case 2: case 4: case 5: +this.$ = {license: yytext} +break; +case 3: +this.$ = {license: $$[$0-1], plus: true} +break; +case 6: +this.$ = $$[$0] +break; +case 7: +this.$ = {exception: $$[$0]} +this.$.license = $$[$0-2].license +if ($$[$0-2].hasOwnProperty('plus')) { + this.$.plus = $$[$0-2].plus +} +break; +case 8: +this.$ = {conjunction: 'and', left: $$[$0-2], right: $$[$0]} +break; +case 9: +this.$ = {conjunction: 'or', left: $$[$0-2], right: $$[$0]} +break; +case 10: +this.$ = $$[$0-1] +break; +} +}, +table: [{3:1,4:2,6:3,7:$V0,9:$V1,10:$V2,16:$V3},{1:[3]},{5:[1,8],14:$V4,15:$V5},o($V6,[2,6],{12:[1,11]}),{4:12,6:3,7:$V0,9:$V1,10:$V2,16:$V3},o($V7,[2,2],{8:[1,13]}),o($V7,[2,4]),{11:[1,14]},{1:[2,1]},{4:15,6:3,7:$V0,9:$V1,10:$V2,16:$V3},{4:16,6:3,7:$V0,9:$V1,10:$V2,16:$V3},{13:[1,17]},{14:$V4,15:$V5,17:[1,18]},o($V7,[2,3]),{9:[1,19]},o($V6,[2,8]),o([5,15,17],[2,9],{14:$V4}),o($V6,[2,7]),o($V6,[2,10]),o($V7,[2,5])], +defaultActions: {8:[2,1]}, +parseError: function parseError(str, hash) { + if (hash.recoverable) { + this.trace(str); + } else { + function _parseError (msg, hash) { + this.message = msg; + this.hash = hash; + } + _parseError.prototype = Error; + + throw new _parseError(str, hash); + } +}, +parse: function parse(input) { + var self = this, stack = [0], tstack = [], vstack = [null], lstack = [], table = this.table, yytext = '', yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1; + var args = lstack.slice.call(arguments, 1); + var lexer = Object.create(this.lexer); + var sharedState = { yy: {} }; + for (var k in this.yy) { + if (Object.prototype.hasOwnProperty.call(this.yy, k)) { + sharedState.yy[k] = this.yy[k]; + } + } + lexer.setInput(input, sharedState.yy); + sharedState.yy.lexer = lexer; + sharedState.yy.parser = this; + if (typeof lexer.yylloc == 'undefined') { + lexer.yylloc = {}; + } + var yyloc = lexer.yylloc; + lstack.push(yyloc); + var ranges = lexer.options && lexer.options.ranges; + if (typeof sharedState.yy.parseError === 'function') { + this.parseError = sharedState.yy.parseError; + } else { + this.parseError = Object.getPrototypeOf(this).parseError; + } + function popStack(n) { + stack.length = stack.length - 2 * n; + vstack.length = vstack.length - n; + lstack.length = lstack.length - n; + } + _token_stack: + var lex = function () { + var token; + token = lexer.lex() || EOF; + if (typeof token !== 'number') { + token = self.symbols_[token] || token; + } + return token; + }; + var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected; + while (true) { + state = stack[stack.length - 1]; + if (this.defaultActions[state]) { + action = this.defaultActions[state]; + } else { + if (symbol === null || typeof symbol == 'undefined') { + symbol = lex(); + } + action = table[state] && table[state][symbol]; + } + if (typeof action === 'undefined' || !action.length || !action[0]) { + var errStr = ''; + expected = []; + for (p in table[state]) { + if (this.terminals_[p] && p > TERROR) { + expected.push('\'' + this.terminals_[p] + '\''); + } + } + if (lexer.showPosition) { + errStr = 'Parse error on line ' + (yylineno + 1) + ':\n' + lexer.showPosition() + '\nExpecting ' + expected.join(', ') + ', got \'' + (this.terminals_[symbol] || symbol) + '\''; + } else { + errStr = 'Parse error on line ' + (yylineno + 1) + ': Unexpected ' + (symbol == EOF ? 'end of input' : '\'' + (this.terminals_[symbol] || symbol) + '\''); + } + this.parseError(errStr, { + text: lexer.match, + token: this.terminals_[symbol] || symbol, + line: lexer.yylineno, + loc: yyloc, + expected: expected + }); + } + if (action[0] instanceof Array && action.length > 1) { + throw new Error('Parse Error: multiple actions possible at state: ' + state + ', token: ' + symbol); + } + switch (action[0]) { + case 1: + stack.push(symbol); + vstack.push(lexer.yytext); + lstack.push(lexer.yylloc); + stack.push(action[1]); + symbol = null; + if (!preErrorSymbol) { + yyleng = lexer.yyleng; + yytext = lexer.yytext; + yylineno = lexer.yylineno; + yyloc = lexer.yylloc; + if (recovering > 0) { + recovering--; + } + } else { + symbol = preErrorSymbol; + preErrorSymbol = null; + } + break; + case 2: + len = this.productions_[action[1]][1]; + yyval.$ = vstack[vstack.length - len]; + yyval._$ = { + first_line: lstack[lstack.length - (len || 1)].first_line, + last_line: lstack[lstack.length - 1].last_line, + first_column: lstack[lstack.length - (len || 1)].first_column, + last_column: lstack[lstack.length - 1].last_column + }; + if (ranges) { + yyval._$.range = [ + lstack[lstack.length - (len || 1)].range[0], + lstack[lstack.length - 1].range[1] + ]; + } + r = this.performAction.apply(yyval, [ + yytext, + yyleng, + yylineno, + sharedState.yy, + action[1], + vstack, + lstack + ].concat(args)); + if (typeof r !== 'undefined') { + return r; + } + if (len) { + stack = stack.slice(0, -1 * len * 2); + vstack = vstack.slice(0, -1 * len); + lstack = lstack.slice(0, -1 * len); + } + stack.push(this.productions_[action[1]][0]); + vstack.push(yyval.$); + lstack.push(yyval._$); + newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; + stack.push(newState); + break; + case 3: + return true; + } + } + return true; +}}; +/* generated by jison-lex 0.3.4 */ +var lexer = (function(){ +var lexer = ({ + +EOF:1, + +parseError:function parseError(str, hash) { + if (this.yy.parser) { + this.yy.parser.parseError(str, hash); + } else { + throw new Error(str); + } + }, + +// resets the lexer, sets new input +setInput:function (input, yy) { + this.yy = yy || this.yy || {}; + this._input = input; + this._more = this._backtrack = this.done = false; + this.yylineno = this.yyleng = 0; + this.yytext = this.matched = this.match = ''; + this.conditionStack = ['INITIAL']; + this.yylloc = { + first_line: 1, + first_column: 0, + last_line: 1, + last_column: 0 + }; + if (this.options.ranges) { + this.yylloc.range = [0,0]; + } + this.offset = 0; + return this; + }, + +// consumes and returns one char from the input +input:function () { + var ch = this._input[0]; + this.yytext += ch; + this.yyleng++; + this.offset++; + this.match += ch; + this.matched += ch; + var lines = ch.match(/(?:\r\n?|\n).*/g); + if (lines) { + this.yylineno++; + this.yylloc.last_line++; + } else { + this.yylloc.last_column++; + } + if (this.options.ranges) { + this.yylloc.range[1]++; + } + + this._input = this._input.slice(1); + return ch; + }, + +// unshifts one char (or a string) into the input +unput:function (ch) { + var len = ch.length; + var lines = ch.split(/(?:\r\n?|\n)/g); + + this._input = ch + this._input; + this.yytext = this.yytext.substr(0, this.yytext.length - len); + //this.yyleng -= len; + this.offset -= len; + var oldLines = this.match.split(/(?:\r\n?|\n)/g); + this.match = this.match.substr(0, this.match.length - 1); + this.matched = this.matched.substr(0, this.matched.length - 1); + + if (lines.length - 1) { + this.yylineno -= lines.length - 1; + } + var r = this.yylloc.range; + + this.yylloc = { + first_line: this.yylloc.first_line, + last_line: this.yylineno + 1, + first_column: this.yylloc.first_column, + last_column: lines ? + (lines.length === oldLines.length ? this.yylloc.first_column : 0) + + oldLines[oldLines.length - lines.length].length - lines[0].length : + this.yylloc.first_column - len + }; + + if (this.options.ranges) { + this.yylloc.range = [r[0], r[0] + this.yyleng - len]; + } + this.yyleng = this.yytext.length; + return this; + }, + +// When called from action, caches matched text and appends it on next action +more:function () { + this._more = true; + return this; + }, + +// When called from action, signals the lexer that this rule fails to match the input, so the next matching rule (regex) should be tested instead. +reject:function () { + if (this.options.backtrack_lexer) { + this._backtrack = true; + } else { + return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n' + this.showPosition(), { + text: "", + token: null, + line: this.yylineno + }); + + } + return this; + }, + +// retain first n characters of the match +less:function (n) { + this.unput(this.match.slice(n)); + }, + +// displays already matched input, i.e. for error messages +pastInput:function () { + var past = this.matched.substr(0, this.matched.length - this.match.length); + return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, ""); + }, + +// displays upcoming input, i.e. for error messages +upcomingInput:function () { + var next = this.match; + if (next.length < 20) { + next += this._input.substr(0, 20-next.length); + } + return (next.substr(0,20) + (next.length > 20 ? '...' : '')).replace(/\n/g, ""); + }, + +// displays the character position where the lexing error occurred, i.e. for error messages +showPosition:function () { + var pre = this.pastInput(); + var c = new Array(pre.length + 1).join("-"); + return pre + this.upcomingInput() + "\n" + c + "^"; + }, + +// test the lexed token: return FALSE when not a match, otherwise return token +test_match:function (match, indexed_rule) { + var token, + lines, + backup; + + if (this.options.backtrack_lexer) { + // save context + backup = { + yylineno: this.yylineno, + yylloc: { + first_line: this.yylloc.first_line, + last_line: this.last_line, + first_column: this.yylloc.first_column, + last_column: this.yylloc.last_column + }, + yytext: this.yytext, + match: this.match, + matches: this.matches, + matched: this.matched, + yyleng: this.yyleng, + offset: this.offset, + _more: this._more, + _input: this._input, + yy: this.yy, + conditionStack: this.conditionStack.slice(0), + done: this.done + }; + if (this.options.ranges) { + backup.yylloc.range = this.yylloc.range.slice(0); + } + } + + lines = match[0].match(/(?:\r\n?|\n).*/g); + if (lines) { + this.yylineno += lines.length; + } + this.yylloc = { + first_line: this.yylloc.last_line, + last_line: this.yylineno + 1, + first_column: this.yylloc.last_column, + last_column: lines ? + lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : + this.yylloc.last_column + match[0].length + }; + this.yytext += match[0]; + this.match += match[0]; + this.matches = match; + this.yyleng = this.yytext.length; + if (this.options.ranges) { + this.yylloc.range = [this.offset, this.offset += this.yyleng]; + } + this._more = false; + this._backtrack = false; + this._input = this._input.slice(match[0].length); + this.matched += match[0]; + token = this.performAction.call(this, this.yy, this, indexed_rule, this.conditionStack[this.conditionStack.length - 1]); + if (this.done && this._input) { + this.done = false; + } + if (token) { + return token; + } else if (this._backtrack) { + // recover context + for (var k in backup) { + this[k] = backup[k]; + } + return false; // rule action called reject() implying the next rule should be tested instead. + } + return false; + }, + +// return next match in input +next:function () { + if (this.done) { + return this.EOF; + } + if (!this._input) { + this.done = true; + } + + var token, + match, + tempMatch, + index; + if (!this._more) { + this.yytext = ''; + this.match = ''; + } + var rules = this._currentRules(); + for (var i = 0; i < rules.length; i++) { + tempMatch = this._input.match(this.rules[rules[i]]); + if (tempMatch && (!match || tempMatch[0].length > match[0].length)) { + match = tempMatch; + index = i; + if (this.options.backtrack_lexer) { + token = this.test_match(tempMatch, rules[i]); + if (token !== false) { + return token; + } else if (this._backtrack) { + match = false; + continue; // rule action called reject() implying a rule MISmatch. + } else { + // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace) + return false; + } + } else if (!this.options.flex) { + break; + } + } + } + if (match) { + token = this.test_match(match, rules[index]); + if (token !== false) { + return token; + } + // else: this is a lexer rule which consumes input without producing a token (e.g. whitespace) + return false; + } + if (this._input === "") { + return this.EOF; + } else { + return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { + text: "", + token: null, + line: this.yylineno + }); + } + }, + +// return next match that has a token +lex:function lex() { + var r = this.next(); + if (r) { + return r; + } else { + return this.lex(); + } + }, + +// activates a new lexer condition state (pushes the new lexer condition state onto the condition stack) +begin:function begin(condition) { + this.conditionStack.push(condition); + }, + +// pop the previously active lexer condition state off the condition stack +popState:function popState() { + var n = this.conditionStack.length - 1; + if (n > 0) { + return this.conditionStack.pop(); + } else { + return this.conditionStack[0]; + } + }, + +// produce the lexer rule set which is active for the currently active lexer condition state +_currentRules:function _currentRules() { + if (this.conditionStack.length && this.conditionStack[this.conditionStack.length - 1]) { + return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules; + } else { + return this.conditions["INITIAL"].rules; + } + }, + +// return the currently active lexer condition state; when an index argument is provided it produces the N-th previous condition state, if available +topState:function topState(n) { + n = this.conditionStack.length - 1 - Math.abs(n || 0); + if (n >= 0) { + return this.conditionStack[n]; + } else { + return "INITIAL"; + } + }, + +// alias for begin(condition) +pushState:function pushState(condition) { + this.begin(condition); + }, + +// return the number of states currently on the stack +stateStackSize:function stateStackSize() { + return this.conditionStack.length; + }, +options: {}, +performAction: function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) { +var YYSTATE=YY_START; +switch($avoiding_name_collisions) { +case 0:return 5 +break; +case 1:/* skip whitespace */ +break; +case 2:return 8 +break; case 3:return 16 break; case 4:return 17 @@ -17452,8308 +23861,27282 @@ break; case 364:return 7 break; } -}, -rules: [/^(?:$)/,/^(?:\s+)/,/^(?:\+)/,/^(?:\()/,/^(?:\))/,/^(?::)/,/^(?:DocumentRef-([0-9A-Za-z-+.]+))/,/^(?:LicenseRef-([0-9A-Za-z-+.]+))/,/^(?:AND)/,/^(?:OR)/,/^(?:WITH)/,/^(?:BSD-3-Clause-No-Nuclear-License-2014)/,/^(?:BSD-3-Clause-No-Nuclear-Warranty)/,/^(?:GPL-2\.0-with-classpath-exception)/,/^(?:GPL-3\.0-with-autoconf-exception)/,/^(?:GPL-2\.0-with-autoconf-exception)/,/^(?:BSD-3-Clause-No-Nuclear-License)/,/^(?:MPL-2\.0-no-copyleft-exception)/,/^(?:GPL-2\.0-with-bison-exception)/,/^(?:GPL-2\.0-with-font-exception)/,/^(?:GPL-2\.0-with-GCC-exception)/,/^(?:CNRI-Python-GPL-Compatible)/,/^(?:GPL-3\.0-with-GCC-exception)/,/^(?:BSD-3-Clause-Attribution)/,/^(?:Classpath-exception-2\.0)/,/^(?:WxWindows-exception-3\.1)/,/^(?:freertos-exception-2\.0)/,/^(?:Autoconf-exception-3\.0)/,/^(?:i2p-gpl-java-exception)/,/^(?:gnu-javamail-exception)/,/^(?:Nokia-Qt-exception-1\.1)/,/^(?:Autoconf-exception-2\.0)/,/^(?:BSD-2-Clause-FreeBSD)/,/^(?:u-boot-exception-2\.0)/,/^(?:zlib-acknowledgement)/,/^(?:Bison-exception-2\.2)/,/^(?:BSD-2-Clause-NetBSD)/,/^(?:CLISP-exception-2\.0)/,/^(?:eCos-exception-2\.0)/,/^(?:BSD-3-Clause-Clear)/,/^(?:Font-exception-2\.0)/,/^(?:FLTK-exception-2\.0)/,/^(?:GCC-exception-2\.0)/,/^(?:Qwt-exception-1\.0)/,/^(?:Libtool-exception)/,/^(?:BSD-3-Clause-LBNL)/,/^(?:GCC-exception-3\.1)/,/^(?:Artistic-1\.0-Perl)/,/^(?:Artistic-1\.0-cl8)/,/^(?:CC-BY-NC-SA-2\.5)/,/^(?:MIT-advertising)/,/^(?:BSD-Source-Code)/,/^(?:CC-BY-NC-SA-4\.0)/,/^(?:LiLiQ-Rplus-1\.1)/,/^(?:CC-BY-NC-SA-3\.0)/,/^(?:BSD-4-Clause-UC)/,/^(?:CC-BY-NC-SA-2\.0)/,/^(?:CC-BY-NC-SA-1\.0)/,/^(?:CC-BY-NC-ND-4\.0)/,/^(?:CC-BY-NC-ND-3\.0)/,/^(?:CC-BY-NC-ND-2\.5)/,/^(?:CC-BY-NC-ND-2\.0)/,/^(?:CC-BY-NC-ND-1\.0)/,/^(?:LZMA-exception)/,/^(?:BitTorrent-1\.1)/,/^(?:CrystalStacker)/,/^(?:FLTK-exception)/,/^(?:SugarCRM-1\.1\.3)/,/^(?:BSD-Protection)/,/^(?:BitTorrent-1\.0)/,/^(?:HaskellReport)/,/^(?:Interbase-1\.0)/,/^(?:StandardML-NJ)/,/^(?:mif-exception)/,/^(?:Frameworx-1\.0)/,/^(?:389-exception)/,/^(?:CC-BY-NC-2\.0)/,/^(?:CC-BY-NC-2\.5)/,/^(?:CC-BY-NC-3\.0)/,/^(?:CC-BY-NC-4\.0)/,/^(?:W3C-19980720)/,/^(?:CC-BY-SA-1\.0)/,/^(?:CC-BY-SA-2\.0)/,/^(?:CC-BY-SA-2\.5)/,/^(?:CC-BY-ND-2\.0)/,/^(?:CC-BY-SA-4\.0)/,/^(?:CC-BY-SA-3\.0)/,/^(?:Artistic-1\.0)/,/^(?:Artistic-2\.0)/,/^(?:CC-BY-ND-2\.5)/,/^(?:CC-BY-ND-3\.0)/,/^(?:CC-BY-ND-4\.0)/,/^(?:CC-BY-ND-1\.0)/,/^(?:BSD-4-Clause)/,/^(?:BSD-3-Clause)/,/^(?:BSD-2-Clause)/,/^(?:CC-BY-NC-1\.0)/,/^(?:bzip2-1\.0\.6)/,/^(?:Unicode-TOU)/,/^(?:CNRI-Jython)/,/^(?:ImageMagick)/,/^(?:Adobe-Glyph)/,/^(?:CUA-OPL-1\.0)/,/^(?:OLDAP-2\.2\.2)/,/^(?:LiLiQ-R-1\.1)/,/^(?:bzip2-1\.0\.5)/,/^(?:LiLiQ-P-1\.1)/,/^(?:OLDAP-2\.0\.1)/,/^(?:OLDAP-2\.2\.1)/,/^(?:CNRI-Python)/,/^(?:XFree86-1\.1)/,/^(?:OSET-PL-2\.1)/,/^(?:Apache-2\.0)/,/^(?:Watcom-1\.0)/,/^(?:PostgreSQL)/,/^(?:Python-2\.0)/,/^(?:RHeCos-1\.1)/,/^(?:EUDatagrid)/,/^(?:Spencer-99)/,/^(?:Intel-ACPI)/,/^(?:CECILL-1\.0)/,/^(?:CECILL-1\.1)/,/^(?:JasPer-2\.0)/,/^(?:CECILL-2\.0)/,/^(?:CECILL-2\.1)/,/^(?:gSOAP-1\.3b)/,/^(?:Spencer-94)/,/^(?:Apache-1\.1)/,/^(?:Spencer-86)/,/^(?:Apache-1\.0)/,/^(?:ClArtistic)/,/^(?:TORQUE-1\.1)/,/^(?:CATOSL-1\.1)/,/^(?:Adobe-2006)/,/^(?:Zimbra-1\.4)/,/^(?:Zimbra-1\.3)/,/^(?:Condor-1\.1)/,/^(?:CC-BY-3\.0)/,/^(?:CC-BY-2\.5)/,/^(?:OLDAP-2\.4)/,/^(?:SGI-B-1\.1)/,/^(?:SISSL-1\.2)/,/^(?:SGI-B-1\.0)/,/^(?:OLDAP-2\.3)/,/^(?:CC-BY-4\.0)/,/^(?:Crossword)/,/^(?:SimPL-2\.0)/,/^(?:OLDAP-2\.2)/,/^(?:OLDAP-2\.1)/,/^(?:ErlPL-1\.1)/,/^(?:LPPL-1\.3a)/,/^(?:LPPL-1\.3c)/,/^(?:OLDAP-2\.0)/,/^(?:Leptonica)/,/^(?:CPOL-1\.02)/,/^(?:OLDAP-1\.4)/,/^(?:OLDAP-1\.3)/,/^(?:CC-BY-2\.0)/,/^(?:Unlicense)/,/^(?:OLDAP-2\.8)/,/^(?:OLDAP-1\.2)/,/^(?:MakeIndex)/,/^(?:OLDAP-2\.7)/,/^(?:OLDAP-1\.1)/,/^(?:Sleepycat)/,/^(?:D-FSL-1\.0)/,/^(?:CC-BY-1\.0)/,/^(?:OLDAP-2\.6)/,/^(?:WXwindows)/,/^(?:NPOSL-3\.0)/,/^(?:FreeImage)/,/^(?:SGI-B-2\.0)/,/^(?:OLDAP-2\.5)/,/^(?:Beerware)/,/^(?:Newsletr)/,/^(?:NBPL-1\.0)/,/^(?:NASA-1\.3)/,/^(?:NLOD-1\.0)/,/^(?:AGPL-1\.0)/,/^(?:OCLC-2\.0)/,/^(?:ODbL-1\.0)/,/^(?:PDDL-1\.0)/,/^(?:Motosoto)/,/^(?:Afmparse)/,/^(?:ANTLR-PD)/,/^(?:LPL-1\.02)/,/^(?:Abstyles)/,/^(?:eCos-2\.0)/,/^(?:APSL-1\.0)/,/^(?:LPPL-1\.2)/,/^(?:LPPL-1\.1)/,/^(?:LPPL-1\.0)/,/^(?:APSL-1\.1)/,/^(?:APSL-2\.0)/,/^(?:Info-ZIP)/,/^(?:Zend-2\.0)/,/^(?:IBM-pibs)/,/^(?:LGPL-2\.0)/,/^(?:LGPL-3\.0)/,/^(?:LGPL-2\.1)/,/^(?:GFDL-1\.3)/,/^(?:PHP-3\.01)/,/^(?:GFDL-1\.2)/,/^(?:GFDL-1\.1)/,/^(?:AGPL-3\.0)/,/^(?:Giftware)/,/^(?:EUPL-1\.1)/,/^(?:RPSL-1\.0)/,/^(?:EUPL-1\.0)/,/^(?:MIT-enna)/,/^(?:CECILL-B)/,/^(?:diffmark)/,/^(?:CECILL-C)/,/^(?:CDDL-1\.0)/,/^(?:Sendmail)/,/^(?:CDDL-1\.1)/,/^(?:CPAL-1\.0)/,/^(?:APSL-1\.2)/,/^(?:NPL-1\.1)/,/^(?:AFL-1\.2)/,/^(?:Caldera)/,/^(?:AFL-2\.0)/,/^(?:FSFULLR)/,/^(?:AFL-2\.1)/,/^(?:VSL-1\.0)/,/^(?:VOSTROM)/,/^(?:UPL-1\.0)/,/^(?:Dotseqn)/,/^(?:CPL-1\.0)/,/^(?:dvipdfm)/,/^(?:EPL-1\.0)/,/^(?:OCCT-PL)/,/^(?:ECL-1\.0)/,/^(?:Latex2e)/,/^(?:ECL-2\.0)/,/^(?:GPL-1\.0)/,/^(?:GPL-2\.0)/,/^(?:GPL-3\.0)/,/^(?:AFL-3\.0)/,/^(?:LAL-1\.2)/,/^(?:LAL-1\.3)/,/^(?:EFL-1\.0)/,/^(?:EFL-2\.0)/,/^(?:gnuplot)/,/^(?:Aladdin)/,/^(?:LPL-1\.0)/,/^(?:libtiff)/,/^(?:Entessa)/,/^(?:AMDPLPA)/,/^(?:IPL-1\.0)/,/^(?:OPL-1\.0)/,/^(?:OSL-1\.0)/,/^(?:OSL-1\.1)/,/^(?:OSL-2\.0)/,/^(?:OSL-2\.1)/,/^(?:OSL-3\.0)/,/^(?:OpenSSL)/,/^(?:ZPL-2\.1)/,/^(?:PHP-3\.0)/,/^(?:ZPL-2\.0)/,/^(?:ZPL-1\.1)/,/^(?:CC0-1\.0)/,/^(?:SPL-1\.0)/,/^(?:psutils)/,/^(?:MPL-1\.0)/,/^(?:QPL-1\.0)/,/^(?:MPL-1\.1)/,/^(?:MPL-2\.0)/,/^(?:APL-1\.0)/,/^(?:RPL-1\.1)/,/^(?:RPL-1\.5)/,/^(?:MIT-CMU)/,/^(?:Multics)/,/^(?:Eurosym)/,/^(?:BSL-1\.0)/,/^(?:MIT-feh)/,/^(?:Saxpath)/,/^(?:Borceux)/,/^(?:OFL-1\.1)/,/^(?:OFL-1\.0)/,/^(?:AFL-1\.1)/,/^(?:YPL-1\.1)/,/^(?:YPL-1\.0)/,/^(?:NPL-1\.0)/,/^(?:iMatix)/,/^(?:mpich2)/,/^(?:APAFML)/,/^(?:Bahyph)/,/^(?:RSA-MD)/,/^(?:psfrag)/,/^(?:Plexus)/,/^(?:eGenix)/,/^(?:Glulxe)/,/^(?:SAX-PD)/,/^(?:Imlib2)/,/^(?:Wsuipa)/,/^(?:LGPLLR)/,/^(?:Libpng)/,/^(?:xinetd)/,/^(?:MITNFA)/,/^(?:NetCDF)/,/^(?:Naumen)/,/^(?:SMPPL)/,/^(?:Nunit)/,/^(?:FSFUL)/,/^(?:GL2PS)/,/^(?:SMLNJ)/,/^(?:Rdisc)/,/^(?:Noweb)/,/^(?:Nokia)/,/^(?:SISSL)/,/^(?:Qhull)/,/^(?:Intel)/,/^(?:Glide)/,/^(?:Xerox)/,/^(?:AMPAS)/,/^(?:WTFPL)/,/^(?:MS-PL)/,/^(?:XSkat)/,/^(?:MS-RL)/,/^(?:MirOS)/,/^(?:RSCPL)/,/^(?:TMate)/,/^(?:OGTSL)/,/^(?:FSFAP)/,/^(?:NCSA)/,/^(?:Zlib)/,/^(?:SCEA)/,/^(?:SNIA)/,/^(?:NGPL)/,/^(?:NOSL)/,/^(?:ADSL)/,/^(?:MTLL)/,/^(?:NLPL)/,/^(?:Ruby)/,/^(?:JSON)/,/^(?:Barr)/,/^(?:0BSD)/,/^(?:Xnet)/,/^(?:Cube)/,/^(?:curl)/,/^(?:DSDP)/,/^(?:Fair)/,/^(?:HPND)/,/^(?:TOSL)/,/^(?:IJG)/,/^(?:SWL)/,/^(?:Vim)/,/^(?:FTL)/,/^(?:ICU)/,/^(?:OML)/,/^(?:NRL)/,/^(?:DOC)/,/^(?:TCL)/,/^(?:W3C)/,/^(?:NTP)/,/^(?:IPA)/,/^(?:ISC)/,/^(?:X11)/,/^(?:AAL)/,/^(?:AML)/,/^(?:xpp)/,/^(?:Zed)/,/^(?:MIT)/,/^(?:Mup)/], -conditions: {"INITIAL":{"rules":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364],"inclusive":true}} -}); -return lexer; -})(); -parser.lexer = lexer; -function Parser () { - this.yy = {}; +}, +rules: [/^(?:$)/,/^(?:\s+)/,/^(?:\+)/,/^(?:\()/,/^(?:\))/,/^(?::)/,/^(?:DocumentRef-([0-9A-Za-z-+.]+))/,/^(?:LicenseRef-([0-9A-Za-z-+.]+))/,/^(?:AND)/,/^(?:OR)/,/^(?:WITH)/,/^(?:BSD-3-Clause-No-Nuclear-License-2014)/,/^(?:BSD-3-Clause-No-Nuclear-Warranty)/,/^(?:GPL-2\.0-with-classpath-exception)/,/^(?:GPL-3\.0-with-autoconf-exception)/,/^(?:GPL-2\.0-with-autoconf-exception)/,/^(?:BSD-3-Clause-No-Nuclear-License)/,/^(?:MPL-2\.0-no-copyleft-exception)/,/^(?:GPL-2\.0-with-bison-exception)/,/^(?:GPL-2\.0-with-font-exception)/,/^(?:GPL-2\.0-with-GCC-exception)/,/^(?:CNRI-Python-GPL-Compatible)/,/^(?:GPL-3\.0-with-GCC-exception)/,/^(?:BSD-3-Clause-Attribution)/,/^(?:Classpath-exception-2\.0)/,/^(?:WxWindows-exception-3\.1)/,/^(?:freertos-exception-2\.0)/,/^(?:Autoconf-exception-3\.0)/,/^(?:i2p-gpl-java-exception)/,/^(?:gnu-javamail-exception)/,/^(?:Nokia-Qt-exception-1\.1)/,/^(?:Autoconf-exception-2\.0)/,/^(?:BSD-2-Clause-FreeBSD)/,/^(?:u-boot-exception-2\.0)/,/^(?:zlib-acknowledgement)/,/^(?:Bison-exception-2\.2)/,/^(?:BSD-2-Clause-NetBSD)/,/^(?:CLISP-exception-2\.0)/,/^(?:eCos-exception-2\.0)/,/^(?:BSD-3-Clause-Clear)/,/^(?:Font-exception-2\.0)/,/^(?:FLTK-exception-2\.0)/,/^(?:GCC-exception-2\.0)/,/^(?:Qwt-exception-1\.0)/,/^(?:Libtool-exception)/,/^(?:BSD-3-Clause-LBNL)/,/^(?:GCC-exception-3\.1)/,/^(?:Artistic-1\.0-Perl)/,/^(?:Artistic-1\.0-cl8)/,/^(?:CC-BY-NC-SA-2\.5)/,/^(?:MIT-advertising)/,/^(?:BSD-Source-Code)/,/^(?:CC-BY-NC-SA-4\.0)/,/^(?:LiLiQ-Rplus-1\.1)/,/^(?:CC-BY-NC-SA-3\.0)/,/^(?:BSD-4-Clause-UC)/,/^(?:CC-BY-NC-SA-2\.0)/,/^(?:CC-BY-NC-SA-1\.0)/,/^(?:CC-BY-NC-ND-4\.0)/,/^(?:CC-BY-NC-ND-3\.0)/,/^(?:CC-BY-NC-ND-2\.5)/,/^(?:CC-BY-NC-ND-2\.0)/,/^(?:CC-BY-NC-ND-1\.0)/,/^(?:LZMA-exception)/,/^(?:BitTorrent-1\.1)/,/^(?:CrystalStacker)/,/^(?:FLTK-exception)/,/^(?:SugarCRM-1\.1\.3)/,/^(?:BSD-Protection)/,/^(?:BitTorrent-1\.0)/,/^(?:HaskellReport)/,/^(?:Interbase-1\.0)/,/^(?:StandardML-NJ)/,/^(?:mif-exception)/,/^(?:Frameworx-1\.0)/,/^(?:389-exception)/,/^(?:CC-BY-NC-2\.0)/,/^(?:CC-BY-NC-2\.5)/,/^(?:CC-BY-NC-3\.0)/,/^(?:CC-BY-NC-4\.0)/,/^(?:W3C-19980720)/,/^(?:CC-BY-SA-1\.0)/,/^(?:CC-BY-SA-2\.0)/,/^(?:CC-BY-SA-2\.5)/,/^(?:CC-BY-ND-2\.0)/,/^(?:CC-BY-SA-4\.0)/,/^(?:CC-BY-SA-3\.0)/,/^(?:Artistic-1\.0)/,/^(?:Artistic-2\.0)/,/^(?:CC-BY-ND-2\.5)/,/^(?:CC-BY-ND-3\.0)/,/^(?:CC-BY-ND-4\.0)/,/^(?:CC-BY-ND-1\.0)/,/^(?:BSD-4-Clause)/,/^(?:BSD-3-Clause)/,/^(?:BSD-2-Clause)/,/^(?:CC-BY-NC-1\.0)/,/^(?:bzip2-1\.0\.6)/,/^(?:Unicode-TOU)/,/^(?:CNRI-Jython)/,/^(?:ImageMagick)/,/^(?:Adobe-Glyph)/,/^(?:CUA-OPL-1\.0)/,/^(?:OLDAP-2\.2\.2)/,/^(?:LiLiQ-R-1\.1)/,/^(?:bzip2-1\.0\.5)/,/^(?:LiLiQ-P-1\.1)/,/^(?:OLDAP-2\.0\.1)/,/^(?:OLDAP-2\.2\.1)/,/^(?:CNRI-Python)/,/^(?:XFree86-1\.1)/,/^(?:OSET-PL-2\.1)/,/^(?:Apache-2\.0)/,/^(?:Watcom-1\.0)/,/^(?:PostgreSQL)/,/^(?:Python-2\.0)/,/^(?:RHeCos-1\.1)/,/^(?:EUDatagrid)/,/^(?:Spencer-99)/,/^(?:Intel-ACPI)/,/^(?:CECILL-1\.0)/,/^(?:CECILL-1\.1)/,/^(?:JasPer-2\.0)/,/^(?:CECILL-2\.0)/,/^(?:CECILL-2\.1)/,/^(?:gSOAP-1\.3b)/,/^(?:Spencer-94)/,/^(?:Apache-1\.1)/,/^(?:Spencer-86)/,/^(?:Apache-1\.0)/,/^(?:ClArtistic)/,/^(?:TORQUE-1\.1)/,/^(?:CATOSL-1\.1)/,/^(?:Adobe-2006)/,/^(?:Zimbra-1\.4)/,/^(?:Zimbra-1\.3)/,/^(?:Condor-1\.1)/,/^(?:CC-BY-3\.0)/,/^(?:CC-BY-2\.5)/,/^(?:OLDAP-2\.4)/,/^(?:SGI-B-1\.1)/,/^(?:SISSL-1\.2)/,/^(?:SGI-B-1\.0)/,/^(?:OLDAP-2\.3)/,/^(?:CC-BY-4\.0)/,/^(?:Crossword)/,/^(?:SimPL-2\.0)/,/^(?:OLDAP-2\.2)/,/^(?:OLDAP-2\.1)/,/^(?:ErlPL-1\.1)/,/^(?:LPPL-1\.3a)/,/^(?:LPPL-1\.3c)/,/^(?:OLDAP-2\.0)/,/^(?:Leptonica)/,/^(?:CPOL-1\.02)/,/^(?:OLDAP-1\.4)/,/^(?:OLDAP-1\.3)/,/^(?:CC-BY-2\.0)/,/^(?:Unlicense)/,/^(?:OLDAP-2\.8)/,/^(?:OLDAP-1\.2)/,/^(?:MakeIndex)/,/^(?:OLDAP-2\.7)/,/^(?:OLDAP-1\.1)/,/^(?:Sleepycat)/,/^(?:D-FSL-1\.0)/,/^(?:CC-BY-1\.0)/,/^(?:OLDAP-2\.6)/,/^(?:WXwindows)/,/^(?:NPOSL-3\.0)/,/^(?:FreeImage)/,/^(?:SGI-B-2\.0)/,/^(?:OLDAP-2\.5)/,/^(?:Beerware)/,/^(?:Newsletr)/,/^(?:NBPL-1\.0)/,/^(?:NASA-1\.3)/,/^(?:NLOD-1\.0)/,/^(?:AGPL-1\.0)/,/^(?:OCLC-2\.0)/,/^(?:ODbL-1\.0)/,/^(?:PDDL-1\.0)/,/^(?:Motosoto)/,/^(?:Afmparse)/,/^(?:ANTLR-PD)/,/^(?:LPL-1\.02)/,/^(?:Abstyles)/,/^(?:eCos-2\.0)/,/^(?:APSL-1\.0)/,/^(?:LPPL-1\.2)/,/^(?:LPPL-1\.1)/,/^(?:LPPL-1\.0)/,/^(?:APSL-1\.1)/,/^(?:APSL-2\.0)/,/^(?:Info-ZIP)/,/^(?:Zend-2\.0)/,/^(?:IBM-pibs)/,/^(?:LGPL-2\.0)/,/^(?:LGPL-3\.0)/,/^(?:LGPL-2\.1)/,/^(?:GFDL-1\.3)/,/^(?:PHP-3\.01)/,/^(?:GFDL-1\.2)/,/^(?:GFDL-1\.1)/,/^(?:AGPL-3\.0)/,/^(?:Giftware)/,/^(?:EUPL-1\.1)/,/^(?:RPSL-1\.0)/,/^(?:EUPL-1\.0)/,/^(?:MIT-enna)/,/^(?:CECILL-B)/,/^(?:diffmark)/,/^(?:CECILL-C)/,/^(?:CDDL-1\.0)/,/^(?:Sendmail)/,/^(?:CDDL-1\.1)/,/^(?:CPAL-1\.0)/,/^(?:APSL-1\.2)/,/^(?:NPL-1\.1)/,/^(?:AFL-1\.2)/,/^(?:Caldera)/,/^(?:AFL-2\.0)/,/^(?:FSFULLR)/,/^(?:AFL-2\.1)/,/^(?:VSL-1\.0)/,/^(?:VOSTROM)/,/^(?:UPL-1\.0)/,/^(?:Dotseqn)/,/^(?:CPL-1\.0)/,/^(?:dvipdfm)/,/^(?:EPL-1\.0)/,/^(?:OCCT-PL)/,/^(?:ECL-1\.0)/,/^(?:Latex2e)/,/^(?:ECL-2\.0)/,/^(?:GPL-1\.0)/,/^(?:GPL-2\.0)/,/^(?:GPL-3\.0)/,/^(?:AFL-3\.0)/,/^(?:LAL-1\.2)/,/^(?:LAL-1\.3)/,/^(?:EFL-1\.0)/,/^(?:EFL-2\.0)/,/^(?:gnuplot)/,/^(?:Aladdin)/,/^(?:LPL-1\.0)/,/^(?:libtiff)/,/^(?:Entessa)/,/^(?:AMDPLPA)/,/^(?:IPL-1\.0)/,/^(?:OPL-1\.0)/,/^(?:OSL-1\.0)/,/^(?:OSL-1\.1)/,/^(?:OSL-2\.0)/,/^(?:OSL-2\.1)/,/^(?:OSL-3\.0)/,/^(?:OpenSSL)/,/^(?:ZPL-2\.1)/,/^(?:PHP-3\.0)/,/^(?:ZPL-2\.0)/,/^(?:ZPL-1\.1)/,/^(?:CC0-1\.0)/,/^(?:SPL-1\.0)/,/^(?:psutils)/,/^(?:MPL-1\.0)/,/^(?:QPL-1\.0)/,/^(?:MPL-1\.1)/,/^(?:MPL-2\.0)/,/^(?:APL-1\.0)/,/^(?:RPL-1\.1)/,/^(?:RPL-1\.5)/,/^(?:MIT-CMU)/,/^(?:Multics)/,/^(?:Eurosym)/,/^(?:BSL-1\.0)/,/^(?:MIT-feh)/,/^(?:Saxpath)/,/^(?:Borceux)/,/^(?:OFL-1\.1)/,/^(?:OFL-1\.0)/,/^(?:AFL-1\.1)/,/^(?:YPL-1\.1)/,/^(?:YPL-1\.0)/,/^(?:NPL-1\.0)/,/^(?:iMatix)/,/^(?:mpich2)/,/^(?:APAFML)/,/^(?:Bahyph)/,/^(?:RSA-MD)/,/^(?:psfrag)/,/^(?:Plexus)/,/^(?:eGenix)/,/^(?:Glulxe)/,/^(?:SAX-PD)/,/^(?:Imlib2)/,/^(?:Wsuipa)/,/^(?:LGPLLR)/,/^(?:Libpng)/,/^(?:xinetd)/,/^(?:MITNFA)/,/^(?:NetCDF)/,/^(?:Naumen)/,/^(?:SMPPL)/,/^(?:Nunit)/,/^(?:FSFUL)/,/^(?:GL2PS)/,/^(?:SMLNJ)/,/^(?:Rdisc)/,/^(?:Noweb)/,/^(?:Nokia)/,/^(?:SISSL)/,/^(?:Qhull)/,/^(?:Intel)/,/^(?:Glide)/,/^(?:Xerox)/,/^(?:AMPAS)/,/^(?:WTFPL)/,/^(?:MS-PL)/,/^(?:XSkat)/,/^(?:MS-RL)/,/^(?:MirOS)/,/^(?:RSCPL)/,/^(?:TMate)/,/^(?:OGTSL)/,/^(?:FSFAP)/,/^(?:NCSA)/,/^(?:Zlib)/,/^(?:SCEA)/,/^(?:SNIA)/,/^(?:NGPL)/,/^(?:NOSL)/,/^(?:ADSL)/,/^(?:MTLL)/,/^(?:NLPL)/,/^(?:Ruby)/,/^(?:JSON)/,/^(?:Barr)/,/^(?:0BSD)/,/^(?:Xnet)/,/^(?:Cube)/,/^(?:curl)/,/^(?:DSDP)/,/^(?:Fair)/,/^(?:HPND)/,/^(?:TOSL)/,/^(?:IJG)/,/^(?:SWL)/,/^(?:Vim)/,/^(?:FTL)/,/^(?:ICU)/,/^(?:OML)/,/^(?:NRL)/,/^(?:DOC)/,/^(?:TCL)/,/^(?:W3C)/,/^(?:NTP)/,/^(?:IPA)/,/^(?:ISC)/,/^(?:X11)/,/^(?:AAL)/,/^(?:AML)/,/^(?:xpp)/,/^(?:Zed)/,/^(?:MIT)/,/^(?:Mup)/], +conditions: {"INITIAL":{"rules":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364],"inclusive":true}} +}); +return lexer; +})(); +parser.lexer = lexer; +function Parser () { + this.yy = {}; +} +Parser.prototype = parser;parser.Parser = Parser; +return new Parser; +})(); + + +if (true) { +exports.parser = spdxparse; +exports.Parser = spdxparse.Parser; +exports.parse = function () { return spdxparse.parse.apply(spdxparse, arguments); }; +exports.main = function commonjsMain(args) { + if (!args[1]) { + console.log('Usage: '+args[0]+' FILE'); + process.exit(1); + } + var source = __webpack_require__(13).readFileSync(__webpack_require__(5).normalize(args[1]), "utf8"); + return exports.parser.parse(source); +}; +if ( true && __webpack_require__.c[__webpack_require__.s] === module) { + exports.main(process.argv.slice(1)); +} +} + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(112)(module))) + +/***/ }), +/* 202 */ +/***/ (function(module, exports, __webpack_require__) { + +var licenseIDs = __webpack_require__(203); + +function valid(string) { + return licenseIDs.indexOf(string) > -1; +} + +// Common transpositions of license identifier acronyms +var transpositions = [ + ['APGL', 'AGPL'], + ['Gpl', 'GPL'], + ['GLP', 'GPL'], + ['APL', 'Apache'], + ['ISD', 'ISC'], + ['GLP', 'GPL'], + ['IST', 'ISC'], + ['Claude', 'Clause'], + [' or later', '+'], + [' International', ''], + ['GNU', 'GPL'], + ['GUN', 'GPL'], + ['+', ''], + ['GNU GPL', 'GPL'], + ['GNU/GPL', 'GPL'], + ['GNU GLP', 'GPL'], + ['GNU General Public License', 'GPL'], + ['Gnu public license', 'GPL'], + ['GNU Public License', 'GPL'], + ['GNU GENERAL PUBLIC LICENSE', 'GPL'], + ['MTI', 'MIT'], + ['Mozilla Public License', 'MPL'], + ['WTH', 'WTF'], + ['-License', ''] +]; + +var TRANSPOSED = 0; +var CORRECT = 1; + +// Simple corrections to nearly valid identifiers. +var transforms = [ + // e.g. 'mit' + function(argument) { + return argument.toUpperCase(); + }, + // e.g. 'MIT ' + function(argument) { + return argument.trim(); + }, + // e.g. 'M.I.T.' + function(argument) { + return argument.replace(/\./g, ''); + }, + // e.g. 'Apache- 2.0' + function(argument) { + return argument.replace(/\s+/g, ''); + }, + // e.g. 'CC BY 4.0'' + function(argument) { + return argument.replace(/\s+/g, '-'); + }, + // e.g. 'LGPLv2.1' + function(argument) { + return argument.replace('v', '-'); + }, + // e.g. 'Apache 2.0' + function(argument) { + return argument.replace(/,?\s*(\d)/, '-$1'); + }, + // e.g. 'GPL 2' + function(argument) { + return argument.replace(/,?\s*(\d)/, '-$1.0'); + }, + // e.g. 'Apache Version 2.0' + function(argument) { + return argument.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/, '-$2'); + }, + // e.g. 'Apache Version 2' + function(argument) { + return argument.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/, '-$2.0'); + }, + // e.g. 'ZLIB' + function(argument) { + return argument[0].toUpperCase() + argument.slice(1); + }, + // e.g. 'MPL/2.0' + function(argument) { + return argument.replace('/', '-'); + }, + // e.g. 'Apache 2' + function(argument) { + return argument + .replace(/\s*V\s*(\d)/, '-$1') + .replace(/(\d)$/, '$1.0'); + }, + // e.g. 'GPL-2.0-' + function(argument) { + return argument.slice(0, argument.length - 1); + }, + // e.g. 'GPL2' + function(argument) { + return argument.replace(/(\d)$/, '-$1.0'); + }, + // e.g. 'BSD 3' + function(argument) { + return argument.replace(/(-| )?(\d)$/, '-$2-Clause'); + }, + // e.g. 'BSD clause 3' + function(argument) { + return argument.replace(/(-| )clause(-| )(\d)/, '-$3-Clause'); + }, + // e.g. 'BY-NC-4.0' + function(argument) { + return 'CC-' + argument; + }, + // e.g. 'BY-NC' + function(argument) { + return 'CC-' + argument + '-4.0'; + }, + // e.g. 'Attribution-NonCommercial' + function(argument) { + return argument + .replace('Attribution', 'BY') + .replace('NonCommercial', 'NC') + .replace('NoDerivatives', 'ND') + .replace(/ (\d)/, '-$1') + .replace(/ ?International/, ''); + }, + // e.g. 'Attribution-NonCommercial' + function(argument) { + return 'CC-' + + argument + .replace('Attribution', 'BY') + .replace('NonCommercial', 'NC') + .replace('NoDerivatives', 'ND') + .replace(/ (\d)/, '-$1') + .replace(/ ?International/, '') + + '-4.0'; + } +]; + +// If all else fails, guess that strings containing certain substrings +// meant to identify certain licenses. +var lastResorts = [ + ['UNLI', 'Unlicense'], + ['WTF', 'WTFPL'], + ['2 CLAUSE', 'BSD-2-Clause'], + ['2-CLAUSE', 'BSD-2-Clause'], + ['3 CLAUSE', 'BSD-3-Clause'], + ['3-CLAUSE', 'BSD-3-Clause'], + ['AFFERO', 'AGPL-3.0'], + ['AGPL', 'AGPL-3.0'], + ['APACHE', 'Apache-2.0'], + ['ARTISTIC', 'Artistic-2.0'], + ['Affero', 'AGPL-3.0'], + ['BEER', 'Beerware'], + ['BOOST', 'BSL-1.0'], + ['BSD', 'BSD-2-Clause'], + ['ECLIPSE', 'EPL-1.0'], + ['FUCK', 'WTFPL'], + ['GNU', 'GPL-3.0'], + ['LGPL', 'LGPL-3.0'], + ['GPL', 'GPL-3.0'], + ['MIT', 'MIT'], + ['MPL', 'MPL-2.0'], + ['X11', 'X11'], + ['ZLIB', 'Zlib'] +]; + +var SUBSTRING = 0; +var IDENTIFIER = 1; + +var validTransformation = function(identifier) { + for (var i = 0; i < transforms.length; i++) { + var transformed = transforms[i](identifier); + if (transformed !== identifier && valid(transformed)) { + return transformed; + } + } + return null; +}; + +var validLastResort = function(identifier) { + var upperCased = identifier.toUpperCase(); + for (var i = 0; i < lastResorts.length; i++) { + var lastResort = lastResorts[i]; + if (upperCased.indexOf(lastResort[SUBSTRING]) > -1) { + return lastResort[IDENTIFIER]; + } + } + return null; +}; + +var anyCorrection = function(identifier, check) { + for (var i = 0; i < transpositions.length; i++) { + var transposition = transpositions[i]; + var transposed = transposition[TRANSPOSED]; + if (identifier.indexOf(transposed) > -1) { + var corrected = identifier.replace( + transposed, + transposition[CORRECT] + ); + var checked = check(corrected); + if (checked !== null) { + return checked; + } + } + } + return null; +}; + +module.exports = function(identifier) { + identifier = identifier.replace(/\+$/, ''); + if (valid(identifier)) { + return identifier; + } + var transformed = validTransformation(identifier); + if (transformed !== null) { + return transformed; + } + transformed = anyCorrection(identifier, function(argument) { + if (valid(argument)) { + return argument; + } + return validTransformation(argument); + }); + if (transformed !== null) { + return transformed; + } + transformed = validLastResort(identifier); + if (transformed !== null) { + return transformed; + } + transformed = anyCorrection(identifier, validLastResort); + if (transformed !== null) { + return transformed; + } + return null; +}; + + +/***/ }), +/* 203 */ +/***/ (function(module) { + +module.exports = ["Glide","Abstyles","AFL-1.1","AFL-1.2","AFL-2.0","AFL-2.1","AFL-3.0","AMPAS","APL-1.0","Adobe-Glyph","APAFML","Adobe-2006","AGPL-1.0","Afmparse","Aladdin","ADSL","AMDPLPA","ANTLR-PD","Apache-1.0","Apache-1.1","Apache-2.0","AML","APSL-1.0","APSL-1.1","APSL-1.2","APSL-2.0","Artistic-1.0","Artistic-1.0-Perl","Artistic-1.0-cl8","Artistic-2.0","AAL","Bahyph","Barr","Beerware","BitTorrent-1.0","BitTorrent-1.1","BSL-1.0","Borceux","BSD-2-Clause","BSD-2-Clause-FreeBSD","BSD-2-Clause-NetBSD","BSD-3-Clause","BSD-3-Clause-Clear","BSD-4-Clause","BSD-Protection","BSD-Source-Code","BSD-3-Clause-Attribution","0BSD","BSD-4-Clause-UC","bzip2-1.0.5","bzip2-1.0.6","Caldera","CECILL-1.0","CECILL-1.1","CECILL-2.0","CECILL-2.1","CECILL-B","CECILL-C","ClArtistic","MIT-CMU","CNRI-Jython","CNRI-Python","CNRI-Python-GPL-Compatible","CPOL-1.02","CDDL-1.0","CDDL-1.1","CPAL-1.0","CPL-1.0","CATOSL-1.1","Condor-1.1","CC-BY-1.0","CC-BY-2.0","CC-BY-2.5","CC-BY-3.0","CC-BY-4.0","CC-BY-ND-1.0","CC-BY-ND-2.0","CC-BY-ND-2.5","CC-BY-ND-3.0","CC-BY-ND-4.0","CC-BY-NC-1.0","CC-BY-NC-2.0","CC-BY-NC-2.5","CC-BY-NC-3.0","CC-BY-NC-4.0","CC-BY-NC-ND-1.0","CC-BY-NC-ND-2.0","CC-BY-NC-ND-2.5","CC-BY-NC-ND-3.0","CC-BY-NC-ND-4.0","CC-BY-NC-SA-1.0","CC-BY-NC-SA-2.0","CC-BY-NC-SA-2.5","CC-BY-NC-SA-3.0","CC-BY-NC-SA-4.0","CC-BY-SA-1.0","CC-BY-SA-2.0","CC-BY-SA-2.5","CC-BY-SA-3.0","CC-BY-SA-4.0","CC0-1.0","Crossword","CrystalStacker","CUA-OPL-1.0","Cube","curl","D-FSL-1.0","diffmark","WTFPL","DOC","Dotseqn","DSDP","dvipdfm","EPL-1.0","ECL-1.0","ECL-2.0","eGenix","EFL-1.0","EFL-2.0","MIT-advertising","MIT-enna","Entessa","ErlPL-1.1","EUDatagrid","EUPL-1.0","EUPL-1.1","Eurosym","Fair","MIT-feh","Frameworx-1.0","FreeImage","FTL","FSFAP","FSFUL","FSFULLR","Giftware","GL2PS","Glulxe","AGPL-3.0","GFDL-1.1","GFDL-1.2","GFDL-1.3","GPL-1.0","GPL-2.0","GPL-3.0","LGPL-2.1","LGPL-3.0","LGPL-2.0","gnuplot","gSOAP-1.3b","HaskellReport","HPND","IBM-pibs","IPL-1.0","ICU","ImageMagick","iMatix","Imlib2","IJG","Info-ZIP","Intel-ACPI","Intel","Interbase-1.0","IPA","ISC","JasPer-2.0","JSON","LPPL-1.0","LPPL-1.1","LPPL-1.2","LPPL-1.3a","LPPL-1.3c","Latex2e","BSD-3-Clause-LBNL","Leptonica","LGPLLR","Libpng","libtiff","LAL-1.2","LAL-1.3","LiLiQ-P-1.1","LiLiQ-Rplus-1.1","LiLiQ-R-1.1","LPL-1.02","LPL-1.0","MakeIndex","MTLL","MS-PL","MS-RL","MirOS","MITNFA","MIT","Motosoto","MPL-1.0","MPL-1.1","MPL-2.0","MPL-2.0-no-copyleft-exception","mpich2","Multics","Mup","NASA-1.3","Naumen","NBPL-1.0","NetCDF","NGPL","NOSL","NPL-1.0","NPL-1.1","Newsletr","NLPL","Nokia","NPOSL-3.0","NLOD-1.0","Noweb","NRL","NTP","Nunit","OCLC-2.0","ODbL-1.0","PDDL-1.0","OCCT-PL","OGTSL","OLDAP-2.2.2","OLDAP-1.1","OLDAP-1.2","OLDAP-1.3","OLDAP-1.4","OLDAP-2.0","OLDAP-2.0.1","OLDAP-2.1","OLDAP-2.2","OLDAP-2.2.1","OLDAP-2.3","OLDAP-2.4","OLDAP-2.5","OLDAP-2.6","OLDAP-2.7","OLDAP-2.8","OML","OPL-1.0","OSL-1.0","OSL-1.1","OSL-2.0","OSL-2.1","OSL-3.0","OpenSSL","OSET-PL-2.1","PHP-3.0","PHP-3.01","Plexus","PostgreSQL","psfrag","psutils","Python-2.0","QPL-1.0","Qhull","Rdisc","RPSL-1.0","RPL-1.1","RPL-1.5","RHeCos-1.1","RSCPL","RSA-MD","Ruby","SAX-PD","Saxpath","SCEA","SWL","SMPPL","Sendmail","SGI-B-1.0","SGI-B-1.1","SGI-B-2.0","OFL-1.0","OFL-1.1","SimPL-2.0","Sleepycat","SNIA","Spencer-86","Spencer-94","Spencer-99","SMLNJ","SugarCRM-1.1.3","SISSL","SISSL-1.2","SPL-1.0","Watcom-1.0","TCL","Unlicense","TMate","TORQUE-1.1","TOSL","Unicode-TOU","UPL-1.0","NCSA","Vim","VOSTROM","VSL-1.0","W3C-19980720","W3C","Wsuipa","Xnet","X11","Xerox","XFree86-1.1","xinetd","xpp","XSkat","YPL-1.0","YPL-1.1","Zed","Zend-2.0","Zimbra-1.3","Zimbra-1.4","Zlib","zlib-acknowledgement","ZPL-1.1","ZPL-2.0","ZPL-2.1","BSD-3-Clause-No-Nuclear-License","BSD-3-Clause-No-Nuclear-Warranty","BSD-3-Clause-No-Nuclear-License-2014","eCos-2.0","GPL-2.0-with-autoconf-exception","GPL-2.0-with-bison-exception","GPL-2.0-with-classpath-exception","GPL-2.0-with-font-exception","GPL-2.0-with-GCC-exception","GPL-3.0-with-autoconf-exception","GPL-3.0-with-GCC-exception","StandardML-NJ","WXwindows"]; + +/***/ }), +/* 204 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var url = __webpack_require__(102) +var gitHosts = __webpack_require__(124) +var GitHost = module.exports = __webpack_require__(205) + +var protocolToRepresentationMap = { + 'git+ssh': 'sshurl', + 'git+https': 'https', + 'ssh': 'sshurl', + 'git': 'git' +} + +function protocolToRepresentation (protocol) { + if (protocol.substr(-1) === ':') protocol = protocol.slice(0, -1) + return protocolToRepresentationMap[protocol] || protocol +} + +var authProtocols = { + 'git:': true, + 'https:': true, + 'git+https:': true, + 'http:': true, + 'git+http:': true +} + +var cache = {} + +module.exports.fromUrl = function (giturl, opts) { + var key = giturl + JSON.stringify(opts || {}) + + if (!(key in cache)) { + cache[key] = fromUrl(giturl, opts) + } + + return cache[key] +} + +function fromUrl (giturl, opts) { + if (giturl == null || giturl === '') return + var url = fixupUnqualifiedGist( + isGitHubShorthand(giturl) ? 'github:' + giturl : giturl + ) + var parsed = parseGitUrl(url) + var shortcutMatch = url.match(new RegExp('^([^:]+):(?:(?:[^@:]+(?:[^@]+)?@)?([^/]*))[/](.+?)(?:[.]git)?($|#)')) + var matches = Object.keys(gitHosts).map(function (gitHostName) { + try { + var gitHostInfo = gitHosts[gitHostName] + var auth = null + if (parsed.auth && authProtocols[parsed.protocol]) { + auth = decodeURIComponent(parsed.auth) + } + var committish = parsed.hash ? decodeURIComponent(parsed.hash.substr(1)) : null + var user = null + var project = null + var defaultRepresentation = null + if (shortcutMatch && shortcutMatch[1] === gitHostName) { + user = shortcutMatch[2] && decodeURIComponent(shortcutMatch[2]) + project = decodeURIComponent(shortcutMatch[3]) + defaultRepresentation = 'shortcut' + } else { + if (parsed.host !== gitHostInfo.domain) return + if (!gitHostInfo.protocols_re.test(parsed.protocol)) return + if (!parsed.path) return + var pathmatch = gitHostInfo.pathmatch + var matched = parsed.path.match(pathmatch) + if (!matched) return + if (matched[1] != null) user = decodeURIComponent(matched[1].replace(/^:/, '')) + if (matched[2] != null) project = decodeURIComponent(matched[2]) + defaultRepresentation = protocolToRepresentation(parsed.protocol) + } + return new GitHost(gitHostName, user, auth, project, committish, defaultRepresentation, opts) + } catch (ex) { + if (!(ex instanceof URIError)) throw ex + } + }).filter(function (gitHostInfo) { return gitHostInfo }) + if (matches.length !== 1) return + return matches[0] +} + +function isGitHubShorthand (arg) { + // Note: This does not fully test the git ref format. + // See https://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html + // + // The only way to do this properly would be to shell out to + // git-check-ref-format, and as this is a fast sync function, + // we don't want to do that. Just let git fail if it turns + // out that the commit-ish is invalid. + // GH usernames cannot start with . or - + return /^[^:@%/\s.-][^:@%/\s]*[/][^:@\s/%]+(?:#.*)?$/.test(arg) +} + +function fixupUnqualifiedGist (giturl) { + // necessary for round-tripping gists + var parsed = url.parse(giturl) + if (parsed.protocol === 'gist:' && parsed.host && !parsed.path) { + return parsed.protocol + '/' + parsed.host + } else { + return giturl + } +} + +function parseGitUrl (giturl) { + if (typeof giturl !== 'string') giturl = '' + giturl + var matched = giturl.match(/^([^@]+)@([^:/]+):[/]?((?:[^/]+[/])?[^/]+?)(?:[.]git)?(#.*)?$/) + if (!matched) return url.parse(giturl) + return { + protocol: 'git+ssh:', + slashes: true, + auth: matched[1], + host: matched[2], + port: null, + hostname: matched[2], + hash: matched[4], + search: null, + query: null, + pathname: '/' + matched[3], + path: '/' + matched[3], + href: 'git+ssh://' + matched[1] + '@' + matched[2] + + '/' + matched[3] + (matched[4] || '') + } +} + + +/***/ }), +/* 205 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var gitHosts = __webpack_require__(124) +var extend = Object.assign || __webpack_require__(14)._extend + +var GitHost = module.exports = function (type, user, auth, project, committish, defaultRepresentation, opts) { + var gitHostInfo = this + gitHostInfo.type = type + Object.keys(gitHosts[type]).forEach(function (key) { + gitHostInfo[key] = gitHosts[type][key] + }) + gitHostInfo.user = user + gitHostInfo.auth = auth + gitHostInfo.project = project + gitHostInfo.committish = committish + gitHostInfo.default = defaultRepresentation + gitHostInfo.opts = opts || {} +} +GitHost.prototype = {} + +GitHost.prototype.hash = function () { + return this.committish ? '#' + this.committish : '' +} + +GitHost.prototype._fill = function (template, opts) { + if (!template) return + var vars = extend({}, opts) + opts = extend(extend({}, this.opts), opts) + var self = this + Object.keys(this).forEach(function (key) { + if (self[key] != null && vars[key] == null) vars[key] = self[key] + }) + var rawAuth = vars.auth + var rawComittish = vars.committish + Object.keys(vars).forEach(function (key) { + vars[key] = encodeURIComponent(vars[key]) + }) + vars['auth@'] = rawAuth ? rawAuth + '@' : '' + if (opts.noCommittish) { + vars['#committish'] = '' + vars['/tree/committish'] = '' + vars['/comittish'] = '' + vars.comittish = '' + } else { + vars['#committish'] = rawComittish ? '#' + rawComittish : '' + vars['/tree/committish'] = vars.committish + ? '/' + vars.treepath + '/' + vars.committish + : '' + vars['/committish'] = vars.committish ? '/' + vars.committish : '' + vars.committish = vars.committish || 'master' + } + var res = template + Object.keys(vars).forEach(function (key) { + res = res.replace(new RegExp('[{]' + key + '[}]', 'g'), vars[key]) + }) + if (opts.noGitPlus) { + return res.replace(/^git[+]/, '') + } else { + return res + } +} + +GitHost.prototype.ssh = function (opts) { + return this._fill(this.sshtemplate, opts) +} + +GitHost.prototype.sshurl = function (opts) { + return this._fill(this.sshurltemplate, opts) +} + +GitHost.prototype.browse = function (opts) { + return this._fill(this.browsetemplate, opts) +} + +GitHost.prototype.docs = function (opts) { + return this._fill(this.docstemplate, opts) +} + +GitHost.prototype.bugs = function (opts) { + return this._fill(this.bugstemplate, opts) +} + +GitHost.prototype.https = function (opts) { + return this._fill(this.httpstemplate, opts) +} + +GitHost.prototype.git = function (opts) { + return this._fill(this.gittemplate, opts) +} + +GitHost.prototype.shortcut = function (opts) { + return this._fill(this.shortcuttemplate, opts) +} + +GitHost.prototype.path = function (opts) { + return this._fill(this.pathtemplate, opts) +} + +GitHost.prototype.tarball = function (opts) { + return this._fill(this.tarballtemplate, opts) +} + +GitHost.prototype.file = function (P, opts) { + return this._fill(this.filetemplate, extend({ + path: P.replace(/^[/]+/g, '') + }, opts)) +} + +GitHost.prototype.getDefaultRepresentation = function () { + return this.default +} + +GitHost.prototype.toString = function (opts) { + return (this[this.default] || this.sshurl).call(this, opts) +} + + +/***/ }), +/* 206 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var builtinModules = __webpack_require__(207); + +module.exports = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + return builtinModules.indexOf(str) !== -1; +}; + + +/***/ }), +/* 207 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var blacklist = [ + 'freelist', + 'sys' +]; + +module.exports = Object.keys(process.binding('natives')).filter(function (el) { + return !/^_|^internal|\//.test(el) && blacklist.indexOf(el) === -1; +}).sort(); + + +/***/ }), +/* 208 */ +/***/ (function(module, exports) { + +module.exports = extractDescription + +// Extracts description from contents of a readme file in markdown format +function extractDescription (d) { + if (!d) return; + if (d === "ERROR: No README data found!") return; + // the first block of text before the first heading + // that isn't the first line heading + d = d.trim().split('\n') + for (var s = 0; d[s] && d[s].trim().match(/^(#|$)/); s ++); + var l = d.length + for (var e = s + 1; e < l && d[e].trim(); e ++); + return d.slice(s, e).join(' ').trim() +} + + +/***/ }), +/* 209 */ +/***/ (function(module) { + +module.exports = {"topLevel":{"dependancies":"dependencies","dependecies":"dependencies","depdenencies":"dependencies","devEependencies":"devDependencies","depends":"dependencies","dev-dependencies":"devDependencies","devDependences":"devDependencies","devDepenencies":"devDependencies","devdependencies":"devDependencies","repostitory":"repository","repo":"repository","prefereGlobal":"preferGlobal","hompage":"homepage","hampage":"homepage","autohr":"author","autor":"author","contributers":"contributors","publicationConfig":"publishConfig","script":"scripts"},"bugs":{"web":"url","name":"url"},"script":{"server":"start","tests":"test"}}; + +/***/ }), +/* 210 */ +/***/ (function(module, exports, __webpack_require__) { + +var util = __webpack_require__(14) +var messages = __webpack_require__(211) + +module.exports = function() { + var args = Array.prototype.slice.call(arguments, 0) + var warningName = args.shift() + if (warningName == "typo") { + return makeTypoWarning.apply(null,args) + } + else { + var msgTemplate = messages[warningName] ? messages[warningName] : warningName + ": '%s'" + args.unshift(msgTemplate) + return util.format.apply(null, args) + } +} + +function makeTypoWarning (providedName, probableName, field) { + if (field) { + providedName = field + "['" + providedName + "']" + probableName = field + "['" + probableName + "']" + } + return util.format(messages.typo, providedName, probableName) +} + + +/***/ }), +/* 211 */ +/***/ (function(module) { + +module.exports = {"repositories":"'repositories' (plural) Not supported. Please pick one as the 'repository' field","missingRepository":"No repository field.","brokenGitUrl":"Probably broken git url: %s","nonObjectScripts":"scripts must be an object","nonStringScript":"script values must be string commands","nonArrayFiles":"Invalid 'files' member","invalidFilename":"Invalid filename in 'files' list: %s","nonArrayBundleDependencies":"Invalid 'bundleDependencies' list. Must be array of package names","nonStringBundleDependency":"Invalid bundleDependencies member: %s","nonDependencyBundleDependency":"Non-dependency in bundleDependencies: %s","nonObjectDependencies":"%s field must be an object","nonStringDependency":"Invalid dependency: %s %s","deprecatedArrayDependencies":"specifying %s as array is deprecated","deprecatedModules":"modules field is deprecated","nonArrayKeywords":"keywords should be an array of strings","nonStringKeyword":"keywords should be an array of strings","conflictingName":"%s is also the name of a node core module.","nonStringDescription":"'description' field should be a string","missingDescription":"No description","missingReadme":"No README data","missingLicense":"No license field.","nonEmailUrlBugsString":"Bug string field must be url, email, or {email,url}","nonUrlBugsUrlField":"bugs.url field must be a string url. Deleted.","nonEmailBugsEmailField":"bugs.email field must be a string email. Deleted.","emptyNormalizedBugs":"Normalized value of bugs field is an empty object. Deleted.","nonUrlHomepage":"homepage field must be a string url. Deleted.","invalidLicense":"license should be a valid SPDX license expression","typo":"%s should probably be %s."}; + +/***/ }), +/* 212 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const path = __webpack_require__(5); +const writeJsonFile = __webpack_require__(213); +const sortKeys = __webpack_require__(125); + +const opts = {detectIndent: true}; + +const dependencyKeys = new Set([ + 'dependencies', + 'devDependencies', + 'optionalDependencies', + 'peerDependencies' +]); + +function normalize(pkg) { + const ret = {}; + + for (const key of Object.keys(pkg)) { + if (!dependencyKeys.has(key)) { + ret[key] = pkg[key]; + } else if (Object.keys(pkg[key]).length !== 0) { + ret[key] = sortKeys(pkg[key]); + } + } + + return ret; +} + +module.exports = (fp, data) => { + if (typeof fp !== 'string') { + data = fp; + fp = '.'; + } + + fp = path.basename(fp) === 'package.json' ? fp : path.join(fp, 'package.json'); + + data = normalize(data); + + return writeJsonFile(fp, data, opts); +}; + +module.exports.sync = (fp, data) => { + if (typeof fp !== 'string') { + data = fp; + fp = '.'; + } + + fp = path.basename(fp) === 'package.json' ? fp : path.join(fp, 'package.json'); + + data = normalize(data); + + writeJsonFile.sync(fp, data, opts); +}; + + +/***/ }), +/* 213 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const path = __webpack_require__(5); +const fs = __webpack_require__(61); +const writeFileAtomic = __webpack_require__(214); +const sortKeys = __webpack_require__(125); +const makeDir = __webpack_require__(126); +const pify = __webpack_require__(219); +const detectIndent = __webpack_require__(220); + +const init = (fn, fp, data, opts) => { + if (!fp) { + throw new TypeError('Expected a filepath'); + } + + if (data === undefined) { + throw new TypeError('Expected data to stringify'); + } + + opts = Object.assign({ + indent: '\t', + sortKeys: false + }, opts); + + if (opts.sortKeys) { + data = sortKeys(data, { + deep: true, + compare: typeof opts.sortKeys === 'function' && opts.sortKeys + }); + } + + return fn(fp, data, opts); +}; + +const readFile = fp => pify(fs.readFile)(fp, 'utf8').catch(() => {}); + +const main = (fp, data, opts) => { + return (opts.detectIndent ? readFile(fp) : Promise.resolve()) + .then(str => { + const indent = str ? detectIndent(str).indent : opts.indent; + const json = JSON.stringify(data, opts.replacer, indent); + + return pify(writeFileAtomic)(fp, `${json}\n`, {mode: opts.mode}); + }); +}; + +const mainSync = (fp, data, opts) => { + let indent = opts.indent; + + if (opts.detectIndent) { + try { + const file = fs.readFileSync(fp, 'utf8'); + indent = detectIndent(file).indent; + } catch (err) { + if (err.code !== 'ENOENT') { + throw err; + } + } + } + + const json = JSON.stringify(data, opts.replacer, indent); + + return writeFileAtomic.sync(fp, `${json}\n`, {mode: opts.mode}); +}; + +module.exports = (fp, data, opts) => { + return makeDir(path.dirname(fp), {fs}) + .then(() => init(main, fp, data, opts)); +}; + +module.exports.sync = (fp, data, opts) => { + makeDir.sync(path.dirname(fp), {fs}); + init(mainSync, fp, data, opts); +}; + + +/***/ }), +/* 214 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = writeFile +module.exports.sync = writeFileSync +module.exports._getTmpname = getTmpname // for testing +module.exports._cleanupOnExit = cleanupOnExit + +var fs = __webpack_require__(61) +var MurmurHash3 = __webpack_require__(215) +var onExit = __webpack_require__(103) +var path = __webpack_require__(5) +var activeFiles = {} + +var invocations = 0 +function getTmpname (filename) { + return filename + '.' + + MurmurHash3(__filename) + .hash(String(process.pid)) + .hash(String(++invocations)) + .result() +} + +function cleanupOnExit (tmpfile) { + return function () { + try { + fs.unlinkSync(typeof tmpfile === 'function' ? tmpfile() : tmpfile) + } catch (_) {} + } +} + +function writeFile (filename, data, options, callback) { + if (options instanceof Function) { + callback = options + options = null + } + if (!options) options = {} + + var Promise = options.Promise || global.Promise + var truename + var fd + var tmpfile + var removeOnExit = cleanupOnExit(() => tmpfile) + var absoluteName = path.resolve(filename) + + new Promise(function serializeSameFile (resolve) { + // make a queue if it doesn't already exist + if (!activeFiles[absoluteName]) activeFiles[absoluteName] = [] + + activeFiles[absoluteName].push(resolve) // add this job to the queue + if (activeFiles[absoluteName].length === 1) resolve() // kick off the first one + }).then(function getRealPath () { + return new Promise(function (resolve) { + fs.realpath(filename, function (_, realname) { + truename = realname || filename + tmpfile = getTmpname(truename) + resolve() + }) + }) + }).then(function stat () { + return new Promise(function stat (resolve) { + if (options.mode && options.chown) resolve() + else { + // Either mode or chown is not explicitly set + // Default behavior is to copy it from original file + fs.stat(truename, function (err, stats) { + if (err || !stats) resolve() + else { + options = Object.assign({}, options) + + if (!options.mode) { + options.mode = stats.mode + } + if (!options.chown && process.getuid) { + options.chown = { uid: stats.uid, gid: stats.gid } + } + resolve() + } + }) + } + }) + }).then(function thenWriteFile () { + return new Promise(function (resolve, reject) { + fs.open(tmpfile, 'w', options.mode, function (err, _fd) { + fd = _fd + if (err) reject(err) + else resolve() + }) + }) + }).then(function write () { + return new Promise(function (resolve, reject) { + if (Buffer.isBuffer(data)) { + fs.write(fd, data, 0, data.length, 0, function (err) { + if (err) reject(err) + else resolve() + }) + } else if (data != null) { + fs.write(fd, String(data), 0, String(options.encoding || 'utf8'), function (err) { + if (err) reject(err) + else resolve() + }) + } else resolve() + }) + }).then(function syncAndClose () { + if (options.fsync !== false) { + return new Promise(function (resolve, reject) { + fs.fsync(fd, function (err) { + if (err) reject(err) + else fs.close(fd, resolve) + }) + }) + } + }).then(function chown () { + if (options.chown) { + return new Promise(function (resolve, reject) { + fs.chown(tmpfile, options.chown.uid, options.chown.gid, function (err) { + if (err) reject(err) + else resolve() + }) + }) + } + }).then(function chmod () { + if (options.mode) { + return new Promise(function (resolve, reject) { + fs.chmod(tmpfile, options.mode, function (err) { + if (err) reject(err) + else resolve() + }) + }) + } + }).then(function rename () { + return new Promise(function (resolve, reject) { + fs.rename(tmpfile, truename, function (err) { + if (err) reject(err) + else resolve() + }) + }) + }).then(function success () { + removeOnExit() + callback() + }).catch(function fail (err) { + removeOnExit() + fs.unlink(tmpfile, function () { + callback(err) + }) + }).then(function checkQueue () { + activeFiles[absoluteName].shift() // remove the element added by serializeSameFile + if (activeFiles[absoluteName].length > 0) { + activeFiles[absoluteName][0]() // start next job if one is pending + } else delete activeFiles[absoluteName] + }) +} + +function writeFileSync (filename, data, options) { + if (!options) options = {} + try { + filename = fs.realpathSync(filename) + } catch (ex) { + // it's ok, it'll happen on a not yet existing file + } + var tmpfile = getTmpname(filename) + + try { + if (!options.mode || !options.chown) { + // Either mode or chown is not explicitly set + // Default behavior is to copy it from original file + try { + var stats = fs.statSync(filename) + options = Object.assign({}, options) + if (!options.mode) { + options.mode = stats.mode + } + if (!options.chown && process.getuid) { + options.chown = { uid: stats.uid, gid: stats.gid } + } + } catch (ex) { + // ignore stat errors + } + } + + var removeOnExit = onExit(cleanupOnExit(tmpfile)) + var fd = fs.openSync(tmpfile, 'w', options.mode) + if (Buffer.isBuffer(data)) { + fs.writeSync(fd, data, 0, data.length, 0) + } else if (data != null) { + fs.writeSync(fd, String(data), 0, String(options.encoding || 'utf8')) + } + if (options.fsync !== false) { + fs.fsyncSync(fd) + } + fs.closeSync(fd) + if (options.chown) fs.chownSync(tmpfile, options.chown.uid, options.chown.gid) + if (options.mode) fs.chmodSync(tmpfile, options.mode) + fs.renameSync(tmpfile, filename) + removeOnExit() + } catch (err) { + removeOnExit() + try { fs.unlinkSync(tmpfile) } catch (e) {} + throw err + } +} + + +/***/ }), +/* 215 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * @preserve + * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013) + * + * @author Jens Taylor + * @see http://github.com/homebrewing/brauhaus-diff + * @author Gary Court + * @see http://github.com/garycourt/murmurhash-js + * @author Austin Appleby + * @see http://sites.google.com/site/murmurhash/ + */ +(function(){ + var cache; + + // Call this function without `new` to use the cached object (good for + // single-threaded environments), or with `new` to create a new object. + // + // @param {string} key A UTF-16 or ASCII string + // @param {number} seed An optional positive integer + // @return {object} A MurmurHash3 object for incremental hashing + function MurmurHash3(key, seed) { + var m = this instanceof MurmurHash3 ? this : cache; + m.reset(seed) + if (typeof key === 'string' && key.length > 0) { + m.hash(key); + } + + if (m !== this) { + return m; + } + }; + + // Incrementally add a string to this hash + // + // @param {string} key A UTF-16 or ASCII string + // @return {object} this + MurmurHash3.prototype.hash = function(key) { + var h1, k1, i, top, len; + + len = key.length; + this.len += len; + + k1 = this.k1; + i = 0; + switch (this.rem) { + case 0: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) : 0; + case 1: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 8 : 0; + case 2: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 16 : 0; + case 3: + k1 ^= len > i ? (key.charCodeAt(i) & 0xff) << 24 : 0; + k1 ^= len > i ? (key.charCodeAt(i++) & 0xff00) >> 8 : 0; + } + + this.rem = (len + this.rem) & 3; // & 3 is same as % 4 + len -= this.rem; + if (len > 0) { + h1 = this.h1; + while (1) { + k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; + + h1 ^= k1; + h1 = (h1 << 13) | (h1 >>> 19); + h1 = (h1 * 5 + 0xe6546b64) & 0xffffffff; + + if (i >= len) { + break; + } + + k1 = ((key.charCodeAt(i++) & 0xffff)) ^ + ((key.charCodeAt(i++) & 0xffff) << 8) ^ + ((key.charCodeAt(i++) & 0xffff) << 16); + top = key.charCodeAt(i++); + k1 ^= ((top & 0xff) << 24) ^ + ((top & 0xff00) >> 8); + } + + k1 = 0; + switch (this.rem) { + case 3: k1 ^= (key.charCodeAt(i + 2) & 0xffff) << 16; + case 2: k1 ^= (key.charCodeAt(i + 1) & 0xffff) << 8; + case 1: k1 ^= (key.charCodeAt(i) & 0xffff); + } + + this.h1 = h1; + } + + this.k1 = k1; + return this; + }; + + // Get the result of this hash + // + // @return {number} The 32-bit hash + MurmurHash3.prototype.result = function() { + var k1, h1; + + k1 = this.k1; + h1 = this.h1; + + if (k1 > 0) { + k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; + k1 = (k1 << 15) | (k1 >>> 17); + k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; + h1 ^= k1; + } + + h1 ^= this.len; + + h1 ^= h1 >>> 16; + h1 = (h1 * 0xca6b + (h1 & 0xffff) * 0x85eb0000) & 0xffffffff; + h1 ^= h1 >>> 13; + h1 = (h1 * 0xae35 + (h1 & 0xffff) * 0xc2b20000) & 0xffffffff; + h1 ^= h1 >>> 16; + + return h1 >>> 0; + }; + + // Reset the hash object for reuse + // + // @param {number} seed An optional positive integer + MurmurHash3.prototype.reset = function(seed) { + this.h1 = typeof seed === 'number' ? seed : 0; + this.rem = this.k1 = this.len = 0; + return this; + }; + + // A cached object to use. This can be safely used if you're in a single- + // threaded environment, otherwise you need to create new hashes to use. + cache = new MurmurHash3(); + + if (true) { + module.exports = MurmurHash3; + } else {} +}()); + + +/***/ }), +/* 216 */ +/***/ (function(module, exports) { + +// This is not the set of all possible signals. +// +// It IS, however, the set of all signals that trigger +// an exit on either Linux or BSD systems. Linux is a +// superset of the signal names supported on BSD, and +// the unknown signals just fail to register, so we can +// catch that easily enough. +// +// Don't bother with SIGKILL. It's uncatchable, which +// means that we can't fire any callbacks anyway. +// +// If a user does happen to register a handler on a non- +// fatal signal like SIGWINCH or something, and then +// exit, it'll end up firing `process.emit('exit')`, so +// the handler will be fired anyway. +// +// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised +// artificially, inherently leave the process in a +// state from which it is not safe to try and enter JS +// listeners. +module.exports = [ + 'SIGABRT', + 'SIGALRM', + 'SIGHUP', + 'SIGINT', + 'SIGTERM' +] + +if (process.platform !== 'win32') { + module.exports.push( + 'SIGVTALRM', + 'SIGXCPU', + 'SIGXFSZ', + 'SIGUSR2', + 'SIGTRAP', + 'SIGSYS', + 'SIGQUIT', + 'SIGIOT' + // should detect profiler and enable/disable accordingly. + // see #21 + // 'SIGPROF' + ) +} + +if (process.platform === 'linux') { + module.exports.push( + 'SIGIO', + 'SIGPOLL', + 'SIGPWR', + 'SIGSTKFLT', + 'SIGUNUSED' + ) +} + + +/***/ }), +/* 217 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var toString = Object.prototype.toString; + +module.exports = function (x) { + var prototype; + return toString.call(x) === '[object Object]' && (prototype = Object.getPrototypeOf(x), prototype === null || prototype === Object.getPrototypeOf({})); +}; + + +/***/ }), +/* 218 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const processFn = (fn, opts) => function () { + const P = opts.promiseModule; + const args = new Array(arguments.length); + + for (let i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + + return new P((resolve, reject) => { + if (opts.errorFirst) { + args.push(function (err, result) { + if (opts.multiArgs) { + const results = new Array(arguments.length - 1); + + for (let i = 1; i < arguments.length; i++) { + results[i - 1] = arguments[i]; + } + + if (err) { + results.unshift(err); + reject(results); + } else { + resolve(results); + } + } else if (err) { + reject(err); + } else { + resolve(result); + } + }); + } else { + args.push(function (result) { + if (opts.multiArgs) { + const results = new Array(arguments.length - 1); + + for (let i = 0; i < arguments.length; i++) { + results[i] = arguments[i]; + } + + resolve(results); + } else { + resolve(result); + } + }); + } + + fn.apply(this, args); + }); +}; + +module.exports = (obj, opts) => { + opts = Object.assign({ + exclude: [/.+(Sync|Stream)$/], + errorFirst: true, + promiseModule: Promise + }, opts); + + const filter = key => { + const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key); + return opts.include ? opts.include.some(match) : !opts.exclude.some(match); + }; + + let ret; + if (typeof obj === 'function') { + ret = function () { + if (opts.excludeMain) { + return obj.apply(this, arguments); + } + + return processFn(obj, opts).apply(this, arguments); + }; + } else { + ret = Object.create(Object.getPrototypeOf(obj)); + } + + for (const key in obj) { // eslint-disable-line guard-for-in + const x = obj[key]; + ret[key] = typeof x === 'function' && filter(key) ? processFn(x, opts) : x; + } + + return ret; +}; + + +/***/ }), +/* 219 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const processFn = (fn, opts) => function () { + const P = opts.promiseModule; + const args = new Array(arguments.length); + + for (let i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + + return new P((resolve, reject) => { + if (opts.errorFirst) { + args.push(function (err, result) { + if (opts.multiArgs) { + const results = new Array(arguments.length - 1); + + for (let i = 1; i < arguments.length; i++) { + results[i - 1] = arguments[i]; + } + + if (err) { + results.unshift(err); + reject(results); + } else { + resolve(results); + } + } else if (err) { + reject(err); + } else { + resolve(result); + } + }); + } else { + args.push(function (result) { + if (opts.multiArgs) { + const results = new Array(arguments.length - 1); + + for (let i = 0; i < arguments.length; i++) { + results[i] = arguments[i]; + } + + resolve(results); + } else { + resolve(result); + } + }); + } + + fn.apply(this, args); + }); +}; + +module.exports = (obj, opts) => { + opts = Object.assign({ + exclude: [/.+(Sync|Stream)$/], + errorFirst: true, + promiseModule: Promise + }, opts); + + const filter = key => { + const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key); + return opts.include ? opts.include.some(match) : !opts.exclude.some(match); + }; + + let ret; + if (typeof obj === 'function') { + ret = function () { + if (opts.excludeMain) { + return obj.apply(this, arguments); + } + + return processFn(obj, opts).apply(this, arguments); + }; + } else { + ret = Object.create(Object.getPrototypeOf(obj)); + } + + for (const key in obj) { // eslint-disable-line guard-for-in + const x = obj[key]; + ret[key] = typeof x === 'function' && filter(key) ? processFn(x, opts) : x; + } + + return ret; +}; + + +/***/ }), +/* 220 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +// detect either spaces or tabs but not both to properly handle tabs +// for indentation and spaces for alignment +const INDENT_RE = /^(?:( )+|\t+)/; + +function getMostUsed(indents) { + let result = 0; + let maxUsed = 0; + let maxWeight = 0; + + for (const entry of indents) { + // TODO: use destructuring when targeting Node.js 6 + const key = entry[0]; + const val = entry[1]; + + const u = val[0]; + const w = val[1]; + + if (u > maxUsed || (u === maxUsed && w > maxWeight)) { + maxUsed = u; + maxWeight = w; + result = Number(key); + } + } + + return result; +} + +module.exports = str => { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + // used to see if tabs or spaces are the most used + let tabs = 0; + let spaces = 0; + + // remember the size of previous line's indentation + let prev = 0; + + // remember how many indents/unindents as occurred for a given size + // and how much lines follow a given indentation + // + // indents = { + // 3: [1, 0], + // 4: [1, 5], + // 5: [1, 0], + // 12: [1, 0], + // } + const indents = new Map(); + + // pointer to the array of last used indent + let current; + + // whether the last action was an indent (opposed to an unindent) + let isIndent; + + for (const line of str.split(/\n/g)) { + if (!line) { + // ignore empty lines + continue; + } + + let indent; + const matches = line.match(INDENT_RE); + + if (matches) { + indent = matches[0].length; + + if (matches[1]) { + spaces++; + } else { + tabs++; + } + } else { + indent = 0; + } + + const diff = indent - prev; + prev = indent; + + if (diff) { + // an indent or unindent has been detected + + isIndent = diff > 0; + + current = indents.get(isIndent ? diff : -diff); + + if (current) { + current[0]++; + } else { + current = [1, 0]; + indents.set(diff, current); + } + } else if (current) { + // if the last action was an indent, increment the weight + current[1] += Number(isIndent); + } + } + + const amount = getMostUsed(indents); + + let type; + let indent; + if (!amount) { + type = null; + indent = ''; + } else if (spaces >= tabs) { + type = 'space'; + indent = ' '.repeat(amount); + } else { + type = 'tab'; + indent = '\t'.repeat(amount); + } + + return { + amount, + type, + indent + }; +}; + + +/***/ }), +/* 221 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.runScriptInPackage = exports.installInDir = undefined; + +/** + * Install all dependencies in the given directory + */ +let installInDir = exports.installInDir = (() => { + var _ref = _asyncToGenerator(function* (directory, extraArgs = []) { + const options = ['install', '--non-interactive', ...extraArgs]; + // We pass the mutex flag to ensure only one instance of yarn runs at any + // given time (e.g. to avoid conflicts). + yield (0, _child_process.spawn)('yarn', options, { + cwd: directory + }); + }); + + return function installInDir(_x) { + return _ref.apply(this, arguments); + }; +})(); +/** + * Run script in the given directory + */ + + +let runScriptInPackage = exports.runScriptInPackage = (() => { + var _ref2 = _asyncToGenerator(function* (script, args, pkg) { + const execOpts = { + cwd: pkg.path + }; + yield (0, _child_process.spawn)('yarn', ['run', script, ...args], execOpts); + }); + + return function runScriptInPackage(_x2, _x3, _x4) { + return _ref2.apply(this, arguments); + }; +})(); +/** + * Run script in the given directory + */ + + +exports.runScriptInPackageStreaming = runScriptInPackageStreaming; + +var _child_process = __webpack_require__(222); + +function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + + +function runScriptInPackageStreaming(script, args, pkg) { + const execOpts = { + cwd: pkg.path + }; + return (0, _child_process.spawnStreaming)('yarn', ['run', script, ...args], execOpts, { + prefix: pkg.name + }); +} + +/***/ }), +/* 222 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + + +exports.spawn = spawn; +exports.spawnStreaming = spawnStreaming; + +var _chalk = __webpack_require__(26); + +var _chalk2 = _interopRequireDefault(_chalk); + +var _execa = __webpack_require__(223); + +var _execa2 = _interopRequireDefault(_execa); + +var _logSymbols = __webpack_require__(128); + +var _logSymbols2 = _interopRequireDefault(_logSymbols); + +var _strongLogTransformer = __webpack_require__(250); + +var _strongLogTransformer2 = _interopRequireDefault(_strongLogTransformer); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function generateColors() { + const colorWheel = [_chalk2.default.cyan, _chalk2.default.magenta, _chalk2.default.blue, _chalk2.default.yellow, _chalk2.default.green]; + const count = colorWheel.length; + let children = 0; + return () => colorWheel[children++ % count]; +} +function spawn(command, args, opts) { + return (0, _execa2.default)(command, args, _extends({}, opts, { + stdio: 'inherit' + })); +} +const nextColor = generateColors(); +function spawnStreaming(command, args, opts, { prefix }) { + const spawned = (0, _execa2.default)(command, args, _extends({}, opts, { + stdio: ['ignore', 'pipe', 'pipe'] + })); + const color = nextColor(); + const prefixedStdout = (0, _strongLogTransformer2.default)({ tag: `${color.bold(prefix)}:` }); + const prefixedStderr = (0, _strongLogTransformer2.default)({ + mergeMultiline: true, + tag: `${_logSymbols2.default.error} ${color.bold(prefix)}:` + }); + spawned.stdout.pipe(prefixedStdout).pipe(process.stdout); + spawned.stderr.pipe(prefixedStderr).pipe(process.stderr); + return spawned; +} + +/***/ }), +/* 223 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const path = __webpack_require__(5); +const childProcess = __webpack_require__(127); +const crossSpawn = __webpack_require__(224); +const stripEof = __webpack_require__(239); +const npmRunPath = __webpack_require__(240); +const isStream = __webpack_require__(242); +const _getStream = __webpack_require__(243); +const pFinally = __webpack_require__(247); +const onExit = __webpack_require__(103); +const errname = __webpack_require__(248); +const stdio = __webpack_require__(249); + +const TEN_MEGABYTES = 1000 * 1000 * 10; + +function handleArgs(cmd, args, opts) { + let parsed; + + opts = Object.assign({ + extendEnv: true, + env: {} + }, opts); + + if (opts.extendEnv) { + opts.env = Object.assign({}, process.env, opts.env); + } + + if (opts.__winShell === true) { + delete opts.__winShell; + parsed = { + command: cmd, + args, + options: opts, + file: cmd, + original: { + cmd, + args + } + }; + } else { + parsed = crossSpawn._parse(cmd, args, opts); + } + + opts = Object.assign({ + maxBuffer: TEN_MEGABYTES, + buffer: true, + stripEof: true, + preferLocal: true, + localDir: parsed.options.cwd || process.cwd(), + encoding: 'utf8', + reject: true, + cleanup: true + }, parsed.options); + + opts.stdio = stdio(opts); + + if (opts.preferLocal) { + opts.env = npmRunPath.env(Object.assign({}, opts, {cwd: opts.localDir})); + } + + if (opts.detached) { + // #115 + opts.cleanup = false; + } + + if (process.platform === 'win32' && path.basename(parsed.command) === 'cmd.exe') { + // #116 + parsed.args.unshift('/q'); + } + + return { + cmd: parsed.command, + args: parsed.args, + opts, + parsed + }; +} + +function handleInput(spawned, input) { + if (input === null || input === undefined) { + return; + } + + if (isStream(input)) { + input.pipe(spawned.stdin); + } else { + spawned.stdin.end(input); + } +} + +function handleOutput(opts, val) { + if (val && opts.stripEof) { + val = stripEof(val); + } + + return val; +} + +function handleShell(fn, cmd, opts) { + let file = '/bin/sh'; + let args = ['-c', cmd]; + + opts = Object.assign({}, opts); + + if (process.platform === 'win32') { + opts.__winShell = true; + file = process.env.comspec || 'cmd.exe'; + args = ['/s', '/c', `"${cmd}"`]; + opts.windowsVerbatimArguments = true; + } + + if (opts.shell) { + file = opts.shell; + delete opts.shell; + } + + return fn(file, args, opts); +} + +function getStream(process, stream, {encoding, buffer, maxBuffer}) { + if (!process[stream]) { + return null; + } + + let ret; + + if (!buffer) { + // TODO: Use `ret = util.promisify(stream.finished)(process[stream]);` when targeting Node.js 10 + ret = new Promise((resolve, reject) => { + process[stream] + .once('end', resolve) + .once('error', reject); + }); + } else if (encoding) { + ret = _getStream(process[stream], { + encoding, + maxBuffer + }); + } else { + ret = _getStream.buffer(process[stream], {maxBuffer}); + } + + return ret.catch(err => { + err.stream = stream; + err.message = `${stream} ${err.message}`; + throw err; + }); +} + +function makeError(result, options) { + const {stdout, stderr} = result; + + let err = result.error; + const {code, signal} = result; + + const {parsed, joinedCmd} = options; + const timedOut = options.timedOut || false; + + if (!err) { + let output = ''; + + if (Array.isArray(parsed.opts.stdio)) { + if (parsed.opts.stdio[2] !== 'inherit') { + output += output.length > 0 ? stderr : `\n${stderr}`; + } + + if (parsed.opts.stdio[1] !== 'inherit') { + output += `\n${stdout}`; + } + } else if (parsed.opts.stdio !== 'inherit') { + output = `\n${stderr}${stdout}`; + } + + err = new Error(`Command failed: ${joinedCmd}${output}`); + err.code = code < 0 ? errname(code) : code; + } + + err.stdout = stdout; + err.stderr = stderr; + err.failed = true; + err.signal = signal || null; + err.cmd = joinedCmd; + err.timedOut = timedOut; + + return err; +} + +function joinCmd(cmd, args) { + let joinedCmd = cmd; + + if (Array.isArray(args) && args.length > 0) { + joinedCmd += ' ' + args.join(' '); + } + + return joinedCmd; +} + +module.exports = (cmd, args, opts) => { + const parsed = handleArgs(cmd, args, opts); + const {encoding, buffer, maxBuffer} = parsed.opts; + const joinedCmd = joinCmd(cmd, args); + + let spawned; + try { + spawned = childProcess.spawn(parsed.cmd, parsed.args, parsed.opts); + } catch (err) { + return Promise.reject(err); + } + + let removeExitHandler; + if (parsed.opts.cleanup) { + removeExitHandler = onExit(() => { + spawned.kill(); + }); + } + + let timeoutId = null; + let timedOut = false; + + const cleanup = () => { + if (timeoutId) { + clearTimeout(timeoutId); + timeoutId = null; + } + + if (removeExitHandler) { + removeExitHandler(); + } + }; + + if (parsed.opts.timeout > 0) { + timeoutId = setTimeout(() => { + timeoutId = null; + timedOut = true; + spawned.kill(parsed.opts.killSignal); + }, parsed.opts.timeout); + } + + const processDone = new Promise(resolve => { + spawned.on('exit', (code, signal) => { + cleanup(); + resolve({code, signal}); + }); + + spawned.on('error', err => { + cleanup(); + resolve({error: err}); + }); + + if (spawned.stdin) { + spawned.stdin.on('error', err => { + cleanup(); + resolve({error: err}); + }); + } + }); + + function destroy() { + if (spawned.stdout) { + spawned.stdout.destroy(); + } + + if (spawned.stderr) { + spawned.stderr.destroy(); + } + } + + const handlePromise = () => pFinally(Promise.all([ + processDone, + getStream(spawned, 'stdout', {encoding, buffer, maxBuffer}), + getStream(spawned, 'stderr', {encoding, buffer, maxBuffer}) + ]).then(arr => { + const result = arr[0]; + result.stdout = arr[1]; + result.stderr = arr[2]; + + if (result.error || result.code !== 0 || result.signal !== null) { + const err = makeError(result, { + joinedCmd, + parsed, + timedOut + }); + + // TODO: missing some timeout logic for killed + // https://github.com/nodejs/node/blob/master/lib/child_process.js#L203 + // err.killed = spawned.killed || killed; + err.killed = err.killed || spawned.killed; + + if (!parsed.opts.reject) { + return err; + } + + throw err; + } + + return { + stdout: handleOutput(parsed.opts, result.stdout), + stderr: handleOutput(parsed.opts, result.stderr), + code: 0, + failed: false, + killed: false, + signal: null, + cmd: joinedCmd, + timedOut: false + }; + }), destroy); + + crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed); + + handleInput(spawned, parsed.opts.input); + + spawned.then = (onfulfilled, onrejected) => handlePromise().then(onfulfilled, onrejected); + spawned.catch = onrejected => handlePromise().catch(onrejected); + + return spawned; +}; + +// TODO: set `stderr: 'ignore'` when that option is implemented +module.exports.stdout = (...args) => module.exports(...args).then(x => x.stdout); + +// TODO: set `stdout: 'ignore'` when that option is implemented +module.exports.stderr = (...args) => module.exports(...args).then(x => x.stderr); + +module.exports.shell = (cmd, opts) => handleShell(module.exports, cmd, opts); + +module.exports.sync = (cmd, args, opts) => { + const parsed = handleArgs(cmd, args, opts); + const joinedCmd = joinCmd(cmd, args); + + if (isStream(parsed.opts.input)) { + throw new TypeError('The `input` option cannot be a stream in sync mode'); + } + + const result = childProcess.spawnSync(parsed.cmd, parsed.args, parsed.opts); + result.code = result.status; + + if (result.error || result.status !== 0 || result.signal !== null) { + const err = makeError(result, { + joinedCmd, + parsed + }); + + if (!parsed.opts.reject) { + return err; + } + + throw err; + } + + return { + stdout: handleOutput(parsed.opts, result.stdout), + stderr: handleOutput(parsed.opts, result.stderr), + code: 0, + failed: false, + signal: null, + cmd: joinedCmd, + timedOut: false + }; +}; + +module.exports.shellSync = (cmd, opts) => handleShell(module.exports.sync, cmd, opts); + + +/***/ }), +/* 224 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const cp = __webpack_require__(127); +const parse = __webpack_require__(225); +const enoent = __webpack_require__(238); + +function spawn(command, args, options) { + // Parse the arguments + const parsed = parse(command, args, options); + + // Spawn the child process + const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); + + // Hook into child process "exit" event to emit an error if the command + // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + enoent.hookChildProcess(spawned, parsed); + + return spawned; +} + +function spawnSync(command, args, options) { + // Parse the arguments + const parsed = parse(command, args, options); + + // Spawn the child process + const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); + + // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 + result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); + + return result; +} + +module.exports = spawn; +module.exports.spawn = spawn; +module.exports.sync = spawnSync; + +module.exports._parse = parse; +module.exports._enoent = enoent; + + +/***/ }), +/* 225 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const path = __webpack_require__(5); +const niceTry = __webpack_require__(226); +const resolveCommand = __webpack_require__(227); +const escape = __webpack_require__(233); +const readShebang = __webpack_require__(234); +const semver = __webpack_require__(237); + +const isWin = process.platform === 'win32'; +const isExecutableRegExp = /\.(?:com|exe)$/i; +const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; + +// `options.shell` is supported in Node ^4.8.0, ^5.7.0 and >= 6.0.0 +const supportsShellOption = niceTry(() => semver.satisfies(process.version, '^4.8.0 || ^5.7.0 || >= 6.0.0', true)) || false; + +function detectShebang(parsed) { + parsed.file = resolveCommand(parsed); + + const shebang = parsed.file && readShebang(parsed.file); + + if (shebang) { + parsed.args.unshift(parsed.file); + parsed.command = shebang; + + return resolveCommand(parsed); + } + + return parsed.file; +} + +function parseNonShell(parsed) { + if (!isWin) { + return parsed; + } + + // Detect & add support for shebangs + const commandFile = detectShebang(parsed); + + // We don't need a shell if the command filename is an executable + const needsShell = !isExecutableRegExp.test(commandFile); + + // If a shell is required, use cmd.exe and take care of escaping everything correctly + // Note that `forceShell` is an hidden option used only in tests + if (parsed.options.forceShell || needsShell) { + // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` + // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument + // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, + // we need to double escape them + const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); + + // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) + // This is necessary otherwise it will always fail with ENOENT in those cases + parsed.command = path.normalize(parsed.command); + + // Escape command & arguments + parsed.command = escape.command(parsed.command); + parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); + + const shellCommand = [parsed.command].concat(parsed.args).join(' '); + + parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; + parsed.command = process.env.comspec || 'cmd.exe'; + parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped + } + + return parsed; +} + +function parseShell(parsed) { + // If node supports the shell option, there's no need to mimic its behavior + if (supportsShellOption) { + return parsed; + } + + // Mimic node shell option + // See https://github.com/nodejs/node/blob/b9f6a2dc059a1062776133f3d4fd848c4da7d150/lib/child_process.js#L335 + const shellCommand = [parsed.command].concat(parsed.args).join(' '); + + if (isWin) { + parsed.command = typeof parsed.options.shell === 'string' ? parsed.options.shell : process.env.comspec || 'cmd.exe'; + parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; + parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped + } else { + if (typeof parsed.options.shell === 'string') { + parsed.command = parsed.options.shell; + } else if (process.platform === 'android') { + parsed.command = '/system/bin/sh'; + } else { + parsed.command = '/bin/sh'; + } + + parsed.args = ['-c', shellCommand]; + } + + return parsed; +} + +function parse(command, args, options) { + // Normalize arguments, similar to nodejs + if (args && !Array.isArray(args)) { + options = args; + args = null; + } + + args = args ? args.slice(0) : []; // Clone array to avoid changing the original + options = Object.assign({}, options); // Clone object to avoid changing the original + + // Build our parsed object + const parsed = { + command, + args, + options, + file: undefined, + original: { + command, + args, + }, + }; + + // Delegate further parsing to shell or non-shell + return options.shell ? parseShell(parsed) : parseNonShell(parsed); +} + +module.exports = parse; + + +/***/ }), +/* 226 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Tries to execute a function and discards any error that occurs. + * @param {Function} fn - Function that might or might not throw an error. + * @returns {?*} Return-value of the function when no error occurred. + */ +module.exports = function(fn) { + + try { return fn() } + catch (e) {} + +} + +/***/ }), +/* 227 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const path = __webpack_require__(5); +const which = __webpack_require__(228); +const pathKey = __webpack_require__(232)(); + +function resolveCommandAttempt(parsed, withoutPathExt) { + const cwd = process.cwd(); + const hasCustomCwd = parsed.options.cwd != null; + + // If a custom `cwd` was specified, we need to change the process cwd + // because `which` will do stat calls but does not support a custom cwd + if (hasCustomCwd) { + try { + process.chdir(parsed.options.cwd); + } catch (err) { + /* Empty */ + } + } + + let resolved; + + try { + resolved = which.sync(parsed.command, { + path: (parsed.options.env || process.env)[pathKey], + pathExt: withoutPathExt ? path.delimiter : undefined, + }); + } catch (e) { + /* Empty */ + } finally { + process.chdir(cwd); + } + + // If we successfully resolved, ensure that an absolute path is returned + // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it + if (resolved) { + resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); + } + + return resolved; +} + +function resolveCommand(parsed) { + return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); +} + +module.exports = resolveCommand; + + +/***/ }), +/* 228 */ +/***/ (function(module, exports, __webpack_require__) { + +module.exports = which +which.sync = whichSync + +var isWindows = process.platform === 'win32' || + process.env.OSTYPE === 'cygwin' || + process.env.OSTYPE === 'msys' + +var path = __webpack_require__(5) +var COLON = isWindows ? ';' : ':' +var isexe = __webpack_require__(229) + +function getNotFoundError (cmd) { + var er = new Error('not found: ' + cmd) + er.code = 'ENOENT' + + return er +} + +function getPathInfo (cmd, opt) { + var colon = opt.colon || COLON + var pathEnv = opt.path || process.env.PATH || '' + var pathExt = [''] + + pathEnv = pathEnv.split(colon) + + var pathExtExe = '' + if (isWindows) { + pathEnv.unshift(process.cwd()) + pathExtExe = (opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM') + pathExt = pathExtExe.split(colon) + + + // Always test the cmd itself first. isexe will check to make sure + // it's found in the pathExt set. + if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') + pathExt.unshift('') + } + + // If it has a slash, then we don't bother searching the pathenv. + // just check the file itself, and that's it. + if (cmd.match(/\//) || isWindows && cmd.match(/\\/)) + pathEnv = [''] + + return { + env: pathEnv, + ext: pathExt, + extExe: pathExtExe + } +} + +function which (cmd, opt, cb) { + if (typeof opt === 'function') { + cb = opt + opt = {} + } + + var info = getPathInfo(cmd, opt) + var pathEnv = info.env + var pathExt = info.ext + var pathExtExe = info.extExe + var found = [] + + ;(function F (i, l) { + if (i === l) { + if (opt.all && found.length) + return cb(null, found) + else + return cb(getNotFoundError(cmd)) + } + + var pathPart = pathEnv[i] + if (pathPart.charAt(0) === '"' && pathPart.slice(-1) === '"') + pathPart = pathPart.slice(1, -1) + + var p = path.join(pathPart, cmd) + if (!pathPart && (/^\.[\\\/]/).test(cmd)) { + p = cmd.slice(0, 2) + p + } + ;(function E (ii, ll) { + if (ii === ll) return F(i + 1, l) + var ext = pathExt[ii] + isexe(p + ext, { pathExt: pathExtExe }, function (er, is) { + if (!er && is) { + if (opt.all) + found.push(p + ext) + else + return cb(null, p + ext) + } + return E(ii + 1, ll) + }) + })(0, pathExt.length) + })(0, pathEnv.length) +} + +function whichSync (cmd, opt) { + opt = opt || {} + + var info = getPathInfo(cmd, opt) + var pathEnv = info.env + var pathExt = info.ext + var pathExtExe = info.extExe + var found = [] + + for (var i = 0, l = pathEnv.length; i < l; i ++) { + var pathPart = pathEnv[i] + if (pathPart.charAt(0) === '"' && pathPart.slice(-1) === '"') + pathPart = pathPart.slice(1, -1) + + var p = path.join(pathPart, cmd) + if (!pathPart && /^\.[\\\/]/.test(cmd)) { + p = cmd.slice(0, 2) + p + } + for (var j = 0, ll = pathExt.length; j < ll; j ++) { + var cur = p + pathExt[j] + var is + try { + is = isexe.sync(cur, { pathExt: pathExtExe }) + if (is) { + if (opt.all) + found.push(cur) + else + return cur + } + } catch (ex) {} + } + } + + if (opt.all && found.length) + return found + + if (opt.nothrow) + return null + + throw getNotFoundError(cmd) +} + + +/***/ }), +/* 229 */ +/***/ (function(module, exports, __webpack_require__) { + +var fs = __webpack_require__(13) +var core +if (process.platform === 'win32' || global.TESTING_WINDOWS) { + core = __webpack_require__(230) +} else { + core = __webpack_require__(231) +} + +module.exports = isexe +isexe.sync = sync + +function isexe (path, options, cb) { + if (typeof options === 'function') { + cb = options + options = {} + } + + if (!cb) { + if (typeof Promise !== 'function') { + throw new TypeError('callback not provided') + } + + return new Promise(function (resolve, reject) { + isexe(path, options || {}, function (er, is) { + if (er) { + reject(er) + } else { + resolve(is) + } + }) + }) + } + + core(path, options || {}, function (er, is) { + // ignore EACCES because that just means we aren't allowed to run it + if (er) { + if (er.code === 'EACCES' || options && options.ignoreErrors) { + er = null + is = false + } + } + cb(er, is) + }) +} + +function sync (path, options) { + // my kingdom for a filtered catch + try { + return core.sync(path, options || {}) + } catch (er) { + if (options && options.ignoreErrors || er.code === 'EACCES') { + return false + } else { + throw er + } + } +} + + +/***/ }), +/* 230 */ +/***/ (function(module, exports, __webpack_require__) { + +module.exports = isexe +isexe.sync = sync + +var fs = __webpack_require__(13) + +function checkPathExt (path, options) { + var pathext = options.pathExt !== undefined ? + options.pathExt : process.env.PATHEXT + + if (!pathext) { + return true + } + + pathext = pathext.split(';') + if (pathext.indexOf('') !== -1) { + return true + } + for (var i = 0; i < pathext.length; i++) { + var p = pathext[i].toLowerCase() + if (p && path.substr(-p.length).toLowerCase() === p) { + return true + } + } + return false +} + +function checkStat (stat, path, options) { + if (!stat.isSymbolicLink() && !stat.isFile()) { + return false + } + return checkPathExt(path, options) +} + +function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, path, options)) + }) +} + +function sync (path, options) { + return checkStat(fs.statSync(path), path, options) +} + + +/***/ }), +/* 231 */ +/***/ (function(module, exports, __webpack_require__) { + +module.exports = isexe +isexe.sync = sync + +var fs = __webpack_require__(13) + +function isexe (path, options, cb) { + fs.stat(path, function (er, stat) { + cb(er, er ? false : checkStat(stat, options)) + }) +} + +function sync (path, options) { + return checkStat(fs.statSync(path), options) +} + +function checkStat (stat, options) { + return stat.isFile() && checkMode(stat, options) +} + +function checkMode (stat, options) { + var mod = stat.mode + var uid = stat.uid + var gid = stat.gid + + var myUid = options.uid !== undefined ? + options.uid : process.getuid && process.getuid() + var myGid = options.gid !== undefined ? + options.gid : process.getgid && process.getgid() + + var u = parseInt('100', 8) + var g = parseInt('010', 8) + var o = parseInt('001', 8) + var ug = u | g + + var ret = (mod & o) || + (mod & g) && gid === myGid || + (mod & u) && uid === myUid || + (mod & ug) && myUid === 0 + + return ret +} + + +/***/ }), +/* 232 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = opts => { + opts = opts || {}; + + const env = opts.env || process.env; + const platform = opts.platform || process.platform; + + if (platform !== 'win32') { + return 'PATH'; + } + + return Object.keys(env).find(x => x.toUpperCase() === 'PATH') || 'Path'; +}; + + +/***/ }), +/* 233 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +// See http://www.robvanderwoude.com/escapechars.php +const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; + +function escapeCommand(arg) { + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + return arg; +} + +function escapeArgument(arg, doubleEscapeMetaChars) { + // Convert to string + arg = `${arg}`; + + // Algorithm below is based on https://qntm.org/cmd + + // Sequence of backslashes followed by a double quote: + // double up all the backslashes and escape the double quote + arg = arg.replace(/(\\*)"/g, '$1$1\\"'); + + // Sequence of backslashes followed by the end of the string + // (which will become a double quote later): + // double up all the backslashes + arg = arg.replace(/(\\*)$/, '$1$1'); + + // All other backslashes occur literally + + // Quote the whole thing: + arg = `"${arg}"`; + + // Escape meta chars + arg = arg.replace(metaCharsRegExp, '^$1'); + + // Double escape meta chars if necessary + if (doubleEscapeMetaChars) { + arg = arg.replace(metaCharsRegExp, '^$1'); + } + + return arg; +} + +module.exports.command = escapeCommand; +module.exports.argument = escapeArgument; + + +/***/ }), +/* 234 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const fs = __webpack_require__(13); +const shebangCommand = __webpack_require__(235); + +function readShebang(command) { + // Read the first 150 bytes from the file + const size = 150; + let buffer; + + if (Buffer.alloc) { + // Node.js v4.5+ / v5.10+ + buffer = Buffer.alloc(size); + } else { + // Old Node.js API + buffer = new Buffer(size); + buffer.fill(0); // zero-fill + } + + let fd; + + try { + fd = fs.openSync(command, 'r'); + fs.readSync(fd, buffer, 0, size, 0); + fs.closeSync(fd); + } catch (e) { /* Empty */ } + + // Attempt to extract shebang (null is returned if not a shebang) + return shebangCommand(buffer.toString()); +} + +module.exports = readShebang; + + +/***/ }), +/* 235 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var shebangRegex = __webpack_require__(236); + +module.exports = function (str) { + var match = str.match(shebangRegex); + + if (!match) { + return null; + } + + var arr = match[0].replace(/#! ?/, '').split(' '); + var bin = arr[0].split('/').pop(); + var arg = arr[1]; + + return (bin === 'env' ? + arg : + bin + (arg ? ' ' + arg : '') + ); +}; + + +/***/ }), +/* 236 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = /^#!.*/; + + +/***/ }), +/* 237 */ +/***/ (function(module, exports) { + +exports = module.exports = SemVer; + +// The debug function is excluded entirely from the minified version. +/* nomin */ var debug; +/* nomin */ if (typeof process === 'object' && + /* nomin */ process.env && + /* nomin */ process.env.NODE_DEBUG && + /* nomin */ /\bsemver\b/i.test(process.env.NODE_DEBUG)) + /* nomin */ debug = function() { + /* nomin */ var args = Array.prototype.slice.call(arguments, 0); + /* nomin */ args.unshift('SEMVER'); + /* nomin */ console.log.apply(console, args); + /* nomin */ }; +/* nomin */ else + /* nomin */ debug = function() {}; + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0'; + +var MAX_LENGTH = 256; +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; + +// Max safe segment length for coercion. +var MAX_SAFE_COMPONENT_LENGTH = 16; + +// The actual regexps go on exports.re +var re = exports.re = []; +var src = exports.src = []; +var R = 0; + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +var NUMERICIDENTIFIER = R++; +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; +var NUMERICIDENTIFIERLOOSE = R++; +src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; + + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +var NONNUMERICIDENTIFIER = R++; +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; + + +// ## Main Version +// Three dot-separated numeric identifiers. + +var MAINVERSION = R++; +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')'; + +var MAINVERSIONLOOSE = R++; +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +var PRERELEASEIDENTIFIER = R++; +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + + '|' + src[NONNUMERICIDENTIFIER] + ')'; + +var PRERELEASEIDENTIFIERLOOSE = R++; +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + + '|' + src[NONNUMERICIDENTIFIER] + ')'; + + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +var PRERELEASE = R++; +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; + +var PRERELEASELOOSE = R++; +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +var BUILDIDENTIFIER = R++; +src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +var BUILD = R++; +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; + + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +var FULL = R++; +var FULLPLAIN = 'v?' + src[MAINVERSION] + + src[PRERELEASE] + '?' + + src[BUILD] + '?'; + +src[FULL] = '^' + FULLPLAIN + '$'; + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + + src[PRERELEASELOOSE] + '?' + + src[BUILD] + '?'; + +var LOOSE = R++; +src[LOOSE] = '^' + LOOSEPLAIN + '$'; + +var GTLT = R++; +src[GTLT] = '((?:<|>)?=?)'; + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +var XRANGEIDENTIFIERLOOSE = R++; +src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; +var XRANGEIDENTIFIER = R++; +src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; + +var XRANGEPLAIN = R++; +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:' + src[PRERELEASE] + ')?' + + src[BUILD] + '?' + + ')?)?'; + +var XRANGEPLAINLOOSE = R++; +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[PRERELEASELOOSE] + ')?' + + src[BUILD] + '?' + + ')?)?'; + +var XRANGE = R++; +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; +var XRANGELOOSE = R++; +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +var COERCE = R++; +src[COERCE] = '(?:^|[^\\d])' + + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:$|[^\\d])'; + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +var LONETILDE = R++; +src[LONETILDE] = '(?:~>?)'; + +var TILDETRIM = R++; +src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; +re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); +var tildeTrimReplace = '$1~'; + +var TILDE = R++; +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; +var TILDELOOSE = R++; +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +var LONECARET = R++; +src[LONECARET] = '(?:\\^)'; + +var CARETTRIM = R++; +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); +var caretTrimReplace = '$1^'; + +var CARET = R++; +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; +var CARETLOOSE = R++; +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +var COMPARATORLOOSE = R++; +src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; +var COMPARATOR = R++; +src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; + + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +var COMPARATORTRIM = R++; +src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; + +// this one has to use the /g flag +re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); +var comparatorTrimReplace = '$1$2$3'; + + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +var HYPHENRANGE = R++; +src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAIN] + ')' + + '\\s*$'; + +var HYPHENRANGELOOSE = R++; +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s*$'; + +// Star ranges basically just allow anything at all. +var STAR = R++; +src[STAR] = '(<|>)?=?\\s*\\*'; + +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]); + if (!re[i]) + re[i] = new RegExp(src[i]); +} + +exports.parse = parse; +function parse(version, loose) { + if (version instanceof SemVer) + return version; + + if (typeof version !== 'string') + return null; + + if (version.length > MAX_LENGTH) + return null; + + var r = loose ? re[LOOSE] : re[FULL]; + if (!r.test(version)) + return null; + + try { + return new SemVer(version, loose); + } catch (er) { + return null; + } +} + +exports.valid = valid; +function valid(version, loose) { + var v = parse(version, loose); + return v ? v.version : null; +} + + +exports.clean = clean; +function clean(version, loose) { + var s = parse(version.trim().replace(/^[=v]+/, ''), loose); + return s ? s.version : null; +} + +exports.SemVer = SemVer; + +function SemVer(version, loose) { + if (version instanceof SemVer) { + if (version.loose === loose) + return version; + else + version = version.version; + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version); + } + + if (version.length > MAX_LENGTH) + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + + if (!(this instanceof SemVer)) + return new SemVer(version, loose); + + debug('SemVer', version, loose); + this.loose = loose; + var m = version.trim().match(loose ? re[LOOSE] : re[FULL]); + + if (!m) + throw new TypeError('Invalid Version: ' + version); + + this.raw = version; + + // these are actually numbers + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) + throw new TypeError('Invalid major version') + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) + throw new TypeError('Invalid minor version') + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) + throw new TypeError('Invalid patch version') + + // numberify any prerelease numeric ids + if (!m[4]) + this.prerelease = []; + else + this.prerelease = m[4].split('.').map(function(id) { + if (/^[0-9]+$/.test(id)) { + var num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) + return num; + } + return id; + }); + + this.build = m[5] ? m[5].split('.') : []; + this.format(); +} + +SemVer.prototype.format = function() { + this.version = this.major + '.' + this.minor + '.' + this.patch; + if (this.prerelease.length) + this.version += '-' + this.prerelease.join('.'); + return this.version; +}; + +SemVer.prototype.toString = function() { + return this.version; +}; + +SemVer.prototype.compare = function(other) { + debug('SemVer.compare', this.version, this.loose, other); + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + return this.compareMain(other) || this.comparePre(other); +}; + +SemVer.prototype.compareMain = function(other) { + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch); +}; + +SemVer.prototype.comparePre = function(other) { + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) + return -1; + else if (!this.prerelease.length && other.prerelease.length) + return 1; + else if (!this.prerelease.length && !other.prerelease.length) + return 0; + + var i = 0; + do { + var a = this.prerelease[i]; + var b = other.prerelease[i]; + debug('prerelease compare', i, a, b); + if (a === undefined && b === undefined) + return 0; + else if (b === undefined) + return 1; + else if (a === undefined) + return -1; + else if (a === b) + continue; + else + return compareIdentifiers(a, b); + } while (++i); +}; + +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function(release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break; + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break; + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) + this.major++; + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) + this.minor++; + this.patch = 0; + this.prerelease = []; + break; + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) + this.patch++; + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) + this.prerelease = [0]; + else { + var i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + if (i === -1) // didn't increment anything + this.prerelease.push(0); + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) + this.prerelease = [identifier, 0]; + } else + this.prerelease = [identifier, 0]; + } + break; + + default: + throw new Error('invalid increment argument: ' + release); + } + this.format(); + this.raw = this.version; + return this; +}; + +exports.inc = inc; +function inc(version, release, loose, identifier) { + if (typeof(loose) === 'string') { + identifier = loose; + loose = undefined; + } + + try { + return new SemVer(version, loose).inc(release, identifier).version; + } catch (er) { + return null; + } +} + +exports.diff = diff; +function diff(version1, version2) { + if (eq(version1, version2)) { + return null; + } else { + var v1 = parse(version1); + var v2 = parse(version2); + if (v1.prerelease.length || v2.prerelease.length) { + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return 'pre'+key; + } + } + } + return 'prerelease'; + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return key; + } + } + } + } +} + +exports.compareIdentifiers = compareIdentifiers; + +var numeric = /^[0-9]+$/; +function compareIdentifiers(a, b) { + var anum = numeric.test(a); + var bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return (anum && !bnum) ? -1 : + (bnum && !anum) ? 1 : + a < b ? -1 : + a > b ? 1 : + 0; +} + +exports.rcompareIdentifiers = rcompareIdentifiers; +function rcompareIdentifiers(a, b) { + return compareIdentifiers(b, a); +} + +exports.major = major; +function major(a, loose) { + return new SemVer(a, loose).major; +} + +exports.minor = minor; +function minor(a, loose) { + return new SemVer(a, loose).minor; +} + +exports.patch = patch; +function patch(a, loose) { + return new SemVer(a, loose).patch; +} + +exports.compare = compare; +function compare(a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)); +} + +exports.compareLoose = compareLoose; +function compareLoose(a, b) { + return compare(a, b, true); +} + +exports.rcompare = rcompare; +function rcompare(a, b, loose) { + return compare(b, a, loose); +} + +exports.sort = sort; +function sort(list, loose) { + return list.sort(function(a, b) { + return exports.compare(a, b, loose); + }); +} + +exports.rsort = rsort; +function rsort(list, loose) { + return list.sort(function(a, b) { + return exports.rcompare(a, b, loose); + }); +} + +exports.gt = gt; +function gt(a, b, loose) { + return compare(a, b, loose) > 0; +} + +exports.lt = lt; +function lt(a, b, loose) { + return compare(a, b, loose) < 0; +} + +exports.eq = eq; +function eq(a, b, loose) { + return compare(a, b, loose) === 0; +} + +exports.neq = neq; +function neq(a, b, loose) { + return compare(a, b, loose) !== 0; +} + +exports.gte = gte; +function gte(a, b, loose) { + return compare(a, b, loose) >= 0; +} + +exports.lte = lte; +function lte(a, b, loose) { + return compare(a, b, loose) <= 0; +} + +exports.cmp = cmp; +function cmp(a, op, b, loose) { + var ret; + switch (op) { + case '===': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + ret = a === b; + break; + case '!==': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + ret = a !== b; + break; + case '': case '=': case '==': ret = eq(a, b, loose); break; + case '!=': ret = neq(a, b, loose); break; + case '>': ret = gt(a, b, loose); break; + case '>=': ret = gte(a, b, loose); break; + case '<': ret = lt(a, b, loose); break; + case '<=': ret = lte(a, b, loose); break; + default: throw new TypeError('Invalid operator: ' + op); + } + return ret; +} + +exports.Comparator = Comparator; +function Comparator(comp, loose) { + if (comp instanceof Comparator) { + if (comp.loose === loose) + return comp; + else + comp = comp.value; + } + + if (!(this instanceof Comparator)) + return new Comparator(comp, loose); + + debug('comparator', comp, loose); + this.loose = loose; + this.parse(comp); + + if (this.semver === ANY) + this.value = ''; + else + this.value = this.operator + this.semver.version; + + debug('comp', this); +} + +var ANY = {}; +Comparator.prototype.parse = function(comp) { + var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var m = comp.match(r); + + if (!m) + throw new TypeError('Invalid comparator: ' + comp); + + this.operator = m[1]; + if (this.operator === '=') + this.operator = ''; + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) + this.semver = ANY; + else + this.semver = new SemVer(m[2], this.loose); +}; + +Comparator.prototype.toString = function() { + return this.value; +}; + +Comparator.prototype.test = function(version) { + debug('Comparator.test', version, this.loose); + + if (this.semver === ANY) + return true; + + if (typeof version === 'string') + version = new SemVer(version, this.loose); + + return cmp(version, this.operator, this.semver, this.loose); +}; + +Comparator.prototype.intersects = function(comp, loose) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required'); + } + + var rangeTmp; + + if (this.operator === '') { + rangeTmp = new Range(comp.value, loose); + return satisfies(this.value, rangeTmp, loose); + } else if (comp.operator === '') { + rangeTmp = new Range(this.value, loose); + return satisfies(comp.semver, rangeTmp, loose); + } + + var sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>'); + var sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<'); + var sameSemVer = this.semver.version === comp.semver.version; + var differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<='); + var oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, loose) && + ((this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<')); + var oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, loose) && + ((this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>')); + + return sameDirectionIncreasing || sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || oppositeDirectionsGreaterThan; +}; + + +exports.Range = Range; +function Range(range, loose) { + if (range instanceof Range) { + if (range.loose === loose) { + return range; + } else { + return new Range(range.raw, loose); + } + } + + if (range instanceof Comparator) { + return new Range(range.value, loose); + } + + if (!(this instanceof Range)) + return new Range(range, loose); + + this.loose = loose; + + // First, split based on boolean or || + this.raw = range; + this.set = range.split(/\s*\|\|\s*/).map(function(range) { + return this.parseRange(range.trim()); + }, this).filter(function(c) { + // throw out any that are not relevant for whatever reason + return c.length; + }); + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range); + } + + this.format(); +} + +Range.prototype.format = function() { + this.range = this.set.map(function(comps) { + return comps.join(' ').trim(); + }).join('||').trim(); + return this.range; +}; + +Range.prototype.toString = function() { + return this.range; +}; + +Range.prototype.parseRange = function(range) { + var loose = this.loose; + range = range.trim(); + debug('range', range, loose); + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; + range = range.replace(hr, hyphenReplace); + debug('hyphen replace', range); + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); + debug('comparator trim', range, re[COMPARATORTRIM]); + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[TILDETRIM], tildeTrimReplace); + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[CARETTRIM], caretTrimReplace); + + // normalize spaces + range = range.split(/\s+/).join(' '); + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var set = range.split(' ').map(function(comp) { + return parseComparator(comp, loose); + }).join(' ').split(/\s+/); + if (this.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function(comp) { + return !!comp.match(compRe); + }); + } + set = set.map(function(comp) { + return new Comparator(comp, loose); + }); + + return set; +}; + +Range.prototype.intersects = function(range, loose) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required'); + } + + return this.set.some(function(thisComparators) { + return thisComparators.every(function(thisComparator) { + return range.set.some(function(rangeComparators) { + return rangeComparators.every(function(rangeComparator) { + return thisComparator.intersects(rangeComparator, loose); + }); + }); + }); + }); +}; + +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators; +function toComparators(range, loose) { + return new Range(range, loose).set.map(function(comp) { + return comp.map(function(c) { + return c.value; + }).join(' ').trim().split(' '); + }); +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator(comp, loose) { + debug('comp', comp); + comp = replaceCarets(comp, loose); + debug('caret', comp); + comp = replaceTildes(comp, loose); + debug('tildes', comp); + comp = replaceXRanges(comp, loose); + debug('xrange', comp); + comp = replaceStars(comp, loose); + debug('stars', comp); + return comp; +} + +function isX(id) { + return !id || id.toLowerCase() === 'x' || id === '*'; +} + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes(comp, loose) { + return comp.trim().split(/\s+/).map(function(comp) { + return replaceTilde(comp, loose); + }).join(' '); +} + +function replaceTilde(comp, loose) { + var r = loose ? re[TILDELOOSE] : re[TILDE]; + return comp.replace(r, function(_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) + ret = ''; + else if (isX(m)) + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + else if (isX(p)) + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + else if (pr) { + debug('replaceTilde pr', pr); + if (pr.charAt(0) !== '-') + pr = '-' + pr; + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; + + debug('tilde return', ret); + return ret; + }); +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets(comp, loose) { + return comp.trim().split(/\s+/).map(function(comp) { + return replaceCaret(comp, loose); + }).join(' '); +} + +function replaceCaret(comp, loose) { + debug('caret', comp, loose); + var r = loose ? re[CARETLOOSE] : re[CARET]; + return comp.replace(r, function(_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) + ret = ''; + else if (isX(m)) + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + else if (isX(p)) { + if (M === '0') + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + else + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; + } else if (pr) { + debug('replaceCaret pr', pr); + if (pr.charAt(0) !== '-') + pr = '-' + pr; + if (M === '0') { + if (m === '0') + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + m + '.' + (+p + 1); + else + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + (+M + 1) + '.0.0'; + } else { + debug('no pr'); + if (M === '0') { + if (m === '0') + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1); + else + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0'; + } + + debug('caret return', ret); + return ret; + }); +} + +function replaceXRanges(comp, loose) { + debug('replaceXRanges', comp, loose); + return comp.split(/\s+/).map(function(comp) { + return replaceXRange(comp, loose); + }).join(' '); +} + +function replaceXRange(comp, loose) { + comp = comp.trim(); + var r = loose ? re[XRANGELOOSE] : re[XRANGE]; + return comp.replace(r, function(ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr); + var xM = isX(M); + var xm = xM || isX(m); + var xp = xm || isX(p); + var anyX = xp; + + if (gtlt === '=' && anyX) + gtlt = ''; + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // replace X with 0 + if (xm) + m = 0; + if (xp) + p = 0; + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>='; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else if (xp) { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<'; + if (xm) + M = +M + 1; + else + m = +m + 1; + } + + ret = gtlt + M + '.' + m + '.' + p; + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + } + + debug('xRange return', ret); + + return ret; + }); +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars(comp, loose) { + debug('replaceStars', comp, loose); + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[STAR], ''); +} + +// This function is passed to string.replace(re[HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + + if (isX(fM)) + from = ''; + else if (isX(fm)) + from = '>=' + fM + '.0.0'; + else if (isX(fp)) + from = '>=' + fM + '.' + fm + '.0'; + else + from = '>=' + from; + + if (isX(tM)) + to = ''; + else if (isX(tm)) + to = '<' + (+tM + 1) + '.0.0'; + else if (isX(tp)) + to = '<' + tM + '.' + (+tm + 1) + '.0'; + else if (tpr) + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; + else + to = '<=' + to; + + return (from + ' ' + to).trim(); +} + + +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function(version) { + if (!version) + return false; + + if (typeof version === 'string') + version = new SemVer(version, this.loose); + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version)) + return true; + } + return false; +}; + +function testSet(set, version) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) + return false; + } + + if (version.prerelease.length) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (var i = 0; i < set.length; i++) { + debug(set[i].semver); + if (set[i].semver === ANY) + continue; + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver; + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) + return true; + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false; + } + + return true; +} + +exports.satisfies = satisfies; +function satisfies(version, range, loose) { + try { + range = new Range(range, loose); + } catch (er) { + return false; + } + return range.test(version); +} + +exports.maxSatisfying = maxSatisfying; +function maxSatisfying(versions, range, loose) { + var max = null; + var maxSV = null; + try { + var rangeObj = new Range(range, loose); + } catch (er) { + return null; + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { // satisfies(v, range, loose) + if (!max || maxSV.compare(v) === -1) { // compare(max, v, true) + max = v; + maxSV = new SemVer(max, loose); + } + } + }) + return max; +} + +exports.minSatisfying = minSatisfying; +function minSatisfying(versions, range, loose) { + var min = null; + var minSV = null; + try { + var rangeObj = new Range(range, loose); + } catch (er) { + return null; + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { // satisfies(v, range, loose) + if (!min || minSV.compare(v) === 1) { // compare(min, v, true) + min = v; + minSV = new SemVer(min, loose); + } + } + }) + return min; +} + +exports.validRange = validRange; +function validRange(range, loose) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, loose).range || '*'; + } catch (er) { + return null; + } +} + +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr; +function ltr(version, range, loose) { + return outside(version, range, '<', loose); +} + +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr; +function gtr(version, range, loose) { + return outside(version, range, '>', loose); +} + +exports.outside = outside; +function outside(version, range, hilo, loose) { + version = new SemVer(version, loose); + range = new Range(range, loose); + + var gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break; + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break; + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } + + // If it satisifes the range it is not outside + if (satisfies(version, range, loose)) { + return false; + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i]; + + var high = null; + var low = null; + + comparators.forEach(function(comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, loose)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, loose)) { + low = comparator; + } + }); + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false; + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false; + } + } + return true; +} + +exports.prerelease = prerelease; +function prerelease(version, loose) { + var parsed = parse(version, loose); + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null; +} + +exports.intersects = intersects; +function intersects(r1, r2, loose) { + r1 = new Range(r1, loose) + r2 = new Range(r2, loose) + return r1.intersects(r2) +} + +exports.coerce = coerce; +function coerce(version) { + if (version instanceof SemVer) + return version; + + if (typeof version !== 'string') + return null; + + var match = version.match(re[COERCE]); + + if (match == null) + return null; + + return parse((match[1] || '0') + '.' + (match[2] || '0') + '.' + (match[3] || '0')); +} + + +/***/ }), +/* 238 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const isWin = process.platform === 'win32'; + +function notFoundError(original, syscall) { + return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { + code: 'ENOENT', + errno: 'ENOENT', + syscall: `${syscall} ${original.command}`, + path: original.command, + spawnargs: original.args, + }); +} + +function hookChildProcess(cp, parsed) { + if (!isWin) { + return; + } + + const originalEmit = cp.emit; + + cp.emit = function (name, arg1) { + // If emitting "exit" event and exit code is 1, we need to check if + // the command exists and emit an "error" instead + // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 + if (name === 'exit') { + const err = verifyENOENT(arg1, parsed, 'spawn'); + + if (err) { + return originalEmit.call(cp, 'error', err); + } + } + + return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params + }; +} + +function verifyENOENT(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawn'); + } + + return null; +} + +function verifyENOENTSync(status, parsed) { + if (isWin && status === 1 && !parsed.file) { + return notFoundError(parsed.original, 'spawnSync'); + } + + return null; +} + +module.exports = { + hookChildProcess, + verifyENOENT, + verifyENOENTSync, + notFoundError, +}; + + +/***/ }), +/* 239 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = function (x) { + var lf = typeof x === 'string' ? '\n' : '\n'.charCodeAt(); + var cr = typeof x === 'string' ? '\r' : '\r'.charCodeAt(); + + if (x[x.length - 1] === lf) { + x = x.slice(0, x.length - 1); + } + + if (x[x.length - 1] === cr) { + x = x.slice(0, x.length - 1); + } + + return x; +}; + + +/***/ }), +/* 240 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const path = __webpack_require__(5); +const pathKey = __webpack_require__(241); + +module.exports = opts => { + opts = Object.assign({ + cwd: process.cwd(), + path: process.env[pathKey()] + }, opts); + + let prev; + let pth = path.resolve(opts.cwd); + const ret = []; + + while (prev !== pth) { + ret.push(path.join(pth, 'node_modules/.bin')); + prev = pth; + pth = path.resolve(pth, '..'); + } + + // ensure the running `node` binary is used + ret.push(path.dirname(process.execPath)); + + return ret.concat(opts.path).join(path.delimiter); +}; + +module.exports.env = opts => { + opts = Object.assign({ + env: process.env + }, opts); + + const env = Object.assign({}, opts.env); + const path = pathKey({env}); + + opts.path = env[path]; + env[path] = module.exports(opts); + + return env; +}; + + +/***/ }), +/* 241 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = opts => { + opts = opts || {}; + + const env = opts.env || process.env; + const platform = opts.platform || process.platform; + + if (platform !== 'win32') { + return 'PATH'; + } + + return Object.keys(env).find(x => x.toUpperCase() === 'PATH') || 'Path'; +}; + + +/***/ }), +/* 242 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var isStream = module.exports = function (stream) { + return stream !== null && typeof stream === 'object' && typeof stream.pipe === 'function'; +}; + +isStream.writable = function (stream) { + return isStream(stream) && stream.writable !== false && typeof stream._write === 'function' && typeof stream._writableState === 'object'; +}; + +isStream.readable = function (stream) { + return isStream(stream) && stream.readable !== false && typeof stream._read === 'function' && typeof stream._readableState === 'object'; +}; + +isStream.duplex = function (stream) { + return isStream.writable(stream) && isStream.readable(stream); +}; + +isStream.transform = function (stream) { + return isStream.duplex(stream) && typeof stream._transform === 'function' && typeof stream._transformState === 'object'; +}; + + +/***/ }), +/* 243 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const pump = __webpack_require__(244); +const bufferStream = __webpack_require__(246); + +class MaxBufferError extends Error { + constructor() { + super('maxBuffer exceeded'); + this.name = 'MaxBufferError'; + } +} + +function getStream(inputStream, options) { + if (!inputStream) { + return Promise.reject(new Error('Expected a stream')); + } + + options = Object.assign({maxBuffer: Infinity}, options); + + const {maxBuffer} = options; + + let stream; + return new Promise((resolve, reject) => { + const rejectPromise = error => { + if (error) { // A null check + error.bufferedData = stream.getBufferedValue(); + } + reject(error); + }; + + stream = pump(inputStream, bufferStream(options), error => { + if (error) { + rejectPromise(error); + return; + } + + resolve(); + }); + + stream.on('data', () => { + if (stream.getBufferedLength() > maxBuffer) { + rejectPromise(new MaxBufferError()); + } + }); + }).then(() => stream.getBufferedValue()); +} + +module.exports = getStream; +module.exports.buffer = (stream, options) => getStream(stream, Object.assign({}, options, {encoding: 'buffer'})); +module.exports.array = (stream, options) => getStream(stream, Object.assign({}, options, {array: true})); +module.exports.MaxBufferError = MaxBufferError; + + +/***/ }), +/* 244 */ +/***/ (function(module, exports, __webpack_require__) { + +var once = __webpack_require__(71) +var eos = __webpack_require__(245) +var fs = __webpack_require__(13) // we only need fs to get the ReadStream and WriteStream prototypes + +var noop = function () {} +var ancient = /^v?\.0/.test(process.version) + +var isFn = function (fn) { + return typeof fn === 'function' +} + +var isFS = function (stream) { + if (!ancient) return false // newer node version do not need to care about fs is a special way + if (!fs) return false // browser + return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close) +} + +var isRequest = function (stream) { + return stream.setHeader && isFn(stream.abort) +} + +var destroyer = function (stream, reading, writing, callback) { + callback = once(callback) + + var closed = false + stream.on('close', function () { + closed = true + }) + + eos(stream, {readable: reading, writable: writing}, function (err) { + if (err) return callback(err) + closed = true + callback() + }) + + var destroyed = false + return function (err) { + if (closed) return + if (destroyed) return + destroyed = true + + if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks + if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want + + if (isFn(stream.destroy)) return stream.destroy() + + callback(err || new Error('stream was destroyed')) + } +} + +var call = function (fn) { + fn() +} + +var pipe = function (from, to) { + return from.pipe(to) +} + +var pump = function () { + var streams = Array.prototype.slice.call(arguments) + var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop + + if (Array.isArray(streams[0])) streams = streams[0] + if (streams.length < 2) throw new Error('pump requires two streams per minimum') + + var error + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1 + var writing = i > 0 + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err + if (err) destroys.forEach(call) + if (reading) return + destroys.forEach(call) + callback(error) + }) + }) + + return streams.reduce(pipe) +} + +module.exports = pump + + +/***/ }), +/* 245 */ +/***/ (function(module, exports, __webpack_require__) { + +var once = __webpack_require__(71); + +var noop = function() {}; + +var isRequest = function(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +}; + +var isChildProcess = function(stream) { + return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 +}; + +var eos = function(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + + callback = once(callback || noop); + + var ws = stream._writableState; + var rs = stream._readableState; + var readable = opts.readable || (opts.readable !== false && stream.readable); + var writable = opts.writable || (opts.writable !== false && stream.writable); + + var onlegacyfinish = function() { + if (!stream.writable) onfinish(); + }; + + var onfinish = function() { + writable = false; + if (!readable) callback.call(stream); + }; + + var onend = function() { + readable = false; + if (!writable) callback.call(stream); + }; + + var onexit = function(exitCode) { + callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); + }; + + var onerror = function(err) { + callback.call(stream, err); + }; + + var onclose = function() { + if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close')); + if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close')); + }; + + var onrequest = function() { + stream.req.on('finish', onfinish); + }; + + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest(); + else stream.on('request', onrequest); + } else if (writable && !ws) { // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + + if (isChildProcess(stream)) stream.on('exit', onexit); + + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + + return function() { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('exit', onexit); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +}; + +module.exports = eos; + + +/***/ }), +/* 246 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const {PassThrough} = __webpack_require__(39); + +module.exports = options => { + options = Object.assign({}, options); + + const {array} = options; + let {encoding} = options; + const buffer = encoding === 'buffer'; + let objectMode = false; + + if (array) { + objectMode = !(encoding || buffer); + } else { + encoding = encoding || 'utf8'; + } + + if (buffer) { + encoding = null; + } + + let len = 0; + const ret = []; + const stream = new PassThrough({objectMode}); + + if (encoding) { + stream.setEncoding(encoding); + } + + stream.on('data', chunk => { + ret.push(chunk); + + if (objectMode) { + len = ret.length; + } else { + len += chunk.length; + } + }); + + stream.getBufferedValue = () => { + if (array) { + return ret; + } + + return buffer ? Buffer.concat(ret, len) : ret.join(''); + }; + + stream.getBufferedLength = () => len; + + return stream; +}; + + +/***/ }), +/* 247 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = (promise, onFinally) => { + onFinally = onFinally || (() => {}); + + return promise.then( + val => new Promise(resolve => { + resolve(onFinally()); + }).then(() => val), + err => new Promise(resolve => { + resolve(onFinally()); + }).then(() => { + throw err; + }) + ); +}; + + +/***/ }), +/* 248 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +// Older verions of Node.js might not have `util.getSystemErrorName()`. +// In that case, fall back to a deprecated internal. +const util = __webpack_require__(14); + +let uv; + +if (typeof util.getSystemErrorName === 'function') { + module.exports = util.getSystemErrorName; +} else { + try { + uv = process.binding('uv'); + + if (typeof uv.errname !== 'function') { + throw new TypeError('uv.errname is not a function'); + } + } catch (err) { + console.error('execa/lib/errname: unable to establish process.binding(\'uv\')', err); + uv = null; + } + + module.exports = code => errname(uv, code); +} + +// Used for testing the fallback behavior +module.exports.__test__ = errname; + +function errname(uv, code) { + if (uv) { + return uv.errname(code); + } + + if (!(code < 0)) { + throw new Error('err >= 0'); + } + + return `Unknown system error ${code}`; +} + + + +/***/ }), +/* 249 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const alias = ['stdin', 'stdout', 'stderr']; + +const hasAlias = opts => alias.some(x => Boolean(opts[x])); + +module.exports = opts => { + if (!opts) { + return null; + } + + if (opts.stdio && hasAlias(opts)) { + throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${alias.map(x => `\`${x}\``).join(', ')}`); + } + + if (typeof opts.stdio === 'string') { + return opts.stdio; + } + + const stdio = opts.stdio || []; + + if (!Array.isArray(stdio)) { + throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``); + } + + const result = []; + const len = Math.max(stdio.length, alias.length); + + for (let i = 0; i < len; i++) { + let value = null; + + if (stdio[i] !== undefined) { + value = stdio[i]; + } else if (opts[alias[i]] !== undefined) { + value = opts[alias[i]]; + } + + result[i] = value; + } + + return result; +}; + + +/***/ }), +/* 250 */ +/***/ (function(module, exports, __webpack_require__) { + +// Copyright IBM Corp. 2014,2018. All Rights Reserved. +// Node module: strong-log-transformer +// This file is licensed under the Apache License 2.0. +// License text available at https://opensource.org/licenses/Apache-2.0 + +module.exports = __webpack_require__(129); +module.exports.cli = __webpack_require__(255); + + +/***/ }), +/* 251 */ +/***/ (function(module, exports, __webpack_require__) { + +// Copyright (C) 2011-2015 John Hewson +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +// IN THE SOFTWARE. + +var stream = __webpack_require__(39), + util = __webpack_require__(14), + timers = __webpack_require__(252); + +// convinience API +module.exports = function(readStream, options) { + return module.exports.createStream(readStream, options); +}; + +// basic API +module.exports.createStream = function(readStream, options) { + if (readStream) { + return createLineStream(readStream, options); + } else { + return new LineStream(options); + } +}; + +// deprecated API +module.exports.createLineStream = function(readStream) { + console.log('WARNING: byline#createLineStream is deprecated and will be removed soon'); + return createLineStream(readStream); +}; + +function createLineStream(readStream, options) { + if (!readStream) { + throw new Error('expected readStream'); + } + if (!readStream.readable) { + throw new Error('readStream must be readable'); + } + var ls = new LineStream(options); + readStream.pipe(ls); + return ls; +} + +// +// using the new node v0.10 "streams2" API +// + +module.exports.LineStream = LineStream; + +function LineStream(options) { + stream.Transform.call(this, options); + options = options || {}; + + // use objectMode to stop the output from being buffered + // which re-concatanates the lines, just without newlines. + this._readableState.objectMode = true; + this._lineBuffer = []; + this._keepEmptyLines = options.keepEmptyLines || false; + this._lastChunkEndedWithCR = false; + + // take the source's encoding if we don't have one + var self = this; + this.on('pipe', function(src) { + if (!self.encoding) { + // but we can't do this for old-style streams + if (src instanceof stream.Readable) { + self.encoding = src._readableState.encoding; + } + } + }); +} +util.inherits(LineStream, stream.Transform); + +LineStream.prototype._transform = function(chunk, encoding, done) { + // decode binary chunks as UTF-8 + encoding = encoding || 'utf8'; + + if (Buffer.isBuffer(chunk)) { + if (encoding == 'buffer') { + chunk = chunk.toString(); // utf8 + encoding = 'utf8'; + } + else { + chunk = chunk.toString(encoding); + } + } + this._chunkEncoding = encoding; + + // see: http://www.unicode.org/reports/tr18/#Line_Boundaries + var lines = chunk.split(/\r\n|[\n\v\f\r\x85\u2028\u2029]/g); + + // don't split CRLF which spans chunks + if (this._lastChunkEndedWithCR && chunk[0] == '\n') { + lines.shift(); + } + + if (this._lineBuffer.length > 0) { + this._lineBuffer[this._lineBuffer.length - 1] += lines[0]; + lines.shift(); + } + + this._lastChunkEndedWithCR = chunk[chunk.length - 1] == '\r'; + this._lineBuffer = this._lineBuffer.concat(lines); + this._pushBuffer(encoding, 1, done); +}; + +LineStream.prototype._pushBuffer = function(encoding, keep, done) { + // always buffer the last (possibly partial) line + while (this._lineBuffer.length > keep) { + var line = this._lineBuffer.shift(); + // skip empty lines + if (this._keepEmptyLines || line.length > 0 ) { + if (!this.push(this._reencode(line, encoding))) { + // when the high-water mark is reached, defer pushes until the next tick + var self = this; + timers.setImmediate(function() { + self._pushBuffer(encoding, keep, done); + }); + return; + } + } + } + done(); +}; + +LineStream.prototype._flush = function(done) { + this._pushBuffer(this._chunkEncoding, 0, done); +}; + +// see Readable::push +LineStream.prototype._reencode = function(line, chunkEncoding) { + if (this.encoding && this.encoding != chunkEncoding) { + return new Buffer(line, chunkEncoding).toString(this.encoding); + } + else if (this.encoding) { + // this should be the most common case, i.e. we're using an encoded source stream + return line; + } + else { + return new Buffer(line, chunkEncoding); + } +}; + + +/***/ }), +/* 252 */ +/***/ (function(module, exports) { + +module.exports = require("timers"); + +/***/ }), +/* 253 */ +/***/ (function(module, exports, __webpack_require__) { + +var Stream = __webpack_require__(39) + +// through +// +// a stream that does nothing but re-emit the input. +// useful for aggregating a series of changing but not ending streams into one stream) + +exports = module.exports = through +through.through = through + +//create a readable writable stream. + +function through (write, end, opts) { + write = write || function (data) { this.queue(data) } + end = end || function () { this.queue(null) } + + var ended = false, destroyed = false, buffer = [], _ended = false + var stream = new Stream() + stream.readable = stream.writable = true + stream.paused = false + +// stream.autoPause = !(opts && opts.autoPause === false) + stream.autoDestroy = !(opts && opts.autoDestroy === false) + + stream.write = function (data) { + write.call(this, data) + return !stream.paused + } + + function drain() { + while(buffer.length && !stream.paused) { + var data = buffer.shift() + if(null === data) + return stream.emit('end') + else + stream.emit('data', data) + } + } + + stream.queue = stream.push = function (data) { +// console.error(ended) + if(_ended) return stream + if(data === null) _ended = true + buffer.push(data) + drain() + return stream + } + + //this will be registered as the first 'end' listener + //must call destroy next tick, to make sure we're after any + //stream piped from here. + //this is only a problem if end is not emitted synchronously. + //a nicer way to do this is to make sure this is the last listener for 'end' + + stream.on('end', function () { + stream.readable = false + if(!stream.writable && stream.autoDestroy) + process.nextTick(function () { + stream.destroy() + }) + }) + + function _end () { + stream.writable = false + end.call(stream) + if(!stream.readable && stream.autoDestroy) + stream.destroy() + } + + stream.end = function (data) { + if(ended) return + ended = true + if(arguments.length) stream.write(data) + _end() // will emit or queue + return stream + } + + stream.destroy = function () { + if(destroyed) return + destroyed = true + ended = true + buffer.length = 0 + stream.writable = stream.readable = false + stream.emit('close') + return stream + } + + stream.pause = function () { + if(stream.paused) return + stream.paused = true + return stream + } + + stream.resume = function () { + if(stream.paused) { + stream.paused = false + stream.emit('resume') + } + drain() + //may have become paused again, + //as drain emits 'data'. + if(!stream.paused) + stream.emit('drain') + return stream + } + return stream +} + + + +/***/ }), +/* 254 */ +/***/ (function(module, exports, __webpack_require__) { + +var Stream = __webpack_require__(39) +var writeMethods = ["write", "end", "destroy"] +var readMethods = ["resume", "pause"] +var readEvents = ["data", "close"] +var slice = Array.prototype.slice + +module.exports = duplex + +function forEach (arr, fn) { + if (arr.forEach) { + return arr.forEach(fn) + } + + for (var i = 0; i < arr.length; i++) { + fn(arr[i], i) + } +} + +function duplex(writer, reader) { + var stream = new Stream() + var ended = false + + forEach(writeMethods, proxyWriter) + + forEach(readMethods, proxyReader) + + forEach(readEvents, proxyStream) + + reader.on("end", handleEnd) + + writer.on("drain", function() { + stream.emit("drain") + }) + + writer.on("error", reemit) + reader.on("error", reemit) + + stream.writable = writer.writable + stream.readable = reader.readable + + return stream + + function proxyWriter(methodName) { + stream[methodName] = method + + function method() { + return writer[methodName].apply(writer, arguments) + } + } + + function proxyReader(methodName) { + stream[methodName] = method + + function method() { + stream.emit(methodName) + var func = reader[methodName] + if (func) { + return func.apply(reader, arguments) + } + reader.emit(methodName) + } + } + + function proxyStream(methodName) { + reader.on(methodName, reemit) + + function reemit() { + var args = slice.call(arguments) + args.unshift(methodName) + stream.emit.apply(stream, args) + } + } + + function handleEnd() { + if (ended) { + return + } + ended = true + var args = slice.call(arguments) + args.unshift("end") + stream.emit.apply(stream, args) + } + + function reemit(err) { + stream.emit("error", err) + } +} + + +/***/ }), +/* 255 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +// Copyright IBM Corp. 2014,2018. All Rights Reserved. +// Node module: strong-log-transformer +// This file is licensed under the Apache License 2.0. +// License text available at https://opensource.org/licenses/Apache-2.0 + + + +var minimist = __webpack_require__(256); +var path = __webpack_require__(5); + +var Logger = __webpack_require__(129); +var pkg = __webpack_require__(257); + +module.exports = cli; + +function cli(args) { + var opts = minimist(args.slice(2)); + var $0 = path.basename(args[1]); + var p = console.log.bind(console); + if (opts.v || opts.version) { + version($0, p); + } else if (opts.h || opts.help) { + usage($0, p); + } else if (args.length < 3) { + process.stdin.pipe(Logger()).pipe(process.stdout); + } else { + process.stdin.pipe(Logger(opts)).pipe(process.stdout); + } +} + +function version($0, p) { + p('%s v%s', pkg.name, pkg.version); +} + +function usage($0, p) { + var PADDING = ' '; + var opt, def; + p('Usage: %s [options]', $0); + p(''); + p('%s', pkg.description); + p(''); + p('OPTIONS:'); + for (opt in Logger.DEFAULTS) { + def = Logger.DEFAULTS[opt]; + if (typeof def === 'boolean') + boolOpt(opt, Logger.DEFAULTS[opt]); + else + stdOpt(opt, Logger.DEFAULTS[opt]); + } + p(''); + + function boolOpt(name, def) { + name = name + PADDING.slice(0, 20-name.length); + p(' --%s default: %s', name, def); + } + + function stdOpt(name, def) { + var value = name.toUpperCase() + + PADDING.slice(0, 19 - name.length*2); + p(' --%s %s default: %j', name, value, def); + } +} + + +/***/ }), +/* 256 */ +/***/ (function(module, exports) { + +module.exports = function (args, opts) { + if (!opts) opts = {}; + + var flags = { bools : {}, strings : {}, unknownFn: null }; + + if (typeof opts['unknown'] === 'function') { + flags.unknownFn = opts['unknown']; + } + + if (typeof opts['boolean'] === 'boolean' && opts['boolean']) { + flags.allBools = true; + } else { + [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + }); + } + + var aliases = {}; + Object.keys(opts.alias || {}).forEach(function (key) { + aliases[key] = [].concat(opts.alias[key]); + aliases[key].forEach(function (x) { + aliases[x] = [key].concat(aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + + [].concat(opts.string).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + if (aliases[key]) { + flags.strings[aliases[key]] = true; + } + }); + + var defaults = opts['default'] || {}; + + var argv = { _ : [] }; + Object.keys(flags.bools).forEach(function (key) { + setArg(key, defaults[key] === undefined ? false : defaults[key]); + }); + + var notFlags = []; + + if (args.indexOf('--') !== -1) { + notFlags = args.slice(args.indexOf('--')+1); + args = args.slice(0, args.indexOf('--')); + } + + function argDefined(key, arg) { + return (flags.allBools && /^--[^=]+$/.test(arg)) || + flags.strings[key] || flags.bools[key] || aliases[key]; + } + + function setArg (key, val, arg) { + if (arg && flags.unknownFn && !argDefined(key, arg)) { + if (flags.unknownFn(arg) === false) return; + } + + var value = !flags.strings[key] && isNumber(val) + ? Number(val) : val + ; + setKey(argv, key.split('.'), value); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), value); + }); + } + + function setKey (obj, keys, value) { + var o = obj; + keys.slice(0,-1).forEach(function (key) { + if (o[key] === undefined) o[key] = {}; + o = o[key]; + }); + + var key = keys[keys.length - 1]; + if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') { + o[key] = value; + } + else if (Array.isArray(o[key])) { + o[key].push(value); + } + else { + o[key] = [ o[key], value ]; + } + } + + function aliasIsBoolean(key) { + return aliases[key].some(function (x) { + return flags.bools[x]; + }); + } + + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + + if (/^--.+=/.test(arg)) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + var m = arg.match(/^--([^=]+)=([\s\S]*)$/); + var key = m[1]; + var value = m[2]; + if (flags.bools[key]) { + value = value !== 'false'; + } + setArg(key, value, arg); + } + else if (/^--no-.+/.test(arg)) { + var key = arg.match(/^--no-(.+)/)[1]; + setArg(key, false, arg); + } + else if (/^--.+/.test(arg)) { + var key = arg.match(/^--(.+)/)[1]; + var next = args[i + 1]; + if (next !== undefined && !/^-/.test(next) + && !flags.bools[key] + && !flags.allBools + && (aliases[key] ? !aliasIsBoolean(key) : true)) { + setArg(key, next, arg); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next === 'true', arg); + i++; + } + else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } + else if (/^-[^-]+/.test(arg)) { + var letters = arg.slice(1,-1).split(''); + + var broken = false; + for (var j = 0; j < letters.length; j++) { + var next = arg.slice(j+2); + + if (next === '-') { + setArg(letters[j], next, arg) + continue; + } + + if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) { + setArg(letters[j], next.split('=')[1], arg); + broken = true; + break; + } + + if (/[A-Za-z]/.test(letters[j]) + && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { + setArg(letters[j], next, arg); + broken = true; + break; + } + + if (letters[j+1] && letters[j+1].match(/\W/)) { + setArg(letters[j], arg.slice(j+2), arg); + broken = true; + break; + } + else { + setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg); + } + } + + var key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1]) + && !flags.bools[key] + && (aliases[key] ? !aliasIsBoolean(key) : true)) { + setArg(key, args[i+1], arg); + i++; + } + else if (args[i+1] && /true|false/.test(args[i+1])) { + setArg(key, args[i+1] === 'true', arg); + i++; + } + else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } + } + else { + if (!flags.unknownFn || flags.unknownFn(arg) !== false) { + argv._.push( + flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) + ); + } + if (opts.stopEarly) { + argv._.push.apply(argv._, args.slice(i + 1)); + break; + } + } + } + + Object.keys(defaults).forEach(function (key) { + if (!hasKey(argv, key.split('.'))) { + setKey(argv, key.split('.'), defaults[key]); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), defaults[key]); + }); + } + }); + + if (opts['--']) { + argv['--'] = new Array(); + notFlags.forEach(function(key) { + argv['--'].push(key); + }); + } + else { + notFlags.forEach(function(key) { + argv._.push(key); + }); + } + + return argv; +}; + +function hasKey (obj, keys) { + var o = obj; + keys.slice(0,-1).forEach(function (key) { + o = (o[key] || {}); + }); + + var key = keys[keys.length - 1]; + return key in o; +} + +function isNumber (x) { + if (typeof x === 'number') return true; + if (/^0x[0-9a-f]+$/i.test(x)) return true; + return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); +} + + + +/***/ }), +/* 257 */ +/***/ (function(module) { + +module.exports = {"name":"strong-log-transformer","version":"2.0.0","description":"Stream transformer that prefixes lines with timestamps and other things.","author":"Ryan Graham ","license":"Apache-2.0","repository":{"type":"git","url":"git://github.com/strongloop/strong-log-transformer"},"keywords":["logging","streams"],"bugs":{"url":"https://github.com/strongloop/strong-log-transformer/issues"},"homepage":"https://github.com/strongloop/strong-log-transformer","directories":{"test":"test"},"bin":{"sl-log-transformer":"bin/sl-log-transformer.js"},"main":"index.js","scripts":{"test":"tap --100 test/test-*"},"dependencies":{"byline":"^5.0.0","duplexer":"^0.1.1","minimist":"^1.2.0","through":"^2.3.4"},"devDependencies":{"tap":"^12.0.1"},"engines":{"node":">=4"}}; + +/***/ }), +/* 258 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.CleanCommand = undefined; + +var _chalk = __webpack_require__(26); + +var _chalk2 = _interopRequireDefault(_chalk); + +var _del = __webpack_require__(131); + +var _del2 = _interopRequireDefault(_del); + +var _ora = __webpack_require__(272); + +var _ora2 = _interopRequireDefault(_ora); + +var _path = __webpack_require__(5); + +var _fs = __webpack_require__(70); + +var _log = __webpack_require__(40); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + + +const CleanCommand = exports.CleanCommand = { + description: 'Remove the node_modules and target directories from all projects.', + name: 'clean', + run(projects) { + return _asyncToGenerator(function* () { + const toDelete = []; + for (const project of projects.values()) { + if (yield (0, _fs.isDirectory)(project.nodeModulesLocation)) { + toDelete.push({ + cwd: project.path, + pattern: (0, _path.relative)(project.path, project.nodeModulesLocation) + }); + } + if (yield (0, _fs.isDirectory)(project.targetLocation)) { + toDelete.push({ + cwd: project.path, + pattern: (0, _path.relative)(project.path, project.targetLocation) + }); + } + const { extraPatterns } = project.getCleanConfig(); + if (extraPatterns) { + toDelete.push({ + cwd: project.path, + pattern: extraPatterns + }); + } + } + if (toDelete.length === 0) { + _log.log.write(_chalk2.default.bold.green('\n\nNothing to delete')); + } else { + _log.log.write(_chalk2.default.bold.red('\n\nDeleting:\n')); + /** + * In order to avoid patterns like `/build` in packages from accidentally + * impacting files outside the package we use `process.chdir()` to change + * the cwd to the package and execute `del()` without the `force` option + * so it will check that each file being deleted is within the package. + * + * `del()` does support a `cwd` option, but it's only for resolving the + * patterns and does not impact the cwd check. + */ + const originalCwd = process.cwd(); + try { + for (const _ref of toDelete) { + const { pattern, cwd } = _ref; + + process.chdir(cwd); + const promise = (0, _del2.default)(pattern); + _ora2.default.promise(promise, (0, _path.relative)(originalCwd, (0, _path.join)(cwd, String(pattern)))); + yield promise; + } + } finally { + process.chdir(originalCwd); + } + } + })(); + } +}; + +/***/ }), +/* 259 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var Promise = __webpack_require__(260); +var arrayUnion = __webpack_require__(132); +var objectAssign = __webpack_require__(263); +var glob = __webpack_require__(48); +var pify = __webpack_require__(264); + +var globP = pify(glob, Promise).bind(glob); + +function isNegative(pattern) { + return pattern[0] === '!'; +} + +function isString(value) { + return typeof value === 'string'; +} + +function assertPatternsInput(patterns) { + if (!patterns.every(isString)) { + throw new TypeError('patterns must be a string or an array of strings'); + } +} + +function generateGlobTasks(patterns, opts) { + patterns = [].concat(patterns); + assertPatternsInput(patterns); + + var globTasks = []; + + opts = objectAssign({ + cache: Object.create(null), + statCache: Object.create(null), + realpathCache: Object.create(null), + symlinks: Object.create(null), + ignore: [] + }, opts); + + patterns.forEach(function (pattern, i) { + if (isNegative(pattern)) { + return; + } + + var ignore = patterns.slice(i).filter(isNegative).map(function (pattern) { + return pattern.slice(1); + }); + + globTasks.push({ + pattern: pattern, + opts: objectAssign({}, opts, { + ignore: opts.ignore.concat(ignore) + }) + }); + }); + + return globTasks; +} + +module.exports = function (patterns, opts) { + var globTasks; + + try { + globTasks = generateGlobTasks(patterns, opts); + } catch (err) { + return Promise.reject(err); + } + + return Promise.all(globTasks.map(function (task) { + return globP(task.pattern, task.opts); + })).then(function (paths) { + return arrayUnion.apply(null, paths); + }); +}; + +module.exports.sync = function (patterns, opts) { + var globTasks = generateGlobTasks(patterns, opts); + + return globTasks.reduce(function (matches, task) { + return arrayUnion(matches, glob.sync(task.pattern, task.opts)); + }, []); +}; + +module.exports.generateGlobTasks = generateGlobTasks; + +module.exports.hasMagic = function (patterns, opts) { + return [].concat(patterns).some(function (pattern) { + return glob.hasMagic(pattern, opts); + }); +}; + + +/***/ }), +/* 260 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = typeof Promise === 'function' ? Promise : __webpack_require__(261); + + +/***/ }), +/* 261 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var PENDING = 'pending'; +var SETTLED = 'settled'; +var FULFILLED = 'fulfilled'; +var REJECTED = 'rejected'; +var NOOP = function () {}; +var isNode = typeof global !== 'undefined' && typeof global.process !== 'undefined' && typeof global.process.emit === 'function'; + +var asyncSetTimer = typeof setImmediate === 'undefined' ? setTimeout : setImmediate; +var asyncQueue = []; +var asyncTimer; + +function asyncFlush() { + // run promise callbacks + for (var i = 0; i < asyncQueue.length; i++) { + asyncQueue[i][0](asyncQueue[i][1]); + } + + // reset async asyncQueue + asyncQueue = []; + asyncTimer = false; +} + +function asyncCall(callback, arg) { + asyncQueue.push([callback, arg]); + + if (!asyncTimer) { + asyncTimer = true; + asyncSetTimer(asyncFlush, 0); + } +} + +function invokeResolver(resolver, promise) { + function resolvePromise(value) { + resolve(promise, value); + } + + function rejectPromise(reason) { + reject(promise, reason); + } + + try { + resolver(resolvePromise, rejectPromise); + } catch (e) { + rejectPromise(e); + } +} + +function invokeCallback(subscriber) { + var owner = subscriber.owner; + var settled = owner._state; + var value = owner._data; + var callback = subscriber[settled]; + var promise = subscriber.then; + + if (typeof callback === 'function') { + settled = FULFILLED; + try { + value = callback(value); + } catch (e) { + reject(promise, e); + } + } + + if (!handleThenable(promise, value)) { + if (settled === FULFILLED) { + resolve(promise, value); + } + + if (settled === REJECTED) { + reject(promise, value); + } + } +} + +function handleThenable(promise, value) { + var resolved; + + try { + if (promise === value) { + throw new TypeError('A promises callback cannot return that same promise.'); + } + + if (value && (typeof value === 'function' || typeof value === 'object')) { + // then should be retrieved only once + var then = value.then; + + if (typeof then === 'function') { + then.call(value, function (val) { + if (!resolved) { + resolved = true; + + if (value === val) { + fulfill(promise, val); + } else { + resolve(promise, val); + } + } + }, function (reason) { + if (!resolved) { + resolved = true; + + reject(promise, reason); + } + }); + + return true; + } + } + } catch (e) { + if (!resolved) { + reject(promise, e); + } + + return true; + } + + return false; +} + +function resolve(promise, value) { + if (promise === value || !handleThenable(promise, value)) { + fulfill(promise, value); + } +} + +function fulfill(promise, value) { + if (promise._state === PENDING) { + promise._state = SETTLED; + promise._data = value; + + asyncCall(publishFulfillment, promise); + } +} + +function reject(promise, reason) { + if (promise._state === PENDING) { + promise._state = SETTLED; + promise._data = reason; + + asyncCall(publishRejection, promise); + } +} + +function publish(promise) { + promise._then = promise._then.forEach(invokeCallback); +} + +function publishFulfillment(promise) { + promise._state = FULFILLED; + publish(promise); +} + +function publishRejection(promise) { + promise._state = REJECTED; + publish(promise); + if (!promise._handled && isNode) { + global.process.emit('unhandledRejection', promise._data, promise); + } +} + +function notifyRejectionHandled(promise) { + global.process.emit('rejectionHandled', promise); +} + +/** + * @class + */ +function Promise(resolver) { + if (typeof resolver !== 'function') { + throw new TypeError('Promise resolver ' + resolver + ' is not a function'); + } + + if (this instanceof Promise === false) { + throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.'); + } + + this._then = []; + + invokeResolver(resolver, this); +} + +Promise.prototype = { + constructor: Promise, + + _state: PENDING, + _then: null, + _data: undefined, + _handled: false, + + then: function (onFulfillment, onRejection) { + var subscriber = { + owner: this, + then: new this.constructor(NOOP), + fulfilled: onFulfillment, + rejected: onRejection + }; + + if ((onRejection || onFulfillment) && !this._handled) { + this._handled = true; + if (this._state === REJECTED && isNode) { + asyncCall(notifyRejectionHandled, this); + } + } + + if (this._state === FULFILLED || this._state === REJECTED) { + // already resolved, call callback async + asyncCall(invokeCallback, subscriber); + } else { + // subscribe + this._then.push(subscriber); + } + + return subscriber.then; + }, + + catch: function (onRejection) { + return this.then(null, onRejection); + } +}; + +Promise.all = function (promises) { + if (!Array.isArray(promises)) { + throw new TypeError('You must pass an array to Promise.all().'); + } + + return new Promise(function (resolve, reject) { + var results = []; + var remaining = 0; + + function resolver(index) { + remaining++; + return function (value) { + results[index] = value; + if (!--remaining) { + resolve(results); + } + }; + } + + for (var i = 0, promise; i < promises.length; i++) { + promise = promises[i]; + + if (promise && typeof promise.then === 'function') { + promise.then(resolver(i), reject); + } else { + results[i] = promise; + } + } + + if (!remaining) { + resolve(results); + } + }); +}; + +Promise.race = function (promises) { + if (!Array.isArray(promises)) { + throw new TypeError('You must pass an array to Promise.race().'); + } + + return new Promise(function (resolve, reject) { + for (var i = 0, promise; i < promises.length; i++) { + promise = promises[i]; + + if (promise && typeof promise.then === 'function') { + promise.then(resolve, reject); + } else { + resolve(promise); + } + } + }); +}; + +Promise.resolve = function (value) { + if (value && typeof value === 'object' && value.constructor === Promise) { + return value; + } + + return new Promise(function (resolve) { + resolve(value); + }); +}; + +Promise.reject = function (reason) { + return new Promise(function (resolve, reject) { + reject(reason); + }); +}; + +module.exports = Promise; + + +/***/ }), +/* 262 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +// there's 3 implementations written in increasing order of efficiency + +// 1 - no Set type is defined +function uniqNoSet(arr) { + var ret = []; + + for (var i = 0; i < arr.length; i++) { + if (ret.indexOf(arr[i]) === -1) { + ret.push(arr[i]); + } + } + + return ret; +} + +// 2 - a simple Set type is defined +function uniqSet(arr) { + var seen = new Set(); + return arr.filter(function (el) { + if (!seen.has(el)) { + seen.add(el); + return true; + } + + return false; + }); +} + +// 3 - a standard Set type is defined and it has a forEach method +function uniqSetWithForEach(arr) { + var ret = []; + + (new Set(arr)).forEach(function (el) { + ret.push(el); + }); + + return ret; +} + +// V8 currently has a broken implementation +// https://github.com/joyent/node/issues/8449 +function doesForEachActuallyWork() { + var ret = false; + + (new Set([true])).forEach(function (el) { + ret = el; + }); + + return ret === true; +} + +if ('Set' in global) { + if (typeof Set.prototype.forEach === 'function' && doesForEachActuallyWork()) { + module.exports = uniqSetWithForEach; + } else { + module.exports = uniqSet; + } +} else { + module.exports = uniqNoSet; +} + + +/***/ }), +/* 263 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ + + +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; + +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); +} + +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} + +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; +}; + + +/***/ }), +/* 264 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var processFn = function (fn, P, opts) { + return function () { + var that = this; + var args = new Array(arguments.length); + + for (var i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + + return new P(function (resolve, reject) { + args.push(function (err, result) { + if (err) { + reject(err); + } else if (opts.multiArgs) { + var results = new Array(arguments.length - 1); + + for (var i = 1; i < arguments.length; i++) { + results[i - 1] = arguments[i]; + } + + resolve(results); + } else { + resolve(result); + } + }); + + fn.apply(that, args); + }); + }; +}; + +var pify = module.exports = function (obj, P, opts) { + if (typeof P !== 'function') { + opts = P; + P = Promise; + } + + opts = opts || {}; + opts.exclude = opts.exclude || [/.+Sync$/]; + + var filter = function (key) { + var match = function (pattern) { + return typeof pattern === 'string' ? key === pattern : pattern.test(key); + }; + + return opts.include ? opts.include.some(match) : !opts.exclude.some(match); + }; + + var ret = typeof obj === 'function' ? function () { + if (opts.excludeMain) { + return obj.apply(this, arguments); + } + + return processFn(obj, P, opts).apply(this, arguments); + } : {}; + + return Object.keys(obj).reduce(function (ret, key) { + var x = obj[key]; + + ret[key] = typeof x === 'function' && filter(key) ? processFn(x, P, opts) : x; + + return ret; + }, ret); +}; + +pify.all = pify; + + +/***/ }), +/* 265 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var path = __webpack_require__(5); + +module.exports = function (str) { + return path.resolve(str) === path.resolve(process.cwd()); +}; + + +/***/ }), +/* 266 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var isPathInside = __webpack_require__(267); + +module.exports = function (str) { + return isPathInside(str, process.cwd()); +}; + + +/***/ }), +/* 267 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var path = __webpack_require__(5); +var pathIsInside = __webpack_require__(268); + +module.exports = function (a, b) { + a = path.resolve(a); + b = path.resolve(b); + + if (a === b) { + return false; + } + + return pathIsInside(a, b); +}; + + +/***/ }), +/* 268 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var path = __webpack_require__(5); + +module.exports = function (thePath, potentialParent) { + // For inside-directory checking, we want to allow trailing slashes, so normalize. + thePath = stripTrailingSep(thePath); + potentialParent = stripTrailingSep(potentialParent); + + // Node treats only Windows as case-insensitive in its path module; we follow those conventions. + if (process.platform === "win32") { + thePath = thePath.toLowerCase(); + potentialParent = potentialParent.toLowerCase(); + } + + return thePath.lastIndexOf(potentialParent, 0) === 0 && + ( + thePath[potentialParent.length] === path.sep || + thePath[potentialParent.length] === undefined + ); +}; + +function stripTrailingSep(thePath) { + if (thePath[thePath.length - 1] === path.sep) { + return thePath.slice(0, -1); + } + return thePath; +} + + +/***/ }), +/* 269 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const processFn = (fn, opts) => function () { + const P = opts.promiseModule; + const args = new Array(arguments.length); + + for (let i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + + return new P((resolve, reject) => { + if (opts.errorFirst) { + args.push(function (err, result) { + if (opts.multiArgs) { + const results = new Array(arguments.length - 1); + + for (let i = 1; i < arguments.length; i++) { + results[i - 1] = arguments[i]; + } + + if (err) { + results.unshift(err); + reject(results); + } else { + resolve(results); + } + } else if (err) { + reject(err); + } else { + resolve(result); + } + }); + } else { + args.push(function (result) { + if (opts.multiArgs) { + const results = new Array(arguments.length - 1); + + for (let i = 0; i < arguments.length; i++) { + results[i] = arguments[i]; + } + + resolve(results); + } else { + resolve(result); + } + }); + } + + fn.apply(this, args); + }); +}; + +module.exports = (obj, opts) => { + opts = Object.assign({ + exclude: [/.+(Sync|Stream)$/], + errorFirst: true, + promiseModule: Promise + }, opts); + + const filter = key => { + const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key); + return opts.include ? opts.include.some(match) : !opts.exclude.some(match); + }; + + let ret; + if (typeof obj === 'function') { + ret = function () { + if (opts.excludeMain) { + return obj.apply(this, arguments); + } + + return processFn(obj, opts).apply(this, arguments); + }; + } else { + ret = Object.create(Object.getPrototypeOf(obj)); + } + + for (const key in obj) { // eslint-disable-line guard-for-in + const x = obj[key]; + ret[key] = typeof x === 'function' && filter(key) ? processFn(x, opts) : x; + } + + return ret; +}; + + +/***/ }), +/* 270 */ +/***/ (function(module, exports, __webpack_require__) { + +module.exports = rimraf +rimraf.sync = rimrafSync + +var assert = __webpack_require__(62) +var path = __webpack_require__(5) +var fs = __webpack_require__(13) +var glob = __webpack_require__(48) +var _0666 = parseInt('666', 8) + +var defaultGlobOpts = { + nosort: true, + silent: true +} + +// for EMFILE handling +var timeout = 0 + +var isWindows = (process.platform === "win32") + +function defaults (options) { + var methods = [ + 'unlink', + 'chmod', + 'stat', + 'lstat', + 'rmdir', + 'readdir' + ] + methods.forEach(function(m) { + options[m] = options[m] || fs[m] + m = m + 'Sync' + options[m] = options[m] || fs[m] + }) + + options.maxBusyTries = options.maxBusyTries || 3 + options.emfileWait = options.emfileWait || 1000 + if (options.glob === false) { + options.disableGlob = true + } + options.disableGlob = options.disableGlob || false + options.glob = options.glob || defaultGlobOpts +} + +function rimraf (p, options, cb) { + if (typeof options === 'function') { + cb = options + options = {} + } + + assert(p, 'rimraf: missing path') + assert.equal(typeof p, 'string', 'rimraf: path should be a string') + assert.equal(typeof cb, 'function', 'rimraf: callback function required') + assert(options, 'rimraf: invalid options argument provided') + assert.equal(typeof options, 'object', 'rimraf: options should be object') + + defaults(options) + + var busyTries = 0 + var errState = null + var n = 0 + + if (options.disableGlob || !glob.hasMagic(p)) + return afterGlob(null, [p]) + + options.lstat(p, function (er, stat) { + if (!er) + return afterGlob(null, [p]) + + glob(p, options.glob, afterGlob) + }) + + function next (er) { + errState = errState || er + if (--n === 0) + cb(errState) + } + + function afterGlob (er, results) { + if (er) + return cb(er) + + n = results.length + if (n === 0) + return cb() + + results.forEach(function (p) { + rimraf_(p, options, function CB (er) { + if (er) { + if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && + busyTries < options.maxBusyTries) { + busyTries ++ + var time = busyTries * 100 + // try again, with the same exact callback as this one. + return setTimeout(function () { + rimraf_(p, options, CB) + }, time) + } + + // this one won't happen if graceful-fs is used. + if (er.code === "EMFILE" && timeout < options.emfileWait) { + return setTimeout(function () { + rimraf_(p, options, CB) + }, timeout ++) + } + + // already gone + if (er.code === "ENOENT") er = null + } + + timeout = 0 + next(er) + }) + }) + } +} + +// Two possible strategies. +// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR +// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR +// +// Both result in an extra syscall when you guess wrong. However, there +// are likely far more normal files in the world than directories. This +// is based on the assumption that a the average number of files per +// directory is >= 1. +// +// If anyone ever complains about this, then I guess the strategy could +// be made configurable somehow. But until then, YAGNI. +function rimraf_ (p, options, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') + + // sunos lets the root user unlink directories, which is... weird. + // so we have to lstat here and make sure it's not a dir. + options.lstat(p, function (er, st) { + if (er && er.code === "ENOENT") + return cb(null) + + // Windows can EPERM on stat. Life is suffering. + if (er && er.code === "EPERM" && isWindows) + fixWinEPERM(p, options, er, cb) + + if (st && st.isDirectory()) + return rmdir(p, options, er, cb) + + options.unlink(p, function (er) { + if (er) { + if (er.code === "ENOENT") + return cb(null) + if (er.code === "EPERM") + return (isWindows) + ? fixWinEPERM(p, options, er, cb) + : rmdir(p, options, er, cb) + if (er.code === "EISDIR") + return rmdir(p, options, er, cb) + } + return cb(er) + }) + }) +} + +function fixWinEPERM (p, options, er, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') + if (er) + assert(er instanceof Error) + + options.chmod(p, _0666, function (er2) { + if (er2) + cb(er2.code === "ENOENT" ? null : er) + else + options.stat(p, function(er3, stats) { + if (er3) + cb(er3.code === "ENOENT" ? null : er) + else if (stats.isDirectory()) + rmdir(p, options, er, cb) + else + options.unlink(p, cb) + }) + }) +} + +function fixWinEPERMSync (p, options, er) { + assert(p) + assert(options) + if (er) + assert(er instanceof Error) + + try { + options.chmodSync(p, _0666) + } catch (er2) { + if (er2.code === "ENOENT") + return + else + throw er + } + + try { + var stats = options.statSync(p) + } catch (er3) { + if (er3.code === "ENOENT") + return + else + throw er + } + + if (stats.isDirectory()) + rmdirSync(p, options, er) + else + options.unlinkSync(p) +} + +function rmdir (p, options, originalEr, cb) { + assert(p) + assert(options) + if (originalEr) + assert(originalEr instanceof Error) + assert(typeof cb === 'function') + + // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) + // if we guessed wrong, and it's not a directory, then + // raise the original error. + options.rmdir(p, function (er) { + if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) + rmkids(p, options, cb) + else if (er && er.code === "ENOTDIR") + cb(originalEr) + else + cb(er) + }) +} + +function rmkids(p, options, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') + + options.readdir(p, function (er, files) { + if (er) + return cb(er) + var n = files.length + if (n === 0) + return options.rmdir(p, cb) + var errState + files.forEach(function (f) { + rimraf(path.join(p, f), options, function (er) { + if (errState) + return + if (er) + return cb(errState = er) + if (--n === 0) + options.rmdir(p, cb) + }) + }) + }) +} + +// this looks simpler, and is strictly *faster*, but will +// tie up the JavaScript thread and fail on excessively +// deep directory trees. +function rimrafSync (p, options) { + options = options || {} + defaults(options) + + assert(p, 'rimraf: missing path') + assert.equal(typeof p, 'string', 'rimraf: path should be a string') + assert(options, 'rimraf: missing options') + assert.equal(typeof options, 'object', 'rimraf: options should be object') + + var results + + if (options.disableGlob || !glob.hasMagic(p)) { + results = [p] + } else { + try { + options.lstatSync(p) + results = [p] + } catch (er) { + results = glob.sync(p, options.glob) + } + } + + if (!results.length) + return + + for (var i = 0; i < results.length; i++) { + var p = results[i] + + try { + var st = options.lstatSync(p) + } catch (er) { + if (er.code === "ENOENT") + return + + // Windows can EPERM on stat. Life is suffering. + if (er.code === "EPERM" && isWindows) + fixWinEPERMSync(p, options, er) + } + + try { + // sunos lets the root user unlink directories, which is... weird. + if (st && st.isDirectory()) + rmdirSync(p, options, null) + else + options.unlinkSync(p) + } catch (er) { + if (er.code === "ENOENT") + return + if (er.code === "EPERM") + return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) + if (er.code !== "EISDIR") + throw er + + rmdirSync(p, options, er) + } + } +} + +function rmdirSync (p, options, originalEr) { + assert(p) + assert(options) + if (originalEr) + assert(originalEr instanceof Error) + + try { + options.rmdirSync(p) + } catch (er) { + if (er.code === "ENOENT") + return + if (er.code === "ENOTDIR") + throw originalEr + if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") + rmkidsSync(p, options) + } +} + +function rmkidsSync (p, options) { + assert(p) + assert(options) + options.readdirSync(p).forEach(function (f) { + rimrafSync(path.join(p, f), options) + }) + + // We only end up here once we got ENOTEMPTY at least once, and + // at this point, we are guaranteed to have removed all the kids. + // So, we know that it won't be ENOENT or ENOTDIR or anything else. + // try really hard to delete stuff on windows, because it has a + // PROFOUNDLY annoying habit of not closing handles promptly when + // files are deleted, resulting in spurious ENOTEMPTY errors. + var retries = isWindows ? 100 : 1 + var i = 0 + do { + var threw = true + try { + var ret = options.rmdirSync(p, options) + threw = false + return ret + } finally { + if (++i < retries && threw) + continue + } + } while (true) +} + + +/***/ }), +/* 271 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = (iterable, mapper, opts) => new Promise((resolve, reject) => { + opts = Object.assign({ + concurrency: Infinity + }, opts); + + if (typeof mapper !== 'function') { + throw new TypeError('Mapper function is required'); + } + + const concurrency = opts.concurrency; + + if (!(typeof concurrency === 'number' && concurrency >= 1)) { + throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${concurrency}\` (${typeof concurrency})`); + } + + const ret = []; + const iterator = iterable[Symbol.iterator](); + let isRejected = false; + let iterableDone = false; + let resolvingCount = 0; + let currentIdx = 0; + + const next = () => { + if (isRejected) { + return; + } + + const nextItem = iterator.next(); + const i = currentIdx; + currentIdx++; + + if (nextItem.done) { + iterableDone = true; + + if (resolvingCount === 0) { + resolve(ret); + } + + return; + } + + resolvingCount++; + + Promise.resolve(nextItem.value) + .then(el => mapper(el, i)) + .then( + val => { + ret[i] = val; + resolvingCount--; + next(); + }, + err => { + isRejected = true; + reject(err); + } + ); + }; + + for (let i = 0; i < concurrency; i++) { + next(); + + if (iterableDone) { + break; + } + } +}); + + +/***/ }), +/* 272 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const chalk = __webpack_require__(26); +const cliCursor = __webpack_require__(273); +const cliSpinners = __webpack_require__(277); +const logSymbols = __webpack_require__(128); + +class Ora { + constructor(options) { + if (typeof options === 'string') { + options = { + text: options + }; + } + + this.options = Object.assign({ + text: '', + color: 'cyan', + stream: process.stderr + }, options); + + const sp = this.options.spinner; + this.spinner = typeof sp === 'object' ? sp : (process.platform === 'win32' ? cliSpinners.line : (cliSpinners[sp] || cliSpinners.dots)); // eslint-disable-line no-nested-ternary + + if (this.spinner.frames === undefined) { + throw new Error('Spinner must define `frames`'); + } + + this.text = this.options.text; + this.color = this.options.color; + this.interval = this.options.interval || this.spinner.interval || 100; + this.stream = this.options.stream; + this.id = null; + this.frameIndex = 0; + this.enabled = typeof this.options.enabled === 'boolean' ? this.options.enabled : ((this.stream && this.stream.isTTY) && !process.env.CI); + } + frame() { + const frames = this.spinner.frames; + let frame = frames[this.frameIndex]; + + if (this.color) { + frame = chalk[this.color](frame); + } + + this.frameIndex = ++this.frameIndex % frames.length; + + return frame + ' ' + this.text; + } + clear() { + if (!this.enabled) { + return this; + } + + this.stream.clearLine(); + this.stream.cursorTo(0); + + return this; + } + render() { + this.clear(); + this.stream.write(this.frame()); + + return this; + } + start(text) { + if (text) { + this.text = text; + } + + if (!this.enabled || this.id) { + return this; + } + + cliCursor.hide(this.stream); + this.render(); + this.id = setInterval(this.render.bind(this), this.interval); + + return this; + } + stop() { + if (!this.enabled) { + return this; + } + + clearInterval(this.id); + this.id = null; + this.frameIndex = 0; + this.clear(); + cliCursor.show(this.stream); + + return this; + } + succeed(text) { + return this.stopAndPersist({symbol: logSymbols.success, text}); + } + fail(text) { + return this.stopAndPersist({symbol: logSymbols.error, text}); + } + warn(text) { + return this.stopAndPersist({symbol: logSymbols.warning, text}); + } + info(text) { + return this.stopAndPersist({symbol: logSymbols.info, text}); + } + stopAndPersist(options) { + if (!this.enabled) { + return this; + } + + // Legacy argument + // TODO: Deprecate sometime in the future + if (typeof options === 'string') { + options = { + symbol: options + }; + } + + options = options || {}; + + this.stop(); + this.stream.write(`${options.symbol || ' '} ${options.text || this.text}\n`); + + return this; + } +} + +module.exports = function (opts) { + return new Ora(opts); +}; + +module.exports.promise = (action, options) => { + if (typeof action.then !== 'function') { + throw new TypeError('Parameter `action` must be a Promise'); + } + + const spinner = new Ora(options); + spinner.start(); + + action.then( + () => { + spinner.succeed(); + }, + () => { + spinner.fail(); + } + ); + + return spinner; +}; + + +/***/ }), +/* 273 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const restoreCursor = __webpack_require__(274); + +let hidden = false; + +exports.show = stream => { + const s = stream || process.stderr; + + if (!s.isTTY) { + return; + } + + hidden = false; + s.write('\u001b[?25h'); +}; + +exports.hide = stream => { + const s = stream || process.stderr; + + if (!s.isTTY) { + return; + } + + restoreCursor(); + hidden = true; + s.write('\u001b[?25l'); +}; + +exports.toggle = (force, stream) => { + if (force !== undefined) { + hidden = force; + } + + if (hidden) { + exports.show(stream); + } else { + exports.hide(stream); + } +}; + + +/***/ }), +/* 274 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const onetime = __webpack_require__(275); +const signalExit = __webpack_require__(103); + +module.exports = onetime(() => { + signalExit(() => { + process.stderr.write('\u001b[?25h'); + }, {alwaysLast: true}); +}); + + +/***/ }), +/* 275 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const mimicFn = __webpack_require__(276); + +module.exports = (fn, opts) => { + // TODO: Remove this in v3 + if (opts === true) { + throw new TypeError('The second argument is now an options object'); + } + + if (typeof fn !== 'function') { + throw new TypeError('Expected a function'); + } + + opts = opts || {}; + + let ret; + let called = false; + const fnName = fn.displayName || fn.name || ''; + + const onetime = function () { + if (called) { + if (opts.throw === true) { + throw new Error(`Function \`${fnName}\` can only be called once`); + } + + return ret; + } + + called = true; + ret = fn.apply(this, arguments); + fn = null; + + return ret; + }; + + mimicFn(onetime, fn); + + return onetime; +}; + + +/***/ }), +/* 276 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = (to, from) => { + // TODO: use `Reflect.ownKeys()` when targeting Node.js 6 + for (const prop of Object.getOwnPropertyNames(from).concat(Object.getOwnPropertySymbols(from))) { + Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop)); + } +}; + + +/***/ }), +/* 277 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = __webpack_require__(278); + + +/***/ }), +/* 278 */ +/***/ (function(module) { + +module.exports = {"dots":{"interval":80,"frames":["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]},"dots2":{"interval":80,"frames":["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"]},"dots3":{"interval":80,"frames":["⠋","⠙","⠚","⠞","⠖","⠦","⠴","⠲","⠳","⠓"]},"dots4":{"interval":80,"frames":["⠄","⠆","⠇","⠋","⠙","⠸","⠰","⠠","⠰","⠸","⠙","⠋","⠇","⠆"]},"dots5":{"interval":80,"frames":["⠋","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋"]},"dots6":{"interval":80,"frames":["⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠴","⠲","⠒","⠂","⠂","⠒","⠚","⠙","⠉","⠁"]},"dots7":{"interval":80,"frames":["⠈","⠉","⠋","⠓","⠒","⠐","⠐","⠒","⠖","⠦","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈"]},"dots8":{"interval":80,"frames":["⠁","⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈","⠈"]},"dots9":{"interval":80,"frames":["⢹","⢺","⢼","⣸","⣇","⡧","⡗","⡏"]},"dots10":{"interval":80,"frames":["⢄","⢂","⢁","⡁","⡈","⡐","⡠"]},"dots11":{"interval":100,"frames":["⠁","⠂","⠄","⡀","⢀","⠠","⠐","⠈"]},"dots12":{"interval":80,"frames":["⢀⠀","⡀⠀","⠄⠀","⢂⠀","⡂⠀","⠅⠀","⢃⠀","⡃⠀","⠍⠀","⢋⠀","⡋⠀","⠍⠁","⢋⠁","⡋⠁","⠍⠉","⠋⠉","⠋⠉","⠉⠙","⠉⠙","⠉⠩","⠈⢙","⠈⡙","⢈⠩","⡀⢙","⠄⡙","⢂⠩","⡂⢘","⠅⡘","⢃⠨","⡃⢐","⠍⡐","⢋⠠","⡋⢀","⠍⡁","⢋⠁","⡋⠁","⠍⠉","⠋⠉","⠋⠉","⠉⠙","⠉⠙","⠉⠩","⠈⢙","⠈⡙","⠈⠩","⠀⢙","⠀⡙","⠀⠩","⠀⢘","⠀⡘","⠀⠨","⠀⢐","⠀⡐","⠀⠠","⠀⢀","⠀⡀"]},"line":{"interval":130,"frames":["-","\\","|","/"]},"line2":{"interval":100,"frames":["⠂","-","–","—","–","-"]},"pipe":{"interval":100,"frames":["┤","┘","┴","└","├","┌","┬","┐"]},"simpleDots":{"interval":400,"frames":[". ",".. ","..."," "]},"simpleDotsScrolling":{"interval":200,"frames":[". ",".. ","..."," .."," ."," "]},"star":{"interval":70,"frames":["✶","✸","✹","✺","✹","✷"]},"star2":{"interval":80,"frames":["+","x","*"]},"flip":{"interval":70,"frames":["_","_","_","-","`","`","'","´","-","_","_","_"]},"hamburger":{"interval":100,"frames":["☱","☲","☴"]},"growVertical":{"interval":120,"frames":["▁","▃","▄","▅","▆","▇","▆","▅","▄","▃"]},"growHorizontal":{"interval":120,"frames":["▏","▎","▍","▌","▋","▊","▉","▊","▋","▌","▍","▎"]},"balloon":{"interval":140,"frames":[" ",".","o","O","@","*"," "]},"balloon2":{"interval":120,"frames":[".","o","O","°","O","o","."]},"noise":{"interval":100,"frames":["▓","▒","░"]},"bounce":{"interval":120,"frames":["⠁","⠂","⠄","⠂"]},"boxBounce":{"interval":120,"frames":["▖","▘","▝","▗"]},"boxBounce2":{"interval":100,"frames":["▌","▀","▐","▄"]},"triangle":{"interval":50,"frames":["◢","◣","◤","◥"]},"arc":{"interval":100,"frames":["◜","◠","◝","◞","◡","◟"]},"circle":{"interval":120,"frames":["◡","⊙","◠"]},"squareCorners":{"interval":180,"frames":["◰","◳","◲","◱"]},"circleQuarters":{"interval":120,"frames":["◴","◷","◶","◵"]},"circleHalves":{"interval":50,"frames":["◐","◓","◑","◒"]},"squish":{"interval":100,"frames":["╫","╪"]},"toggle":{"interval":250,"frames":["⊶","⊷"]},"toggle2":{"interval":80,"frames":["▫","▪"]},"toggle3":{"interval":120,"frames":["□","■"]},"toggle4":{"interval":100,"frames":["■","□","▪","▫"]},"toggle5":{"interval":100,"frames":["▮","▯"]},"toggle6":{"interval":300,"frames":["ဝ","၀"]},"toggle7":{"interval":80,"frames":["⦾","⦿"]},"toggle8":{"interval":100,"frames":["◍","◌"]},"toggle9":{"interval":100,"frames":["◉","◎"]},"toggle10":{"interval":100,"frames":["㊂","㊀","㊁"]},"toggle11":{"interval":50,"frames":["⧇","⧆"]},"toggle12":{"interval":120,"frames":["☗","☖"]},"toggle13":{"interval":80,"frames":["=","*","-"]},"arrow":{"interval":100,"frames":["←","↖","↑","↗","→","↘","↓","↙"]},"arrow2":{"interval":80,"frames":["⬆️ ","↗️ ","➡️ ","↘️ ","⬇️ ","↙️ ","⬅️ ","↖️ "]},"arrow3":{"interval":120,"frames":["▹▹▹▹▹","▸▹▹▹▹","▹▸▹▹▹","▹▹▸▹▹","▹▹▹▸▹","▹▹▹▹▸"]},"bouncingBar":{"interval":80,"frames":["[ ]","[= ]","[== ]","[=== ]","[ ===]","[ ==]","[ =]","[ ]","[ =]","[ ==]","[ ===]","[====]","[=== ]","[== ]","[= ]"]},"bouncingBall":{"interval":80,"frames":["( ● )","( ● )","( ● )","( ● )","( ●)","( ● )","( ● )","( ● )","( ● )","(● )"]},"smiley":{"interval":200,"frames":["😄 ","😝 "]},"monkey":{"interval":300,"frames":["🙈 ","🙈 ","🙉 ","🙊 "]},"hearts":{"interval":100,"frames":["💛 ","💙 ","💜 ","💚 ","❤️ "]},"clock":{"interval":100,"frames":["🕐 ","🕑 ","🕒 ","🕓 ","🕔 ","🕕 ","🕖 ","🕗 ","🕘 ","🕙 ","🕚 "]},"earth":{"interval":180,"frames":["🌍 ","🌎 ","🌏 "]},"moon":{"interval":80,"frames":["🌑 ","🌒 ","🌓 ","🌔 ","🌕 ","🌖 ","🌗 ","🌘 "]},"runner":{"interval":140,"frames":["🚶 ","🏃 "]},"pong":{"interval":80,"frames":["▐⠂ ▌","▐⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂▌","▐ ⠠▌","▐ ⡀▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐⠠ ▌"]},"shark":{"interval":120,"frames":["▐|\\____________▌","▐_|\\___________▌","▐__|\\__________▌","▐___|\\_________▌","▐____|\\________▌","▐_____|\\_______▌","▐______|\\______▌","▐_______|\\_____▌","▐________|\\____▌","▐_________|\\___▌","▐__________|\\__▌","▐___________|\\_▌","▐____________|\\▌","▐____________/|▌","▐___________/|_▌","▐__________/|__▌","▐_________/|___▌","▐________/|____▌","▐_______/|_____▌","▐______/|______▌","▐_____/|_______▌","▐____/|________▌","▐___/|_________▌","▐__/|__________▌","▐_/|___________▌","▐/|____________▌"]},"dqpb":{"interval":100,"frames":["d","q","p","b"]},"weather":{"interval":100,"frames":["☀️ ","☀️ ","☀️ ","🌤 ","⛅️ ","🌥 ","☁️ ","🌧 ","🌨 ","🌧 ","🌨 ","🌧 ","🌨 ","⛈ ","🌨 ","🌧 ","🌨 ","☁️ ","🌥 ","⛅️ ","🌤 ","☀️ ","☀️ "]},"christmas":{"interval":400,"frames":["🌲","🎄"]}}; + +/***/ }), +/* 279 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.RunCommand = undefined; + +var _chalk = __webpack_require__(26); + +var _chalk2 = _interopRequireDefault(_chalk); + +var _log = __webpack_require__(40); + +var _parallelize = __webpack_require__(98); + +var _projects = __webpack_require__(47); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + + +const RunCommand = exports.RunCommand = { + description: 'Run script defined in package.json in each package that contains that script.', + name: 'run', + run(projects, projectGraph, { extraArgs }) { + return _asyncToGenerator(function* () { + const batchedProjects = (0, _projects.topologicallyBatchProjects)(projects, projectGraph); + if (extraArgs.length === 0) { + _log.log.write(_chalk2.default.red.bold('\nNo script specified')); + process.exit(1); + } + const scriptName = extraArgs[0]; + const scriptArgs = extraArgs.slice(1); + _log.log.write(_chalk2.default.bold(`\nRunning script [${_chalk2.default.green(scriptName)}] in batched topological order\n`)); + yield (0, _parallelize.parallelizeBatches)(batchedProjects, (() => { + var _ref = _asyncToGenerator(function* (pkg) { + if (pkg.hasScript(scriptName)) { + yield pkg.runScriptStreaming(scriptName, scriptArgs); + } + }); + + return function (_x) { + return _ref.apply(this, arguments); + }; + })()); + })(); + } +}; + +/***/ }), +/* 280 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.WatchCommand = undefined; + +var _chalk = __webpack_require__(26); + +var _chalk2 = _interopRequireDefault(_chalk); + +var _log = __webpack_require__(40); + +var _parallelize = __webpack_require__(98); + +var _projects = __webpack_require__(47); + +var _watch = __webpack_require__(281); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + + +/** + * Name of the script in the package/project package.json file to run during `kbn watch`. + */ +const watchScriptName = 'kbn:watch'; +/** + * Name of the Kibana project. + */ +const kibanaProjectName = 'kibana'; +/** + * Command that traverses through list of available projects/packages that have `kbn:watch` script in their + * package.json files, groups them into topology aware batches and then processes theses batches one by one + * running `kbn:watch` scripts in parallel within the same batch. + * + * Command internally relies on the fact that most of the build systems that are triggered by `kbn:watch` + * will emit special "marker" once build/watch process is ready that we can use as completion condition for + * the `kbn:watch` script and eventually for the entire batch. Currently we support completion "markers" for + * `webpack` and `tsc` only, for the rest we rely on predefined timeouts. + */ +const WatchCommand = exports.WatchCommand = { + description: 'Runs `kbn:watch` script for every project.', + name: 'watch', + run(projects, projectGraph) { + return _asyncToGenerator(function* () { + const projectsToWatch = new Map(); + for (const project of projects.values()) { + // We can't watch project that doesn't have `kbn:watch` script. + if (project.hasScript(watchScriptName)) { + projectsToWatch.set(project.name, project); + } + } + if (projectsToWatch.size === 0) { + _log.log.write(_chalk2.default.red(`\nThere are no projects to watch found. Make sure that projects define 'kbn:watch' script in 'package.json'.\n`)); + return; + } + const projectNames = Array.from(projectsToWatch.keys()); + _log.log.write(_chalk2.default.bold(_chalk2.default.green(`Running ${watchScriptName} scripts for [${projectNames.join(', ')}].`))); + // Kibana should always be run the last, so we don't rely on automatic + // topological batching and push it to the last one-entry batch manually. + const shouldWatchKibanaProject = projectsToWatch.delete(kibanaProjectName); + const batchedProjects = (0, _projects.topologicallyBatchProjects)(projectsToWatch, projectGraph); + if (shouldWatchKibanaProject) { + batchedProjects.push([projects.get(kibanaProjectName)]); + } + yield (0, _parallelize.parallelizeBatches)(batchedProjects, (() => { + var _ref = _asyncToGenerator(function* (pkg) { + const completionHint = yield (0, _watch.waitUntilWatchIsReady)(pkg.runScriptStreaming(watchScriptName).stdout); + _log.log.write(_chalk2.default.bold(`[${_chalk2.default.green(pkg.name)}] Initial build completed (${completionHint}).`)); + }); + + return function (_x) { + return _ref.apply(this, arguments); + }; + })()); + })(); + } +}; + +/***/ }), +/* 281 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.waitUntilWatchIsReady = waitUntilWatchIsReady; + +var _rxjs = __webpack_require__(462); + +var Rx = _interopRequireWildcard(_rxjs); + +var _operators = __webpack_require__(461); + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/** + * Number of milliseconds we wait before we fall back to the default watch handler. + */ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +const defaultHandlerDelay = 3000; +/** + * If default watch handler is used, then it's the number of milliseconds we wait for + * any build output before we consider watch task ready. + */ +const defaultHandlerReadinessTimeout = 2000; +function getWatchHandlers(buildOutput$, { handlerDelay = defaultHandlerDelay, handlerReadinessTimeout = defaultHandlerReadinessTimeout }) { + const typescriptHandler = buildOutput$.pipe((0, _operators.first)(data => data.includes('$ tsc')), (0, _operators.map)(() => buildOutput$.pipe((0, _operators.first)(data => data.includes('Compilation complete.')), (0, _operators.mapTo)('tsc')))); + const webpackHandler = buildOutput$.pipe((0, _operators.first)(data => data.includes('$ webpack')), (0, _operators.map)(() => buildOutput$.pipe((0, _operators.first)(data => data.includes('Chunk Names')), (0, _operators.mapTo)('webpack')))); + const defaultHandler = Rx.of(undefined).pipe((0, _operators.delay)(handlerReadinessTimeout), (0, _operators.map)(() => buildOutput$.pipe((0, _operators.timeout)(handlerDelay), (0, _operators.catchError)(() => Rx.of('timeout'))))); + return [typescriptHandler, webpackHandler, defaultHandler]; +} +function waitUntilWatchIsReady(stream, opts = {}) { + const buildOutput$ = new Rx.Subject(); + const onDataListener = data => buildOutput$.next(data.toString('utf-8')); + const onEndListener = () => buildOutput$.complete(); + const onErrorListener = e => buildOutput$.error(e); + stream.once('end', onEndListener); + stream.once('error', onErrorListener); + stream.on('data', onDataListener); + return Rx.race(getWatchHandlers(buildOutput$, opts)).pipe((0, _operators.mergeMap)(whenReady => whenReady), (0, _operators.finalize)(() => { + stream.removeListener('data', onDataListener); + stream.removeListener('end', onEndListener); + stream.removeListener('error', onErrorListener); + buildOutput$.complete(); + })).toPromise(); +} + +/***/ }), +/* 282 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.runCommand = undefined; + +let runCommand = exports.runCommand = (() => { + var _ref = _asyncToGenerator(function* (command, config) { + try { + _log.log.write(_chalk2.default.bold(`Running [${_chalk2.default.green(command.name)}] command from [${_chalk2.default.yellow(config.rootPath)}]:\n`)); + const projectPaths = (0, _config.getProjectPaths)(config.rootPath, config.options); + const projects = yield (0, _projects.getProjects)(config.rootPath, projectPaths, { + exclude: toArray(config.options.exclude), + include: toArray(config.options.include) + }); + if (projects.size === 0) { + _log.log.write(_chalk2.default.red(`There are no projects found. Double check project name(s) in '-i/--include' and '-e/--exclude' filters.\n`)); + return process.exit(1); + } + const projectGraph = (0, _projects.buildProjectGraph)(projects); + _log.log.write(_chalk2.default.bold(`Found [${_chalk2.default.green(projects.size.toString())}] projects:\n`)); + _log.log.write((0, _projects_tree.renderProjectsTree)(config.rootPath, projects)); + yield command.run(projects, projectGraph, config); + } catch (e) { + _log.log.write(_chalk2.default.bold.red(`\n[${command.name}] failed:\n`)); + if (e instanceof _errors.CliError) { + const msg = _chalk2.default.red(`CliError: ${e.message}\n`); + _log.log.write((0, _wrapAnsi2.default)(msg, 80)); + const keys = Object.keys(e.meta); + if (keys.length > 0) { + const metaOutput = keys.map(function (key) { + const value = e.meta[key]; + return `${key}: ${value}`; + }); + _log.log.write('Additional debugging info:\n'); + _log.log.write((0, _indentString2.default)(metaOutput.join('\n'), 3)); + } + } else { + _log.log.write(e.stack); + } + process.exit(1); + } + }); + + return function runCommand(_x, _x2) { + return _ref.apply(this, arguments); + }; +})(); + +var _chalk = __webpack_require__(26); + +var _chalk2 = _interopRequireDefault(_chalk); + +var _indentString = __webpack_require__(283); + +var _indentString2 = _interopRequireDefault(_indentString); + +var _wrapAnsi = __webpack_require__(284); + +var _wrapAnsi2 = _interopRequireDefault(_wrapAnsi); + +var _config = __webpack_require__(104); + +var _errors = __webpack_require__(101); + +var _log = __webpack_require__(40); + +var _projects = __webpack_require__(47); + +var _projects_tree = __webpack_require__(291); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + + +function toArray(value) { + if (value == null) { + return []; + } + return Array.isArray(value) ? value : [value]; +} + +/***/ }), +/* 283 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = (str, count, opts) => { + // Support older versions: use the third parameter as options.indent + // TODO: Remove the workaround in the next major version + const options = typeof opts === 'object' ? Object.assign({indent: ' '}, opts) : {indent: opts || ' '}; + count = count === undefined ? 1 : count; + + if (typeof str !== 'string') { + throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof str}\``); + } + + if (typeof count !== 'number') { + throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof count}\``); + } + + if (typeof options.indent !== 'string') { + throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\``); + } + + if (count === 0) { + return str; + } + + const regex = options.includeEmptyLines ? /^/mg : /^(?!\s*$)/mg; + return str.replace(regex, options.indent.repeat(count)); +} +; + + +/***/ }), +/* 284 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const stringWidth = __webpack_require__(285); +const stripAnsi = __webpack_require__(289); + +const ESCAPES = new Set([ + '\u001B', + '\u009B' +]); + +const END_CODE = 39; + +const ESCAPE_CODES = new Map([ + [0, 0], + [1, 22], + [2, 22], + [3, 23], + [4, 24], + [7, 27], + [8, 28], + [9, 29], + [30, 39], + [31, 39], + [32, 39], + [33, 39], + [34, 39], + [35, 39], + [36, 39], + [37, 39], + [90, 39], + [40, 49], + [41, 49], + [42, 49], + [43, 49], + [44, 49], + [45, 49], + [46, 49], + [47, 49] +]); + +const wrapAnsi = code => `${ESCAPES.values().next().value}[${code}m`; + +// Calculate the length of words split on ' ', ignoring +// the extra characters added by ansi escape codes +const wordLengths = str => str.split(' ').map(s => stringWidth(s)); + +// Wrap a long word across multiple rows +// Ansi escape codes do not count towards length +const wrapWord = (rows, word, cols) => { + const arr = Array.from(word); + + let insideEscape = false; + let visible = stringWidth(stripAnsi(rows[rows.length - 1])); + + for (const item of arr.entries()) { + const i = item[0]; + const char = item[1]; + const charLength = stringWidth(char); + + if (visible + charLength <= cols) { + rows[rows.length - 1] += char; + } else { + rows.push(char); + visible = 0; + } + + if (ESCAPES.has(char)) { + insideEscape = true; + } else if (insideEscape && char === 'm') { + insideEscape = false; + continue; + } + + if (insideEscape) { + continue; + } + + visible += charLength; + + if (visible === cols && i < arr.length - 1) { + rows.push(''); + visible = 0; + } + } + + // It's possible that the last row we copy over is only + // ansi escape characters, handle this edge-case + if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) { + rows[rows.length - 2] += rows.pop(); + } +}; + +// The wrap-ansi module can be invoked +// in either 'hard' or 'soft' wrap mode +// +// 'hard' will never allow a string to take up more +// than cols characters +// +// 'soft' allows long words to expand past the column length +const exec = (str, cols, opts) => { + const options = opts || {}; + + if (str.trim() === '') { + return options.trim === false ? str : str.trim(); + } + + let pre = ''; + let ret = ''; + let escapeCode; + + const lengths = wordLengths(str); + const words = str.split(' '); + const rows = ['']; + + for (const item of Array.from(words).entries()) { + const i = item[0]; + const word = item[1]; + + rows[rows.length - 1] = options.trim === false ? rows[rows.length - 1] : rows[rows.length - 1].trim(); + let rowLength = stringWidth(rows[rows.length - 1]); + + if (rowLength || word === '') { + if (rowLength === cols && options.wordWrap === false) { + // If we start with a new word but the current row length equals the length of the columns, add a new row + rows.push(''); + rowLength = 0; + } + + rows[rows.length - 1] += ' '; + rowLength++; + } + + // In 'hard' wrap mode, the length of a line is + // never allowed to extend past 'cols' + if (lengths[i] > cols && options.hard) { + if (rowLength) { + rows.push(''); + } + wrapWord(rows, word, cols); + continue; + } + + if (rowLength + lengths[i] > cols && rowLength > 0) { + if (options.wordWrap === false && rowLength < cols) { + wrapWord(rows, word, cols); + continue; + } + + rows.push(''); + } + + if (rowLength + lengths[i] > cols && options.wordWrap === false) { + wrapWord(rows, word, cols); + continue; + } + + rows[rows.length - 1] += word; + } + + pre = rows.map(r => options.trim === false ? r : r.trim()).join('\n'); + + for (const item of Array.from(pre).entries()) { + const i = item[0]; + const char = item[1]; + + ret += char; + + if (ESCAPES.has(char)) { + const code = parseFloat(/\d[^m]*/.exec(pre.slice(i, i + 4))); + escapeCode = code === END_CODE ? null : code; + } + + const code = ESCAPE_CODES.get(Number(escapeCode)); + + if (escapeCode && code) { + if (pre[i + 1] === '\n') { + ret += wrapAnsi(code); + } else if (char === '\n') { + ret += wrapAnsi(escapeCode); + } + } + } + + return ret; +}; + +// For each newline, invoke the method separately +module.exports = (str, cols, opts) => { + return String(str) + .normalize() + .split('\n') + .map(line => exec(line, cols, opts)) + .join('\n'); +}; + + +/***/ }), +/* 285 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const stripAnsi = __webpack_require__(286); +const isFullwidthCodePoint = __webpack_require__(288); + +module.exports = str => { + if (typeof str !== 'string' || str.length === 0) { + return 0; + } + + str = stripAnsi(str); + + let width = 0; + + for (let i = 0; i < str.length; i++) { + const code = str.codePointAt(i); + + // Ignore control characters + if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { + continue; + } + + // Ignore combining characters + if (code >= 0x300 && code <= 0x36F) { + continue; + } + + // Surrogates + if (code > 0xFFFF) { + i++; + } + + width += isFullwidthCodePoint(code) ? 2 : 1; + } + + return width; +}; + + +/***/ }), +/* 286 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const ansiRegex = __webpack_require__(287); + +module.exports = input => typeof input === 'string' ? input.replace(ansiRegex(), '') : input; + + +/***/ }), +/* 287 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = () => { + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, 'g'); +}; + + +/***/ }), +/* 288 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +/* eslint-disable yoda */ +module.exports = x => { + if (Number.isNaN(x)) { + return false; + } + + // code points are derived from: + // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt + if ( + x >= 0x1100 && ( + x <= 0x115f || // Hangul Jamo + x === 0x2329 || // LEFT-POINTING ANGLE BRACKET + x === 0x232a || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + (0x2e80 <= x && x <= 0x3247 && x !== 0x303f) || + // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + (0x3250 <= x && x <= 0x4dbf) || + // CJK Unified Ideographs .. Yi Radicals + (0x4e00 <= x && x <= 0xa4c6) || + // Hangul Jamo Extended-A + (0xa960 <= x && x <= 0xa97c) || + // Hangul Syllables + (0xac00 <= x && x <= 0xd7a3) || + // CJK Compatibility Ideographs + (0xf900 <= x && x <= 0xfaff) || + // Vertical Forms + (0xfe10 <= x && x <= 0xfe19) || + // CJK Compatibility Forms .. Small Form Variants + (0xfe30 <= x && x <= 0xfe6b) || + // Halfwidth and Fullwidth Forms + (0xff01 <= x && x <= 0xff60) || + (0xffe0 <= x && x <= 0xffe6) || + // Kana Supplement + (0x1b000 <= x && x <= 0x1b001) || + // Enclosed Ideographic Supplement + (0x1f200 <= x && x <= 0x1f251) || + // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + (0x20000 <= x && x <= 0x3fffd) + ) + ) { + return true; + } + + return false; +}; + + +/***/ }), +/* 289 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const ansiRegex = __webpack_require__(290); + +module.exports = input => typeof input === 'string' ? input.replace(ansiRegex(), '') : input; + + +/***/ }), +/* 290 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = () => { + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, 'g'); +}; + + +/***/ }), +/* 291 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.renderProjectsTree = renderProjectsTree; + +var _chalk = __webpack_require__(26); + +var _chalk2 = _interopRequireDefault(_chalk); + +var _path = __webpack_require__(5); + +var _path2 = _interopRequireDefault(_path); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +const projectKey = Symbol('__project'); +function renderProjectsTree(rootPath, projects) { + const projectsTree = buildProjectsTree(rootPath, projects); + return treeToString(createTreeStructure(projectsTree)); +} +function treeToString(tree) { + return [tree.name].concat(childrenToStrings(tree.children, '')).join('\n'); +} +function childrenToStrings(tree, treePrefix) { + if (tree === undefined) { + return []; + } + let strings = []; + tree.forEach((node, index) => { + const isLastNode = tree.length - 1 === index; + const nodePrefix = isLastNode ? '└── ' : '├── '; + const childPrefix = isLastNode ? ' ' : '│ '; + const childrenPrefix = treePrefix + childPrefix; + strings.push(`${treePrefix}${nodePrefix}${node.name}`); + strings = strings.concat(childrenToStrings(node.children, childrenPrefix)); + }); + return strings; +} +function createTreeStructure(tree) { + let name; + const children = []; + for (const [dir, project] of tree.entries()) { + // This is a leaf node (aka a project) + if (typeof project === 'string') { + name = _chalk2.default.green(project); + continue; + } + // If there's only one project and the key indicates it's a leaf node, we + // know that we're at a package folder that contains a package.json, so we + // "inline it" so we don't get unnecessary levels, i.e. we'll just see + // `foo` instead of `foo -> foo`. + if (project.size === 1 && project.has(projectKey)) { + const projectName = project.get(projectKey); + children.push({ + children: [], + name: dirOrProjectName(dir, projectName) + }); + continue; + } + const subtree = createTreeStructure(project); + // If the name is specified, we know there's a package at the "root" of the + // subtree itself. + if (subtree.name !== undefined) { + const projectName = subtree.name; + children.push({ + children: subtree.children, + name: dirOrProjectName(dir, projectName) + }); + continue; + } + // Special-case whenever we have one child, so we don't get unnecessary + // folders in the output. E.g. instead of `foo -> bar -> baz` we get + // `foo/bar/baz` instead. + if (subtree.children && subtree.children.length === 1) { + const child = subtree.children[0]; + const newName = _chalk2.default.dim(_path2.default.join(dir.toString(), child.name)); + children.push({ + children: child.children, + name: newName + }); + continue; + } + children.push({ + children: subtree.children, + name: _chalk2.default.dim(dir.toString()) + }); + } + return { name, children }; +} +function dirOrProjectName(dir, projectName) { + return dir === projectName ? _chalk2.default.green(dir) : _chalk2.default`{dim ${dir.toString()} ({reset.green ${projectName}})}`; +} +function buildProjectsTree(rootPath, projects) { + const tree = new Map(); + for (const project of projects.values()) { + if (rootPath === project.path) { + tree.set(projectKey, project.name); + } else { + const relativeProjectPath = _path2.default.relative(rootPath, project.path); + addProjectToTree(tree, relativeProjectPath.split(_path2.default.sep), project); + } + } + return tree; +} +function addProjectToTree(tree, pathParts, project) { + if (pathParts.length === 0) { + tree.set(projectKey, project.name); + } else { + const [currentDir, ...rest] = pathParts; + if (!tree.has(currentDir)) { + tree.set(currentDir, new Map()); + } + const subtree = tree.get(currentDir); + addProjectToTree(subtree, rest, project); + } +} + +/***/ }), +/* 292 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _build_production_projects = __webpack_require__(293); + +Object.defineProperty(exports, 'buildProductionProjects', { + enumerable: true, + get: function () { + return _build_production_projects.buildProductionProjects; + } +}); + +var _prepare_project_dependencies = __webpack_require__(460); + +Object.defineProperty(exports, 'prepareExternalProjectDependencies', { + enumerable: true, + get: function () { + return _prepare_project_dependencies.prepareExternalProjectDependencies; + } +}); + +/***/ }), +/* 293 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.buildProductionProjects = undefined; + +let buildProductionProjects = exports.buildProductionProjects = (() => { + var _ref = _asyncToGenerator(function* ({ kibanaRoot, buildRoots }) { + const projects = yield getProductionProjects(kibanaRoot); + const projectGraph = (0, _projects.buildProjectGraph)(projects); + const batchedProjects = (0, _projects.topologicallyBatchProjects)(projects, projectGraph); + const projectNames = [...projects.values()].map(function (project) { + return project.name; + }); + _log.log.write(`Preparing production build for [${projectNames.join(', ')}]`); + for (const batch of batchedProjects) { + for (const project of batch) { + yield deleteTarget(project); + yield buildProject(project); + for (const buildRoot of buildRoots) { + yield copyToBuild(project, kibanaRoot, buildRoot); + } + } + } + }); + + return function buildProductionProjects(_x) { + return _ref.apply(this, arguments); + }; +})(); +/** + * Returns the subset of projects that should be built into the production + * bundle. As we copy these into Kibana's `node_modules` during the build step, + * and let Kibana's build process be responsible for installing dependencies, + * we only include Kibana's transitive _production_ dependencies. + */ + + +let getProductionProjects = (() => { + var _ref2 = _asyncToGenerator(function* (rootPath) { + const projectPaths = (0, _config.getProjectPaths)(rootPath, {}); + const projects = yield (0, _projects.getProjects)(rootPath, projectPaths); + const productionProjects = (0, _projects.includeTransitiveProjects)([projects.get('kibana')], projects, { + onlyProductionDependencies: true + }); + // We remove Kibana, as we're already building Kibana + productionProjects.delete('kibana'); + return productionProjects; + }); + + return function getProductionProjects(_x2) { + return _ref2.apply(this, arguments); + }; +})(); + +let deleteTarget = (() => { + var _ref3 = _asyncToGenerator(function* (project) { + const targetDir = project.targetLocation; + if (yield (0, _fs.isDirectory)(targetDir)) { + yield (0, _del2.default)(targetDir, { force: true }); + } + }); + + return function deleteTarget(_x3) { + return _ref3.apply(this, arguments); + }; +})(); + +let buildProject = (() => { + var _ref4 = _asyncToGenerator(function* (project) { + if (project.hasScript('build')) { + yield project.runScript('build'); + } + }); + + return function buildProject(_x4) { + return _ref4.apply(this, arguments); + }; +})(); +/** + * Copy all the project's files from its "intermediate build directory" and + * into the build. The intermediate directory can either be the root of the + * project or some other location defined in the project's `package.json`. + * + * When copying all the files into the build, we exclude `node_modules` because + * we want the Kibana build to be responsible for actually installing all + * dependencies. The primary reason for allowing the Kibana build process to + * manage dependencies is that it will "dedupe" them, so we don't include + * unnecessary copies of dependencies. + */ + + +let copyToBuild = (() => { + var _ref5 = _asyncToGenerator(function* (project, kibanaRoot, buildRoot) { + // We want the package to have the same relative location within the build + const relativeProjectPath = (0, _path.relative)(kibanaRoot, project.path); + const buildProjectPath = (0, _path.resolve)(buildRoot, relativeProjectPath); + yield (0, _cpy2.default)(['**/*', '!node_modules/**'], buildProjectPath, { + cwd: project.getIntermediateBuildDirectory(), + dot: true, + nodir: true, + parents: true + }); + // If a project is using an intermediate build directory, we special-case our + // handling of `package.json`, as the project build process might have copied + // (a potentially modified) `package.json` into the intermediate build + // directory already. If so, we want to use that `package.json` as the basis + // for creating the production-ready `package.json`. If it's not present in + // the intermediate build, we fall back to using the project's already defined + // `package.json`. + const packageJson = (yield (0, _fs.isFile)((0, _path.join)(buildProjectPath, 'package.json'))) ? yield (0, _package_json.readPackageJson)(buildProjectPath) : project.json; + yield (0, _package_json.writePackageJson)(buildProjectPath, packageJson); + }); + + return function copyToBuild(_x5, _x6, _x7) { + return _ref5.apply(this, arguments); + }; +})(); + +var _cpy = __webpack_require__(294); + +var _cpy2 = _interopRequireDefault(_cpy); + +var _del = __webpack_require__(131); + +var _del2 = _interopRequireDefault(_del); + +var _path = __webpack_require__(5); + +var _config = __webpack_require__(104); + +var _fs = __webpack_require__(70); + +var _log = __webpack_require__(40); + +var _package_json = __webpack_require__(72); + +var _projects = __webpack_require__(47); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/***/ }), +/* 294 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const EventEmitter = __webpack_require__(63); +const path = __webpack_require__(5); +const arrify = __webpack_require__(133); +const globby = __webpack_require__(295); +const cpFile = __webpack_require__(453); +const CpyError = __webpack_require__(459); + +const preprocessSrcPath = (srcPath, options) => options.cwd ? path.resolve(options.cwd, srcPath) : srcPath; + +const preprocessDestPath = (srcPath, dest, options) => { + let basename = path.basename(srcPath); + const dirname = path.dirname(srcPath); + + if (typeof options.rename === 'string') { + basename = options.rename; + } else if (typeof options.rename === 'function') { + basename = options.rename(basename); + } + + if (options.cwd) { + dest = path.resolve(options.cwd, dest); + } + + if (options.parents) { + return path.join(dest, dirname, basename); + } + + return path.join(dest, basename); +}; + +module.exports = (src, dest, options = {}) => { + src = arrify(src); + + const progressEmitter = new EventEmitter(); + + if (src.length === 0 || !dest) { + const promise = Promise.reject(new CpyError('`files` and `destination` required')); + promise.on = (...args) => { + progressEmitter.on(...args); + return promise; + }; + return promise; + } + + const copyStatus = new Map(); + let completedFiles = 0; + let completedSize = 0; + + const promise = globby(src, options) + .catch(err => { + throw new CpyError(`Cannot glob \`${src}\`: ${err.message}`, err); + }) + .then(files => { + if (files.length === 0) { + progressEmitter.emit('progress', { + totalFiles: 0, + percent: 1, + completedFiles: 0, + completedSize: 0 + }); + } + + return Promise.all(files.map(srcPath => { + const from = preprocessSrcPath(srcPath, options); + const to = preprocessDestPath(srcPath, dest, options); + + return cpFile(from, to, options) + .on('progress', event => { + const fileStatus = copyStatus.get(event.src) || {written: 0, percent: 0}; + + if (fileStatus.written !== event.written || fileStatus.percent !== event.percent) { + completedSize -= fileStatus.written; + completedSize += event.written; + + if (event.percent === 1 && fileStatus.percent !== 1) { + completedFiles++; + } + + copyStatus.set(event.src, {written: event.written, percent: event.percent}); + + progressEmitter.emit('progress', { + totalFiles: files.length, + percent: completedFiles / files.length, + completedFiles, + completedSize + }); + } + }) + .catch(err => { + throw new CpyError(`Cannot copy from \`${from}\` to \`${to}\`: ${err.message}`, err); + }); + })); + }); + + promise.on = (...args) => { + progressEmitter.on(...args); + return promise; + }; + + return promise; +}; + + +/***/ }), +/* 295 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const arrayUnion = __webpack_require__(132); +const glob = __webpack_require__(48); +const fastGlob = __webpack_require__(134); +const dirGlob = __webpack_require__(448); +const gitignore = __webpack_require__(449); + +const DEFAULT_FILTER = () => false; + +const isNegative = pattern => pattern[0] === '!'; + +const assertPatternsInput = patterns => { + if (!patterns.every(x => typeof x === 'string')) { + throw new TypeError('Patterns must be a string or an array of strings'); + } +}; + +const generateGlobTasks = (patterns, taskOpts) => { + patterns = [].concat(patterns); + assertPatternsInput(patterns); + + const globTasks = []; + + taskOpts = Object.assign({ + ignore: [], + expandDirectories: true + }, taskOpts); + + patterns.forEach((pattern, i) => { + if (isNegative(pattern)) { + return; + } + + const ignore = patterns + .slice(i) + .filter(isNegative) + .map(pattern => pattern.slice(1)); + + const opts = Object.assign({}, taskOpts, { + ignore: taskOpts.ignore.concat(ignore) + }); + + globTasks.push({pattern, opts}); + }); + + return globTasks; +}; + +const globDirs = (task, fn) => { + let opts = {cwd: task.opts.cwd}; + + if (Array.isArray(task.opts.expandDirectories)) { + opts = Object.assign(opts, {files: task.opts.expandDirectories}); + } else if (typeof task.opts.expandDirectories === 'object') { + opts = Object.assign(opts, task.opts.expandDirectories); + } + + return fn(task.pattern, opts); +}; + +const getPattern = (task, fn) => task.opts.expandDirectories ? globDirs(task, fn) : [task.pattern]; + +module.exports = (patterns, opts) => { + let globTasks; + + try { + globTasks = generateGlobTasks(patterns, opts); + } catch (err) { + return Promise.reject(err); + } + + const getTasks = Promise.all(globTasks.map(task => Promise.resolve(getPattern(task, dirGlob)) + .then(globs => Promise.all(globs.map(glob => ({ + pattern: glob, + opts: task.opts + })))) + )) + .then(tasks => arrayUnion.apply(null, tasks)); + + const getFilter = () => { + return Promise.resolve( + opts && opts.gitignore ? + gitignore({cwd: opts.cwd, ignore: opts.ignore}) : + DEFAULT_FILTER + ); + }; + + return getFilter() + .then(filter => { + return getTasks + .then(tasks => Promise.all(tasks.map(task => fastGlob(task.pattern, task.opts)))) + .then(paths => arrayUnion.apply(null, paths)) + .then(paths => paths.filter(p => !filter(p))); + }); +}; + +module.exports.sync = (patterns, opts) => { + const globTasks = generateGlobTasks(patterns, opts); + + const getFilter = () => { + return opts && opts.gitignore ? + gitignore.sync({cwd: opts.cwd, ignore: opts.ignore}) : + DEFAULT_FILTER; + }; + + const tasks = globTasks.reduce((tasks, task) => { + const newTask = getPattern(task, dirGlob.sync).map(glob => ({ + pattern: glob, + opts: task.opts + })); + return tasks.concat(newTask); + }, []); + + const filter = getFilter(); + + return tasks.reduce( + (matches, task) => arrayUnion(matches, fastGlob.sync(task.pattern, task.opts)), + [] + ).filter(p => !filter(p)); +}; + +module.exports.generateGlobTasks = generateGlobTasks; + +module.exports.hasMagic = (patterns, opts) => [] + .concat(patterns) + .some(pattern => glob.hasMagic(pattern, opts)); + +module.exports.gitignore = gitignore; + + +/***/ }), +/* 296 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var merge2 = __webpack_require__(297); +var optionsManager = __webpack_require__(298); +var taskManager = __webpack_require__(299); +var reader_async_1 = __webpack_require__(433); +var reader_stream_1 = __webpack_require__(446); +var reader_sync_1 = __webpack_require__(447); +var arrayUtils = __webpack_require__(158); +/** + * Returns a set of works based on provided tasks and class of the reader. + */ +function getWorks(source, _Reader, opts) { + var patterns = [].concat(source); + var options = optionsManager.prepare(opts); + var tasks = taskManager.generate(patterns, options); + var reader = new _Reader(options); + return tasks.map(reader.read, reader); +} +/** + * Synchronous API. + */ +function sync(source, opts) { + var works = getWorks(source, reader_sync_1.default, opts); + return arrayUtils.flatten(works); +} +exports.sync = sync; +/** + * Asynchronous API. + */ +function async(source, opts) { + var works = getWorks(source, reader_async_1.default, opts); + return Promise.all(works).then(arrayUtils.flatten); +} +exports.async = async; +/** + * Stream API. + */ +function stream(source, opts) { + var works = getWorks(source, reader_stream_1.default, opts); + return merge2(works); +} +exports.stream = stream; + + +/***/ }), +/* 297 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +/* + * merge2 + * https://github.com/teambition/merge2 + * + * Copyright (c) 2014-2016 Teambition + * Licensed under the MIT license. + */ +const Stream = __webpack_require__(39) +const PassThrough = Stream.PassThrough +const slice = Array.prototype.slice + +module.exports = merge2 + +function merge2 () { + const streamsQueue = [] + let merging = false + let args = slice.call(arguments) + let options = args[args.length - 1] + + if (options && !Array.isArray(options) && options.pipe == null) args.pop() + else options = {} + + let doEnd = options.end !== false + if (options.objectMode == null) options.objectMode = true + if (options.highWaterMark == null) options.highWaterMark = 64 * 1024 + const mergedStream = PassThrough(options) + + function addStream () { + for (let i = 0, len = arguments.length; i < len; i++) { + streamsQueue.push(pauseStreams(arguments[i], options)) + } + mergeStream() + return this + } + + function mergeStream () { + if (merging) return + merging = true + + let streams = streamsQueue.shift() + if (!streams) { + process.nextTick(endStream) + return + } + if (!Array.isArray(streams)) streams = [streams] + + let pipesCount = streams.length + 1 + + function next () { + if (--pipesCount > 0) return + merging = false + mergeStream() + } + + function pipe (stream) { + function onend () { + stream.removeListener('merge2UnpipeEnd', onend) + stream.removeListener('end', onend) + next() + } + // skip ended stream + if (stream._readableState.endEmitted) return next() + + stream.on('merge2UnpipeEnd', onend) + stream.on('end', onend) + stream.pipe(mergedStream, {end: false}) + // compatible for old stream + stream.resume() + } + + for (let i = 0; i < streams.length; i++) pipe(streams[i]) + + next() + } + + function endStream () { + merging = false + // emit 'queueDrain' when all streams merged. + mergedStream.emit('queueDrain') + return doEnd && mergedStream.end() + } + + mergedStream.setMaxListeners(0) + mergedStream.add = addStream + mergedStream.on('unpipe', function (stream) { + stream.emit('merge2UnpipeEnd') + }) + + if (args.length) addStream.apply(null, args) + return mergedStream +} + +// check and pause streams for pipe. +function pauseStreams (streams, options) { + if (!Array.isArray(streams)) { + // Backwards-compat with old-style streams + if (!streams._readableState && streams.pipe) streams = streams.pipe(PassThrough(options)) + if (!streams._readableState || !streams.pause || !streams.pipe) { + throw new Error('Only readable stream can be merged.') + } + streams.pause() + } else { + for (let i = 0, len = streams.length; i < len; i++) streams[i] = pauseStreams(streams[i], options) + } + return streams +} + + +/***/ }), +/* 298 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +function prepare(options) { + var opts = Object.assign({ + cwd: process.cwd(), + deep: true, + ignore: [], + dot: false, + stats: false, + onlyFiles: true, + onlyDirectories: false, + followSymlinkedDirectories: true, + unique: true, + markDirectories: false, + absolute: false, + nobrace: false, + noglobstar: false, + noext: false, + nocase: false, + matchBase: false, + transform: null + }, options); + if (opts.onlyDirectories) { + opts.onlyFiles = false; + } + return opts; +} +exports.prepare = prepare; + + +/***/ }), +/* 299 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var objectUtils = __webpack_require__(300); +var patternUtils = __webpack_require__(105); +/** + * Returns grouped patterns by base directory of each pattern. + */ +function groupPatternsByParentDirectory(patterns) { + return patterns.reduce(function (collection, pattern) { + var parent = patternUtils.getBaseDirectory(pattern); + if (!collection[parent]) { + collection[parent] = []; + } + collection[parent].push(pattern); + return collection; + }, {}); +} +exports.groupPatternsByParentDirectory = groupPatternsByParentDirectory; +/** + * Convert positive patterns to tasks. + */ +function makePositiveTaskGroup(positive) { + return Object.keys(positive).reduce(function (collection, base) { + var positivePatterns = [].concat(positive[base]); + collection[base] = { + base: base, + patterns: positivePatterns, + positive: positivePatterns, + negative: [] + }; + return collection; + }, {}); +} +exports.makePositiveTaskGroup = makePositiveTaskGroup; +/** + * Convert negative patterns to tasks. + */ +function makeNegativeTaskGroup(negative) { + return Object.keys(negative).reduce(function (collection, base) { + var negativePatterns = [].concat(negative[base]); + collection[base] = { + base: base, + patterns: negativePatterns.map(patternUtils.convertToNegativePattern), + positive: [], + negative: negativePatterns + }; + return collection; + }, {}); +} +exports.makeNegativeTaskGroup = makeNegativeTaskGroup; +/** + * Returns merged positive and negative task groups. + * + * Just two rules: + * - If a positive task group has a pair in the negative group, then merge it. + * - If a negative task group has a global base task, then merge them to full positive group. + */ +function mergeTaskGroups(positive, negative) { + var group = positive; + var globalNegativePatterns = '.' in negative ? negative['.'].negative : []; + Object.keys(group).forEach(function (base) { + if (base in negative) { + group[base].patterns = group[base].patterns.concat(negative[base].negative.map(patternUtils.convertToNegativePattern)); + group[base].negative = group[base].negative.concat(negative[base].negative); + } + if (globalNegativePatterns.length !== 0) { + group[base].patterns = group[base].patterns.concat(globalNegativePatterns.map(patternUtils.convertToNegativePattern)); + group[base].negative = group[base].negative.concat(globalNegativePatterns); + } + }); + return group; +} +exports.mergeTaskGroups = mergeTaskGroups; +/** + * Returns builded tasks for provided patterns groups. + */ +function makeTasks(positive, negative) { + var positiveTaskGroup = makePositiveTaskGroup(positive); + var negativeTaskGroup = makeNegativeTaskGroup(negative); + var groups = mergeTaskGroups(positiveTaskGroup, negativeTaskGroup); + return objectUtils.values(groups); +} +exports.makeTasks = makeTasks; +/** + * Generate tasks for provided patterns based on base directory of each pattern. + */ +function generate(patterns, options) { + var unixPatterns = patterns.map(patternUtils.unixifyPattern); + var positive = patternUtils.getPositivePatterns(unixPatterns); + if (positive.length === 0) { + return []; + } + var ignore = options.ignore; + var negative = patternUtils.getNegativePatterns(unixPatterns) + .map(patternUtils.convertToPositivePattern) + .concat(ignore) + .map(patternUtils.trimTrailingSlashGlobStar); + var positiveGroup = groupPatternsByParentDirectory(positive); + var negativeGroup = groupPatternsByParentDirectory(negative); + // When we have a global group – there is no reason to divide the patterns into independent tasks because the first task covers the rest. + if ('.' in positiveGroup) { + var task = { + base: '.', + patterns: [].concat(positive, negative.map(patternUtils.convertToNegativePattern)), + positive: positive, + negative: negative + }; + return [task]; + } + return makeTasks(positiveGroup, negativeGroup); +} +exports.generate = generate; + + +/***/ }), +/* 300 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +function values(obj) { + return Object.keys(obj).map(function (key) { return obj[key]; }); +} +exports.values = values; + + +/***/ }), +/* 301 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var path = __webpack_require__(5); +var isglob = __webpack_require__(302); +var pathDirname = __webpack_require__(304); +var isWin32 = __webpack_require__(114).platform() === 'win32'; + +module.exports = function globParent(str) { + // flip windows path separators + if (isWin32 && str.indexOf('/') < 0) str = str.split('\\').join('/'); + + // special case for strings ending in enclosure containing path separator + if (/[\{\[].*[\/]*.*[\}\]]$/.test(str)) str += '/'; + + // preserves full path in case of trailing path separator + str += 'a'; + + // remove path parts that are globby + do {str = pathDirname.posix(str)} + while (isglob(str) || /(^|[^\\])([\{\[]|\([^\)]+$)/.test(str)); + + // remove escape chars and return result + return str.replace(/\\([\*\?\|\[\]\(\)\{\}])/g, '$1'); +}; + + +/***/ }), +/* 302 */ +/***/ (function(module, exports, __webpack_require__) { + +/*! + * is-glob + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. + */ + +var isExtglob = __webpack_require__(303); + +module.exports = function isGlob(str) { + if (typeof str !== 'string' || str === '') { + return false; + } + + if (isExtglob(str)) return true; + + var regex = /(\\).|([*?]|\[.*\]|\{.*\}|\(.*\|.*\)|^!)/; + var match; + + while ((match = regex.exec(str))) { + if (match[2]) return true; + str = str.slice(match.index + match[0].length); + } + return false; +}; + + +/***/ }), +/* 303 */ +/***/ (function(module, exports) { + +/*! + * is-extglob + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. + */ + +module.exports = function isExtglob(str) { + if (typeof str !== 'string' || str === '') { + return false; + } + + var match; + while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) { + if (match[2]) return true; + str = str.slice(match.index + match[0].length); + } + + return false; +}; + + +/***/ }), +/* 304 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var path = __webpack_require__(5); +var inspect = __webpack_require__(14).inspect; + +function assertPath(path) { + if (typeof path !== 'string') { + throw new TypeError('Path must be a string. Received ' + inspect(path)); + } +} + +function posix(path) { + assertPath(path); + if (path.length === 0) + return '.'; + var code = path.charCodeAt(0); + var hasRoot = (code === 47/*/*/); + var end = -1; + var matchedSlash = true; + for (var i = path.length - 1; i >= 1; --i) { + code = path.charCodeAt(i); + if (code === 47/*/*/) { + if (!matchedSlash) { + end = i; + break; + } + } else { + // We saw the first non-path separator + matchedSlash = false; + } + } + + if (end === -1) + return hasRoot ? '/' : '.'; + if (hasRoot && end === 1) + return '//'; + return path.slice(0, end); +} + +function win32(path) { + assertPath(path); + var len = path.length; + if (len === 0) + return '.'; + var rootEnd = -1; + var end = -1; + var matchedSlash = true; + var offset = 0; + var code = path.charCodeAt(0); + + // Try to match a root + if (len > 1) { + if (code === 47/*/*/ || code === 92/*\*/) { + // Possible UNC root + + rootEnd = offset = 1; + + code = path.charCodeAt(1); + if (code === 47/*/*/ || code === 92/*\*/) { + // Matched double path separator at beginning + var j = 2; + var last = j; + // Match 1 or more non-path separators + for (; j < len; ++j) { + code = path.charCodeAt(j); + if (code === 47/*/*/ || code === 92/*\*/) + break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more path separators + for (; j < len; ++j) { + code = path.charCodeAt(j); + if (code !== 47/*/*/ && code !== 92/*\*/) + break; + } + if (j < len && j !== last) { + // Matched! + last = j; + // Match 1 or more non-path separators + for (; j < len; ++j) { + code = path.charCodeAt(j); + if (code === 47/*/*/ || code === 92/*\*/) + break; + } + if (j === len) { + // We matched a UNC root only + return path; + } + if (j !== last) { + // We matched a UNC root with leftovers + + // Offset by 1 to include the separator after the UNC root to + // treat it as a "normal root" on top of a (UNC) root + rootEnd = offset = j + 1; + } + } + } + } + } else if ((code >= 65/*A*/ && code <= 90/*Z*/) || + (code >= 97/*a*/ && code <= 122/*z*/)) { + // Possible device root + + code = path.charCodeAt(1); + if (path.charCodeAt(1) === 58/*:*/) { + rootEnd = offset = 2; + if (len > 2) { + code = path.charCodeAt(2); + if (code === 47/*/*/ || code === 92/*\*/) + rootEnd = offset = 3; + } + } + } + } else if (code === 47/*/*/ || code === 92/*\*/) { + return path[0]; + } + + for (var i = len - 1; i >= offset; --i) { + code = path.charCodeAt(i); + if (code === 47/*/*/ || code === 92/*\*/) { + if (!matchedSlash) { + end = i; + break; + } + } else { + // We saw the first non-path separator + matchedSlash = false; + } + } + + if (end === -1) { + if (rootEnd === -1) + return '.'; + else + end = rootEnd; + } + return path.slice(0, end); +} + +module.exports = process.platform === 'win32' ? win32 : posix; +module.exports.posix = posix; +module.exports.win32 = win32; + + +/***/ }), +/* 305 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Module dependencies + */ + +var util = __webpack_require__(14); +var braces = __webpack_require__(306); +var toRegex = __webpack_require__(43); +var extend = __webpack_require__(20); + +/** + * Local dependencies + */ + +var compilers = __webpack_require__(410); +var parsers = __webpack_require__(429); +var cache = __webpack_require__(430); +var utils = __webpack_require__(431); +var MAX_LENGTH = 1024 * 64; + +/** + * The main function takes a list of strings and one or more + * glob patterns to use for matching. + * + * ```js + * var mm = require('micromatch'); + * mm(list, patterns[, options]); + * + * console.log(mm(['a.js', 'a.txt'], ['*.js'])); + * //=> [ 'a.js' ] + * ``` + * @param {Array} `list` A list of strings to match + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of matches + * @summary false + * @api public + */ + +function micromatch(list, patterns, options) { + patterns = utils.arrayify(patterns); + list = utils.arrayify(list); + + var len = patterns.length; + if (list.length === 0 || len === 0) { + return []; + } + + if (len === 1) { + return micromatch.match(list, patterns[0], options); + } + + var omit = []; + var keep = []; + var idx = -1; + + while (++idx < len) { + var pattern = patterns[idx]; + + if (typeof pattern === 'string' && pattern.charCodeAt(0) === 33 /* ! */) { + omit.push.apply(omit, micromatch.match(list, pattern.slice(1), options)); + } else { + keep.push.apply(keep, micromatch.match(list, pattern, options)); + } + } + + var matches = utils.diff(keep, omit); + if (!options || options.nodupes !== false) { + return utils.unique(matches); + } + + return matches; +} + +/** + * Similar to the main function, but `pattern` must be a string. + * + * ```js + * var mm = require('micromatch'); + * mm.match(list, pattern[, options]); + * + * console.log(mm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a')); + * //=> ['a.a', 'a.aa'] + * ``` + * @param {Array} `list` Array of strings to match + * @param {String} `pattern` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of matches + * @api public + */ + +micromatch.match = function(list, pattern, options) { + if (Array.isArray(pattern)) { + throw new TypeError('expected pattern to be a string'); + } + + var unixify = utils.unixify(options); + var isMatch = memoize('match', pattern, options, micromatch.matcher); + var matches = []; + + list = utils.arrayify(list); + var len = list.length; + var idx = -1; + + while (++idx < len) { + var ele = list[idx]; + if (ele === pattern || isMatch(ele)) { + matches.push(utils.value(ele, unixify, options)); + } + } + + // if no options were passed, uniquify results and return + if (typeof options === 'undefined') { + return utils.unique(matches); + } + + if (matches.length === 0) { + if (options.failglob === true) { + throw new Error('no matches found for "' + pattern + '"'); + } + if (options.nonull === true || options.nullglob === true) { + return [options.unescape ? utils.unescape(pattern) : pattern]; + } + } + + // if `opts.ignore` was defined, diff ignored list + if (options.ignore) { + matches = micromatch.not(matches, options.ignore, options); + } + + return options.nodupes !== false ? utils.unique(matches) : matches; +}; + +/** + * Returns true if the specified `string` matches the given glob `pattern`. + * + * ```js + * var mm = require('micromatch'); + * mm.isMatch(string, pattern[, options]); + * + * console.log(mm.isMatch('a.a', '*.a')); + * //=> true + * console.log(mm.isMatch('a.b', '*.a')); + * //=> false + * ``` + * @param {String} `string` String to match + * @param {String} `pattern` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if the string matches the glob pattern. + * @api public + */ + +micromatch.isMatch = function(str, pattern, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + } + + if (isEmptyString(str) || isEmptyString(pattern)) { + return false; + } + + var equals = utils.equalsPattern(options); + if (equals(str)) { + return true; + } + + var isMatch = memoize('isMatch', pattern, options, micromatch.matcher); + return isMatch(str); +}; + +/** + * Returns true if some of the strings in the given `list` match any of the + * given glob `patterns`. + * + * ```js + * var mm = require('micromatch'); + * mm.some(list, patterns[, options]); + * + * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // true + * console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +micromatch.some = function(list, patterns, options) { + if (typeof list === 'string') { + list = [list]; + } + for (var i = 0; i < list.length; i++) { + if (micromatch(list[i], patterns, options).length === 1) { + return true; + } + } + return false; +}; + +/** + * Returns true if every string in the given `list` matches + * any of the given glob `patterns`. + * + * ```js + * var mm = require('micromatch'); + * mm.every(list, patterns[, options]); + * + * console.log(mm.every('foo.js', ['foo.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // false + * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +micromatch.every = function(list, patterns, options) { + if (typeof list === 'string') { + list = [list]; + } + for (var i = 0; i < list.length; i++) { + if (micromatch(list[i], patterns, options).length !== 1) { + return false; + } + } + return true; +}; + +/** + * Returns true if **any** of the given glob `patterns` + * match the specified `string`. + * + * ```js + * var mm = require('micromatch'); + * mm.any(string, patterns[, options]); + * + * console.log(mm.any('a.a', ['b.*', '*.a'])); + * //=> true + * console.log(mm.any('a.a', 'b.*')); + * //=> false + * ``` + * @param {String|Array} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +micromatch.any = function(str, patterns, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + } + + if (isEmptyString(str) || isEmptyString(patterns)) { + return false; + } + + if (typeof patterns === 'string') { + patterns = [patterns]; + } + + for (var i = 0; i < patterns.length; i++) { + if (micromatch.isMatch(str, patterns[i], options)) { + return true; + } + } + return false; +}; + +/** + * Returns true if **all** of the given `patterns` match + * the specified string. + * + * ```js + * var mm = require('micromatch'); + * mm.all(string, patterns[, options]); + * + * console.log(mm.all('foo.js', ['foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); + * // false + * + * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); + * // true + * ``` + * @param {String|Array} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + +micromatch.all = function(str, patterns, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + } + if (typeof patterns === 'string') { + patterns = [patterns]; + } + for (var i = 0; i < patterns.length; i++) { + if (!micromatch.isMatch(str, patterns[i], options)) { + return false; + } + } + return true; +}; + +/** + * Returns a list of strings that _**do not match any**_ of the given `patterns`. + * + * ```js + * var mm = require('micromatch'); + * mm.not(list, patterns[, options]); + * + * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); + * //=> ['b.b', 'c.c'] + * ``` + * @param {Array} `list` Array of strings to match. + * @param {String|Array} `patterns` One or more glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of strings that **do not match** the given patterns. + * @api public + */ + +micromatch.not = function(list, patterns, options) { + var opts = extend({}, options); + var ignore = opts.ignore; + delete opts.ignore; + + var unixify = utils.unixify(opts); + list = utils.arrayify(list).map(unixify); + + var matches = utils.diff(list, micromatch(list, patterns, opts)); + if (ignore) { + matches = utils.diff(matches, micromatch(list, ignore)); + } + + return opts.nodupes !== false ? utils.unique(matches) : matches; +}; + +/** + * Returns true if the given `string` contains the given pattern. Similar + * to [.isMatch](#isMatch) but the pattern can match any part of the string. + * + * ```js + * var mm = require('micromatch'); + * mm.contains(string, pattern[, options]); + * + * console.log(mm.contains('aa/bb/cc', '*b')); + * //=> true + * console.log(mm.contains('aa/bb/cc', '*d')); + * //=> false + * ``` + * @param {String} `str` The string to match. + * @param {String|Array} `patterns` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if the patter matches any part of `str`. + * @api public + */ + +micromatch.contains = function(str, patterns, options) { + if (typeof str !== 'string') { + throw new TypeError('expected a string: "' + util.inspect(str) + '"'); + } + + if (typeof patterns === 'string') { + if (isEmptyString(str) || isEmptyString(patterns)) { + return false; + } + + var equals = utils.equalsPattern(patterns, options); + if (equals(str)) { + return true; + } + var contains = utils.containsPattern(patterns, options); + if (contains(str)) { + return true; + } + } + + var opts = extend({}, options, {contains: true}); + return micromatch.any(str, patterns, opts); +}; + +/** + * Returns true if the given pattern and options should enable + * the `matchBase` option. + * @return {Boolean} + * @api private + */ + +micromatch.matchBase = function(pattern, options) { + if (pattern && pattern.indexOf('/') !== -1 || !options) return false; + return options.basename === true || options.matchBase === true; +}; + +/** + * Filter the keys of the given object with the given `glob` pattern + * and `options`. Does not attempt to match nested keys. If you need this feature, + * use [glob-object][] instead. + * + * ```js + * var mm = require('micromatch'); + * mm.matchKeys(object, patterns[, options]); + * + * var obj = { aa: 'a', ab: 'b', ac: 'c' }; + * console.log(mm.matchKeys(obj, '*b')); + * //=> { ab: 'b' } + * ``` + * @param {Object} `object` The object with keys to filter. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Object} Returns an object with only keys that match the given patterns. + * @api public + */ + +micromatch.matchKeys = function(obj, patterns, options) { + if (!utils.isObject(obj)) { + throw new TypeError('expected the first argument to be an object'); + } + var keys = micromatch(Object.keys(obj), patterns, options); + return utils.pick(obj, keys); +}; + +/** + * Returns a memoized matcher function from the given glob `pattern` and `options`. + * The returned function takes a string to match as its only argument and returns + * true if the string is a match. + * + * ```js + * var mm = require('micromatch'); + * mm.matcher(pattern[, options]); + * + * var isMatch = mm.matcher('*.!(*a)'); + * console.log(isMatch('a.a')); + * //=> false + * console.log(isMatch('a.b')); + * //=> true + * ``` + * @param {String} `pattern` Glob pattern + * @param {Object} `options` See available [options](#options) for changing how matches are performed. + * @return {Function} Returns a matcher function. + * @api public + */ + +micromatch.matcher = function matcher(pattern, options) { + if (Array.isArray(pattern)) { + return compose(pattern, options, matcher); + } + + // if pattern is a regex + if (pattern instanceof RegExp) { + return test(pattern); + } + + // if pattern is invalid + if (!utils.isString(pattern)) { + throw new TypeError('expected pattern to be an array, string or regex'); + } + + // if pattern is a non-glob string + if (!utils.hasSpecialChars(pattern)) { + if (options && options.nocase === true) { + pattern = pattern.toLowerCase(); + } + return utils.matchPath(pattern, options); + } + + // if pattern is a glob string + var re = micromatch.makeRe(pattern, options); + + // if `options.matchBase` or `options.basename` is defined + if (micromatch.matchBase(pattern, options)) { + return utils.matchBasename(re, options); + } + + function test(regex) { + var equals = utils.equalsPattern(options); + var unixify = utils.unixify(options); + + return function(str) { + if (equals(str)) { + return true; + } + + if (regex.test(unixify(str))) { + return true; + } + return false; + }; + } + + var fn = test(re); + Object.defineProperty(fn, 'result', { + configurable: true, + enumerable: false, + value: re.result + }); + return fn; +}; + +/** + * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match. + * + * ```js + * var mm = require('micromatch'); + * mm.capture(pattern, string[, options]); + * + * console.log(mm.capture('test/*.js', 'test/foo.js')); + * //=> ['foo'] + * console.log(mm.capture('test/*.js', 'foo/bar.css')); + * //=> null + * ``` + * @param {String} `pattern` Glob pattern to use for matching. + * @param {String} `string` String to match + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`. + * @api public + */ + +micromatch.capture = function(pattern, str, options) { + var re = micromatch.makeRe(pattern, extend({capture: true}, options)); + var unixify = utils.unixify(options); + + function match() { + return function(string) { + var match = re.exec(unixify(string)); + if (!match) { + return null; + } + + return match.slice(1); + }; + } + + var capture = memoize('capture', pattern, options, match); + return capture(str); +}; + +/** + * Create a regular expression from the given glob `pattern`. + * + * ```js + * var mm = require('micromatch'); + * mm.makeRe(pattern[, options]); + * + * console.log(mm.makeRe('*.js')); + * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ + * ``` + * @param {String} `pattern` A glob pattern to convert to regex. + * @param {Object} `options` See available [options](#options) for changing how matches are performed. + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + +micromatch.makeRe = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected pattern to be a string'); + } + + if (pattern.length > MAX_LENGTH) { + throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); + } + + function makeRe() { + var result = micromatch.create(pattern, options); + var ast_array = []; + var output = result.map(function(obj) { + obj.ast.state = obj.state; + ast_array.push(obj.ast); + return obj.output; + }); + + var regex = toRegex(output.join('|'), options); + Object.defineProperty(regex, 'result', { + configurable: true, + enumerable: false, + value: ast_array + }); + return regex; + } + + return memoize('makeRe', pattern, options, makeRe); +}; + +/** + * Expand the given brace `pattern`. + * + * ```js + * var mm = require('micromatch'); + * console.log(mm.braces('foo/{a,b}/bar')); + * //=> ['foo/(a|b)/bar'] + * + * console.log(mm.braces('foo/{a,b}/bar', {expand: true})); + * //=> ['foo/(a|b)/bar'] + * ``` + * @param {String} `pattern` String with brace pattern to expand. + * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options. + * @return {Array} + * @api public + */ + +micromatch.braces = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } + + function expand() { + if (options && options.nobrace === true) return [pattern]; + if (!/\{.*\}/.test(pattern)) return [pattern]; + // if (/[!@*?+]\{/.test(pattern)) { + // options = utils.extend({}, options, {expand: true}); + // } + return braces(pattern, options); + } + + return memoize('braces', pattern, options, expand); +}; + +/** + * Proxy to the [micromatch.braces](#method), for parity with + * minimatch. + */ + +micromatch.braceExpand = function(pattern, options) { + var opts = extend({}, options, {expand: true}); + return micromatch.braces(pattern, opts); +}; + +/** + * Parses the given glob `pattern` and returns an array of abstract syntax + * trees (ASTs), with the compiled `output` and optional source `map` on + * each AST. + * + * ```js + * var mm = require('micromatch'); + * mm.create(pattern[, options]); + * + * console.log(mm.create('abc/*.js')); + * // [{ options: { source: 'string', sourcemap: true }, + * // state: {}, + * // compilers: + * // { ... }, + * // output: '(\\.[\\\\\\/])?abc\\/(?!\\.)(?=.)[^\\/]*?\\.js', + * // ast: + * // { type: 'root', + * // errors: [], + * // nodes: + * // [ ... ], + * // dot: false, + * // input: 'abc/*.js' }, + * // parsingErrors: [], + * // map: + * // { version: 3, + * // sources: [ 'string' ], + * // names: [], + * // mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE', + * // sourcesContent: [ 'abc/*.js' ] }, + * // position: { line: 1, column: 28 }, + * // content: {}, + * // files: {}, + * // idx: 6 }] + * ``` + * @param {String} `pattern` Glob pattern to parse and compile. + * @param {Object} `options` Any [options](#options) to change how parsing and compiling is performed. + * @return {Object} Returns an object with the parsed AST, compiled string and optional source map. + * @api public + */ + +micromatch.create = function(pattern, options) { + return memoize('create', pattern, options, function() { + function create(str, opts) { + return micromatch.compile(micromatch.parse(str, opts), opts); + } + + pattern = micromatch.braces(pattern, options); + var len = pattern.length; + var idx = -1; + var res = []; + + while (++idx < len) { + res.push(create(pattern[idx], options)); + } + return res; + }); +}; + +/** + * Parse the given `str` with the given `options`. + * + * ```js + * var mm = require('micromatch'); + * mm.parse(pattern[, options]); + * + * var ast = mm.parse('a/{b,c}/d'); + * console.log(ast); + * // { type: 'root', + * // errors: [], + * // input: 'a/{b,c}/d', + * // nodes: + * // [ { type: 'bos', val: '' }, + * // { type: 'text', val: 'a/' }, + * // { type: 'brace', + * // nodes: + * // [ { type: 'brace.open', val: '{' }, + * // { type: 'text', val: 'b,c' }, + * // { type: 'brace.close', val: '}' } ] }, + * // { type: 'text', val: '/d' }, + * // { type: 'eos', val: '' } ] } + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {Object} Returns an AST + * @api public + */ + +micromatch.parse = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } + + function parse() { + var snapdragon = utils.instantiate(null, options); + parsers(snapdragon, options); + + var ast = snapdragon.parse(pattern, options); + utils.define(ast, 'snapdragon', snapdragon); + ast.input = pattern; + return ast; + } + + return memoize('parse', pattern, options, parse); +}; + +/** + * Compile the given `ast` or string with the given `options`. + * + * ```js + * var mm = require('micromatch'); + * mm.compile(ast[, options]); + * + * var ast = mm.parse('a/{b,c}/d'); + * console.log(mm.compile(ast)); + * // { options: { source: 'string' }, + * // state: {}, + * // compilers: + * // { eos: [Function], + * // noop: [Function], + * // bos: [Function], + * // brace: [Function], + * // 'brace.open': [Function], + * // text: [Function], + * // 'brace.close': [Function] }, + * // output: [ 'a/(b|c)/d' ], + * // ast: + * // { ... }, + * // parsingErrors: [] } + * ``` + * @param {Object|String} `ast` + * @param {Object} `options` + * @return {Object} Returns an object that has an `output` property with the compiled string. + * @api public + */ + +micromatch.compile = function(ast, options) { + if (typeof ast === 'string') { + ast = micromatch.parse(ast, options); + } + + return memoize('compile', ast.input, options, function() { + var snapdragon = utils.instantiate(ast, options); + compilers(snapdragon, options); + return snapdragon.compile(ast, options); + }); +}; + +/** + * Clear the regex cache. + * + * ```js + * mm.clearCache(); + * ``` + * @api public + */ + +micromatch.clearCache = function() { + micromatch.cache.caches = {}; +}; + +/** + * Returns true if the given value is effectively an empty string + */ + +function isEmptyString(val) { + return String(val) === '' || String(val) === './'; +} + +/** + * Compose a matcher function with the given patterns. + * This allows matcher functions to be compiled once and + * called multiple times. + */ + +function compose(patterns, options, matcher) { + var matchers; + + return memoize('compose', String(patterns), options, function() { + return function(file) { + // delay composition until it's invoked the first time, + // after that it won't be called again + if (!matchers) { + matchers = []; + for (var i = 0; i < patterns.length; i++) { + matchers.push(matcher(patterns[i], options)); + } + } + + var len = matchers.length; + while (len--) { + if (matchers[len](file) === true) { + return true; + } + } + return false; + }; + }); +} + +/** + * Memoize a generated regex or function. A unique key is generated + * from the `type` (usually method name), the `pattern`, and + * user-defined options. + */ + +function memoize(type, pattern, options, fn) { + var key = utils.createKey(type + '=' + pattern, options); + + if (options && options.cache === false) { + return fn(pattern, options); + } + + if (cache.has(type, key)) { + return cache.get(type, key); + } + + var val = fn(pattern, options); + cache.set(type, key, val); + return val; +} + +/** + * Expose compiler, parser and cache on `micromatch` + */ + +micromatch.compilers = compilers; +micromatch.parsers = parsers; +micromatch.caches = cache.caches; + +/** + * Expose `micromatch` + * @type {Function} + */ + +module.exports = micromatch; + + +/***/ }), +/* 306 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Module dependencies + */ + +var toRegex = __webpack_require__(43); +var unique = __webpack_require__(65); +var extend = __webpack_require__(20); +var define = __webpack_require__(44); + +/** + * Local dependencies + */ + +var compilers = __webpack_require__(135); +var parsers = __webpack_require__(138); +var Braces = __webpack_require__(329); +var utils = __webpack_require__(75); +var MAX_LENGTH = 1024 * 64; +var cache = {}; + +/** + * Convert the given `braces` pattern into a regex-compatible string. By default, only one string is generated for every input string. Set `options.expand` to true to return an array of patterns (similar to Bash or minimatch. Before using `options.expand`, it's recommended that you read the [performance notes](#performance)). + * + * ```js + * var braces = require('braces'); + * console.log(braces('{a,b,c}')); + * //=> ['(a|b|c)'] + * + * console.log(braces('{a,b,c}', {expand: true})); + * //=> ['a', 'b', 'c'] + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {String} + * @api public + */ + +function braces(pattern, options) { + var key = utils.createKey(String(pattern), options); + var arr = []; + + var disabled = options && options.cache === false; + if (!disabled && cache.hasOwnProperty(key)) { + return cache[key]; + } + + if (Array.isArray(pattern)) { + for (var i = 0; i < pattern.length; i++) { + arr.push.apply(arr, braces.create(pattern[i], options)); + } + } else { + arr = braces.create(pattern, options); + } + + if (options && options.nodupes === true) { + arr = unique(arr); + } + + if (!disabled) { + cache[key] = arr; + } + return arr; +} + +/** + * Expands a brace pattern into an array. This method is called by the main [braces](#braces) function when `options.expand` is true. Before using this method it's recommended that you read the [performance notes](#performance)) and advantages of using [.optimize](#optimize) instead. + * + * ```js + * var braces = require('braces'); + * console.log(braces.expand('a/{b,c}/d')); + * //=> ['a/b/d', 'a/c/d']; + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.expand = function(pattern, options) { + return braces.create(pattern, extend({}, options, {expand: true})); +}; + +/** + * Expands a brace pattern into a regex-compatible, optimized string. This method is called by the main [braces](#braces) function by default. + * + * ```js + * var braces = require('braces'); + * console.log(braces.expand('a/{b,c}/d')); + * //=> ['a/(b|c)/d'] + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.optimize = function(pattern, options) { + return braces.create(pattern, options); +}; + +/** + * Processes a brace pattern and returns either an expanded array (if `options.expand` is true), a highly optimized regex-compatible string. This method is called by the main [braces](#braces) function. + * + * ```js + * var braces = require('braces'); + * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) + * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + +braces.create = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } + + if (pattern.length >= MAX_LENGTH) { + throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); + } + + function create() { + if (pattern === '' || pattern.length < 3) { + return [pattern]; + } + + if (utils.isEmptySets(pattern)) { + return []; + } + + if (utils.isQuotedString(pattern)) { + return [pattern.slice(1, -1)]; + } + + var proto = new Braces(options); + var result = !options || options.expand !== true + ? proto.optimize(pattern, options) + : proto.expand(pattern, options); + + // get the generated pattern(s) + var arr = result.output; + + // filter out empty strings if specified + if (options && options.noempty === true) { + arr = arr.filter(Boolean); + } + + // filter out duplicates if specified + if (options && options.nodupes === true) { + arr = unique(arr); + } + + define(arr, 'result', result); + return arr; + } + + return memoize('create', pattern, options, create); +}; + +/** + * Create a regular expression from the given string `pattern`. + * + * ```js + * var braces = require('braces'); + * + * console.log(braces.makeRe('id-{200..300}')); + * //=> /^(?:id-(20[0-9]|2[1-9][0-9]|300))$/ + * ``` + * @param {String} `pattern` The pattern to convert to regex. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ + +braces.makeRe = function(pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('expected a string'); + } + + if (pattern.length >= MAX_LENGTH) { + throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters'); + } + + function makeRe() { + var arr = braces(pattern, options); + var opts = extend({strictErrors: false}, options); + return toRegex(arr, opts); + } + + return memoize('makeRe', pattern, options, makeRe); +}; + +/** + * Parse the given `str` with the given `options`. + * + * ```js + * var braces = require('braces'); + * var ast = braces.parse('a/{b,c}/d'); + * console.log(ast); + * // { type: 'root', + * // errors: [], + * // input: 'a/{b,c}/d', + * // nodes: + * // [ { type: 'bos', val: '' }, + * // { type: 'text', val: 'a/' }, + * // { type: 'brace', + * // nodes: + * // [ { type: 'brace.open', val: '{' }, + * // { type: 'text', val: 'b,c' }, + * // { type: 'brace.close', val: '}' } ] }, + * // { type: 'text', val: '/d' }, + * // { type: 'eos', val: '' } ] } + * ``` + * @param {String} `pattern` Brace pattern to parse + * @param {Object} `options` + * @return {Object} Returns an AST + * @api public + */ + +braces.parse = function(pattern, options) { + var proto = new Braces(options); + return proto.parse(pattern, options); +}; + +/** + * Compile the given `ast` or string with the given `options`. + * + * ```js + * var braces = require('braces'); + * var ast = braces.parse('a/{b,c}/d'); + * console.log(braces.compile(ast)); + * // { options: { source: 'string' }, + * // state: {}, + * // compilers: + * // { eos: [Function], + * // noop: [Function], + * // bos: [Function], + * // brace: [Function], + * // 'brace.open': [Function], + * // text: [Function], + * // 'brace.close': [Function] }, + * // output: [ 'a/(b|c)/d' ], + * // ast: + * // { ... }, + * // parsingErrors: [] } + * ``` + * @param {Object|String} `ast` AST from [.parse](#parse). If a string is passed it will be parsed first. + * @param {Object} `options` + * @return {Object} Returns an object that has an `output` property with the compiled string. + * @api public + */ + +braces.compile = function(ast, options) { + var proto = new Braces(options); + return proto.compile(ast, options); +}; + +/** + * Clear the regex cache. + * + * ```js + * braces.clearCache(); + * ``` + * @api public + */ + +braces.clearCache = function() { + cache = braces.cache = {}; +}; + +/** + * Memoize a generated regex or function. A unique key is generated + * from the method name, pattern, and user-defined options. Set + * options.memoize to false to disable. + */ + +function memoize(type, pattern, options, fn) { + var key = utils.createKey(type + ':' + pattern, options); + var disabled = options && options.cache === false; + if (disabled) { + braces.clearCache(); + return fn(pattern, options); + } + + if (cache.hasOwnProperty(key)) { + return cache[key]; + } + + var res = fn(pattern, options); + cache[key] = res; + return res; +} + +/** + * Expose `Braces` constructor and methods + * @type {Function} + */ + +braces.Braces = Braces; +braces.compilers = compilers; +braces.parsers = parsers; +braces.cache = cache; + +/** + * Expose `braces` + * @type {Function} + */ + +module.exports = braces; + + +/***/ }), +/* 307 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * define-property + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +var isDescriptor = __webpack_require__(308); + +module.exports = function defineProperty(obj, prop, val) { + if (typeof obj !== 'object' && typeof obj !== 'function') { + throw new TypeError('expected an object or function.'); + } + + if (typeof prop !== 'string') { + throw new TypeError('expected `prop` to be a string.'); + } + + if (isDescriptor(val) && ('set' in val || 'get' in val)) { + return Object.defineProperty(obj, prop, val); + } + + return Object.defineProperty(obj, prop, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); +}; + + +/***/ }), +/* 308 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * is-descriptor + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var typeOf = __webpack_require__(309); +var isAccessor = __webpack_require__(310); +var isData = __webpack_require__(312); + +module.exports = function isDescriptor(obj, key) { + if (typeOf(obj) !== 'object') { + return false; + } + if ('get' in obj) { + return isAccessor(obj, key); + } + return isData(obj, key); +}; + + +/***/ }), +/* 309 */ +/***/ (function(module, exports) { + +var toString = Object.prototype.toString; + +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ + +module.exports = function kindOf(val) { + var type = typeof val; + + // primitivies + if (type === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (type === 'string' || val instanceof String) { + return 'string'; + } + if (type === 'number' || val instanceof Number) { + return 'number'; + } + + // functions + if (type === 'function' || val instanceof Function) { + if (typeof val.constructor.name !== 'undefined' && val.constructor.name.slice(0, 9) === 'Generator') { + return 'generatorfunction'; + } + return 'function'; + } + + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } + + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } + + // other objects + type = toString.call(val); + + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + if (type === '[object Promise]') { + return 'promise'; + } + + // buffer + if (isBuffer(val)) { + return 'buffer'; + } + + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } + + if (type === '[object Map Iterator]') { + return 'mapiterator'; + } + if (type === '[object Set Iterator]') { + return 'setiterator'; + } + if (type === '[object String Iterator]') { + return 'stringiterator'; + } + if (type === '[object Array Iterator]') { + return 'arrayiterator'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } + + // must be a plain object + return 'object'; +}; + +/** + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer + */ + +function isBuffer(val) { + return val.constructor + && typeof val.constructor.isBuffer === 'function' + && val.constructor.isBuffer(val); +} + + +/***/ }), +/* 310 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * is-accessor-descriptor + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +var typeOf = __webpack_require__(311); + +// accessor descriptor properties +var accessor = { + get: 'function', + set: 'function', + configurable: 'boolean', + enumerable: 'boolean' +}; + +function isAccessorDescriptor(obj, prop) { + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; + } + + if (typeOf(obj) !== 'object') { + return false; + } + + if (has(obj, 'value') || has(obj, 'writable')) { + return false; + } + + if (!has(obj, 'get') || typeof obj.get !== 'function') { + return false; + } + + // tldr: it's valid to have "set" be undefined + // "set" might be undefined if `Object.getOwnPropertyDescriptor` + // was used to get the value, and only `get` was defined by the user + if (has(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') { + return false; + } + + for (var key in obj) { + if (!accessor.hasOwnProperty(key)) { + continue; + } + + if (typeOf(obj[key]) === accessor[key]) { + continue; + } + + if (typeof obj[key] !== 'undefined') { + return false; + } + } + return true; +} + +function has(obj, key) { + return {}.hasOwnProperty.call(obj, key); +} + +/** + * Expose `isAccessorDescriptor` + */ + +module.exports = isAccessorDescriptor; + + +/***/ }), +/* 311 */ +/***/ (function(module, exports, __webpack_require__) { + +var isBuffer = __webpack_require__(22); +var toString = Object.prototype.toString; + +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ + +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; + } + + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; + } + + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } + + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } + + // other objects + var type = toString.call(val); + + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + + // buffer + if (isBuffer(val)) { + return 'buffer'; + } + + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } + + // must be a plain object + return 'object'; +}; + + +/***/ }), +/* 312 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * is-data-descriptor + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +var typeOf = __webpack_require__(313); + +// data descriptor properties +var data = { + configurable: 'boolean', + enumerable: 'boolean', + writable: 'boolean' +}; + +function isDataDescriptor(obj, prop) { + if (typeOf(obj) !== 'object') { + return false; + } + + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; + } + + if (!('value' in obj) && !('writable' in obj)) { + return false; + } + + for (var key in obj) { + if (key === 'value') continue; + + if (!data.hasOwnProperty(key)) { + continue; + } + + if (typeOf(obj[key]) === data[key]) { + continue; + } + + if (typeof obj[key] !== 'undefined') { + return false; + } + } + return true; +} + +/** + * Expose `isDataDescriptor` + */ + +module.exports = isDataDescriptor; + + +/***/ }), +/* 313 */ +/***/ (function(module, exports, __webpack_require__) { + +var isBuffer = __webpack_require__(22); +var toString = Object.prototype.toString; + +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ + +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; + } + + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; + } + + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } + + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } + + // other objects + var type = toString.call(val); + + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + + // buffer + if (isBuffer(val)) { + return 'buffer'; + } + + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } + + // must be a plain object + return 'object'; +}; + + +/***/ }), +/* 314 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * is-descriptor + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var typeOf = __webpack_require__(315); +var isAccessor = __webpack_require__(316); +var isData = __webpack_require__(318); + +module.exports = function isDescriptor(obj, key) { + if (typeOf(obj) !== 'object') { + return false; + } + if ('get' in obj) { + return isAccessor(obj, key); + } + return isData(obj, key); +}; + + +/***/ }), +/* 315 */ +/***/ (function(module, exports) { + +var toString = Object.prototype.toString; + +module.exports = function kindOf(val) { + if (val === void 0) return 'undefined'; + if (val === null) return 'null'; + + var type = typeof val; + if (type === 'boolean') return 'boolean'; + if (type === 'string') return 'string'; + if (type === 'number') return 'number'; + if (type === 'symbol') return 'symbol'; + if (type === 'function') { + return isGeneratorFn(val) ? 'generatorfunction' : 'function'; + } + + if (isArray(val)) return 'array'; + if (isBuffer(val)) return 'buffer'; + if (isArguments(val)) return 'arguments'; + if (isDate(val)) return 'date'; + if (isError(val)) return 'error'; + if (isRegexp(val)) return 'regexp'; + + switch (ctorName(val)) { + case 'Symbol': return 'symbol'; + case 'Promise': return 'promise'; + + // Set, Map, WeakSet, WeakMap + case 'WeakMap': return 'weakmap'; + case 'WeakSet': return 'weakset'; + case 'Map': return 'map'; + case 'Set': return 'set'; + + // 8-bit typed arrays + case 'Int8Array': return 'int8array'; + case 'Uint8Array': return 'uint8array'; + case 'Uint8ClampedArray': return 'uint8clampedarray'; + + // 16-bit typed arrays + case 'Int16Array': return 'int16array'; + case 'Uint16Array': return 'uint16array'; + + // 32-bit typed arrays + case 'Int32Array': return 'int32array'; + case 'Uint32Array': return 'uint32array'; + case 'Float32Array': return 'float32array'; + case 'Float64Array': return 'float64array'; + } + + if (isGeneratorObj(val)) { + return 'generator'; + } + + // Non-plain objects + type = toString.call(val); + switch (type) { + case '[object Object]': return 'object'; + // iterators + case '[object Map Iterator]': return 'mapiterator'; + case '[object Set Iterator]': return 'setiterator'; + case '[object String Iterator]': return 'stringiterator'; + case '[object Array Iterator]': return 'arrayiterator'; + } + + // other + return type.slice(8, -1).toLowerCase().replace(/\s/g, ''); +}; + +function ctorName(val) { + return val.constructor ? val.constructor.name : null; +} + +function isArray(val) { + if (Array.isArray) return Array.isArray(val); + return val instanceof Array; +} + +function isError(val) { + return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number'); +} + +function isDate(val) { + if (val instanceof Date) return true; + return typeof val.toDateString === 'function' + && typeof val.getDate === 'function' + && typeof val.setDate === 'function'; +} + +function isRegexp(val) { + if (val instanceof RegExp) return true; + return typeof val.flags === 'string' + && typeof val.ignoreCase === 'boolean' + && typeof val.multiline === 'boolean' + && typeof val.global === 'boolean'; +} + +function isGeneratorFn(name, val) { + return ctorName(name) === 'GeneratorFunction'; +} + +function isGeneratorObj(val) { + return typeof val.throw === 'function' + && typeof val.return === 'function' + && typeof val.next === 'function'; +} + +function isArguments(val) { + try { + if (typeof val.length === 'number' && typeof val.callee === 'function') { + return true; + } + } catch (err) { + if (err.message.indexOf('callee') !== -1) { + return true; + } + } + return false; +} + +/** + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer + */ + +function isBuffer(val) { + if (val.constructor && typeof val.constructor.isBuffer === 'function') { + return val.constructor.isBuffer(val); + } + return false; +} + + +/***/ }), +/* 316 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * is-accessor-descriptor + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var typeOf = __webpack_require__(317); + +// accessor descriptor properties +var accessor = { + get: 'function', + set: 'function', + configurable: 'boolean', + enumerable: 'boolean' +}; + +function isAccessorDescriptor(obj, prop) { + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; + } + + if (typeOf(obj) !== 'object') { + return false; + } + + if (has(obj, 'value') || has(obj, 'writable')) { + return false; + } + + if (!has(obj, 'get') || typeof obj.get !== 'function') { + return false; + } + + // tldr: it's valid to have "set" be undefined + // "set" might be undefined if `Object.getOwnPropertyDescriptor` + // was used to get the value, and only `get` was defined by the user + if (has(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') { + return false; + } + + for (var key in obj) { + if (!accessor.hasOwnProperty(key)) { + continue; + } + + if (typeOf(obj[key]) === accessor[key]) { + continue; + } + + if (typeof obj[key] !== 'undefined') { + return false; + } + } + return true; +} + +function has(obj, key) { + return {}.hasOwnProperty.call(obj, key); +} + +/** + * Expose `isAccessorDescriptor` + */ + +module.exports = isAccessorDescriptor; + + +/***/ }), +/* 317 */ +/***/ (function(module, exports) { + +var toString = Object.prototype.toString; + +module.exports = function kindOf(val) { + if (val === void 0) return 'undefined'; + if (val === null) return 'null'; + + var type = typeof val; + if (type === 'boolean') return 'boolean'; + if (type === 'string') return 'string'; + if (type === 'number') return 'number'; + if (type === 'symbol') return 'symbol'; + if (type === 'function') { + return isGeneratorFn(val) ? 'generatorfunction' : 'function'; + } + + if (isArray(val)) return 'array'; + if (isBuffer(val)) return 'buffer'; + if (isArguments(val)) return 'arguments'; + if (isDate(val)) return 'date'; + if (isError(val)) return 'error'; + if (isRegexp(val)) return 'regexp'; + + switch (ctorName(val)) { + case 'Symbol': return 'symbol'; + case 'Promise': return 'promise'; + + // Set, Map, WeakSet, WeakMap + case 'WeakMap': return 'weakmap'; + case 'WeakSet': return 'weakset'; + case 'Map': return 'map'; + case 'Set': return 'set'; + + // 8-bit typed arrays + case 'Int8Array': return 'int8array'; + case 'Uint8Array': return 'uint8array'; + case 'Uint8ClampedArray': return 'uint8clampedarray'; + + // 16-bit typed arrays + case 'Int16Array': return 'int16array'; + case 'Uint16Array': return 'uint16array'; + + // 32-bit typed arrays + case 'Int32Array': return 'int32array'; + case 'Uint32Array': return 'uint32array'; + case 'Float32Array': return 'float32array'; + case 'Float64Array': return 'float64array'; + } + + if (isGeneratorObj(val)) { + return 'generator'; + } + + // Non-plain objects + type = toString.call(val); + switch (type) { + case '[object Object]': return 'object'; + // iterators + case '[object Map Iterator]': return 'mapiterator'; + case '[object Set Iterator]': return 'setiterator'; + case '[object String Iterator]': return 'stringiterator'; + case '[object Array Iterator]': return 'arrayiterator'; + } + + // other + return type.slice(8, -1).toLowerCase().replace(/\s/g, ''); +}; + +function ctorName(val) { + return val.constructor ? val.constructor.name : null; +} + +function isArray(val) { + if (Array.isArray) return Array.isArray(val); + return val instanceof Array; +} + +function isError(val) { + return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number'); +} + +function isDate(val) { + if (val instanceof Date) return true; + return typeof val.toDateString === 'function' + && typeof val.getDate === 'function' + && typeof val.setDate === 'function'; +} + +function isRegexp(val) { + if (val instanceof RegExp) return true; + return typeof val.flags === 'string' + && typeof val.ignoreCase === 'boolean' + && typeof val.multiline === 'boolean' + && typeof val.global === 'boolean'; +} + +function isGeneratorFn(name, val) { + return ctorName(name) === 'GeneratorFunction'; +} + +function isGeneratorObj(val) { + return typeof val.throw === 'function' + && typeof val.return === 'function' + && typeof val.next === 'function'; +} + +function isArguments(val) { + try { + if (typeof val.length === 'number' && typeof val.callee === 'function') { + return true; + } + } catch (err) { + if (err.message.indexOf('callee') !== -1) { + return true; + } + } + return false; +} + +/** + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer + */ + +function isBuffer(val) { + if (val.constructor && typeof val.constructor.isBuffer === 'function') { + return val.constructor.isBuffer(val); + } + return false; +} + + +/***/ }), +/* 318 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * is-data-descriptor + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var typeOf = __webpack_require__(319); + +module.exports = function isDataDescriptor(obj, prop) { + // data descriptor properties + var data = { + configurable: 'boolean', + enumerable: 'boolean', + writable: 'boolean' + }; + + if (typeOf(obj) !== 'object') { + return false; + } + + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; + } + + if (!('value' in obj) && !('writable' in obj)) { + return false; + } + + for (var key in obj) { + if (key === 'value') continue; + + if (!data.hasOwnProperty(key)) { + continue; + } + + if (typeOf(obj[key]) === data[key]) { + continue; + } + + if (typeof obj[key] !== 'undefined') { + return false; + } + } + return true; +}; + + +/***/ }), +/* 319 */ +/***/ (function(module, exports) { + +var toString = Object.prototype.toString; + +module.exports = function kindOf(val) { + if (val === void 0) return 'undefined'; + if (val === null) return 'null'; + + var type = typeof val; + if (type === 'boolean') return 'boolean'; + if (type === 'string') return 'string'; + if (type === 'number') return 'number'; + if (type === 'symbol') return 'symbol'; + if (type === 'function') { + return isGeneratorFn(val) ? 'generatorfunction' : 'function'; + } + + if (isArray(val)) return 'array'; + if (isBuffer(val)) return 'buffer'; + if (isArguments(val)) return 'arguments'; + if (isDate(val)) return 'date'; + if (isError(val)) return 'error'; + if (isRegexp(val)) return 'regexp'; + + switch (ctorName(val)) { + case 'Symbol': return 'symbol'; + case 'Promise': return 'promise'; + + // Set, Map, WeakSet, WeakMap + case 'WeakMap': return 'weakmap'; + case 'WeakSet': return 'weakset'; + case 'Map': return 'map'; + case 'Set': return 'set'; + + // 8-bit typed arrays + case 'Int8Array': return 'int8array'; + case 'Uint8Array': return 'uint8array'; + case 'Uint8ClampedArray': return 'uint8clampedarray'; + + // 16-bit typed arrays + case 'Int16Array': return 'int16array'; + case 'Uint16Array': return 'uint16array'; + + // 32-bit typed arrays + case 'Int32Array': return 'int32array'; + case 'Uint32Array': return 'uint32array'; + case 'Float32Array': return 'float32array'; + case 'Float64Array': return 'float64array'; + } + + if (isGeneratorObj(val)) { + return 'generator'; + } + + // Non-plain objects + type = toString.call(val); + switch (type) { + case '[object Object]': return 'object'; + // iterators + case '[object Map Iterator]': return 'mapiterator'; + case '[object Set Iterator]': return 'setiterator'; + case '[object String Iterator]': return 'stringiterator'; + case '[object Array Iterator]': return 'arrayiterator'; + } + + // other + return type.slice(8, -1).toLowerCase().replace(/\s/g, ''); +}; + +function ctorName(val) { + return val.constructor ? val.constructor.name : null; +} + +function isArray(val) { + if (Array.isArray) return Array.isArray(val); + return val instanceof Array; +} + +function isError(val) { + return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number'); +} + +function isDate(val) { + if (val instanceof Date) return true; + return typeof val.toDateString === 'function' + && typeof val.getDate === 'function' + && typeof val.setDate === 'function'; +} + +function isRegexp(val) { + if (val instanceof RegExp) return true; + return typeof val.flags === 'string' + && typeof val.ignoreCase === 'boolean' + && typeof val.multiline === 'boolean' + && typeof val.global === 'boolean'; +} + +function isGeneratorFn(name, val) { + return ctorName(name) === 'GeneratorFunction'; +} + +function isGeneratorObj(val) { + return typeof val.throw === 'function' + && typeof val.return === 'function' + && typeof val.next === 'function'; +} + +function isArguments(val) { + try { + if (typeof val.length === 'number' && typeof val.callee === 'function') { + return true; + } + } catch (err) { + if (err.message.indexOf('callee') !== -1) { + return true; + } + } + return false; +} + +/** + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer + */ + +function isBuffer(val) { + if (val.constructor && typeof val.constructor.isBuffer === 'function') { + return val.constructor.isBuffer(val); + } + return false; +} + + +/***/ }), +/* 320 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var isExtendable = __webpack_require__(321); +var assignSymbols = __webpack_require__(322); + +module.exports = Object.assign || function(obj/*, objects*/) { + if (obj === null || typeof obj === 'undefined') { + throw new TypeError('Cannot convert undefined or null to object'); + } + if (!isObject(obj)) { + obj = {}; + } + for (var i = 1; i < arguments.length; i++) { + var val = arguments[i]; + if (isString(val)) { + val = toObject(val); + } + if (isObject(val)) { + assign(obj, val); + assignSymbols(obj, val); + } + } + return obj; +}; + +function assign(a, b) { + for (var key in b) { + if (hasOwn(b, key)) { + a[key] = b[key]; + } + } +} + +function isString(val) { + return (val && typeof val === 'string'); +} + +function toObject(str) { + var obj = {}; + for (var i in str) { + obj[i] = str[i]; + } + return obj; +} + +function isObject(val) { + return (val && typeof val === 'object') || isExtendable(val); +} + +/** + * Returns true if the given `key` is an own property of `obj`. + */ + +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +function isEnum(obj, key) { + return Object.prototype.propertyIsEnumerable.call(obj, key); +} + + +/***/ }), +/* 321 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isPlainObject = __webpack_require__(76); + +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); +}; + + +/***/ }), +/* 322 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * assign-symbols + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +module.exports = function(receiver, objects) { + if (receiver === null || typeof receiver === 'undefined') { + throw new TypeError('expected first argument to be an object.'); + } + + if (typeof objects === 'undefined' || typeof Symbol === 'undefined') { + return receiver; + } + + if (typeof Object.getOwnPropertySymbols !== 'function') { + return receiver; + } + + var isEnumerable = Object.prototype.propertyIsEnumerable; + var target = Object(receiver); + var len = arguments.length, i = 0; + + while (++i < len) { + var provider = Object(arguments[i]); + var names = Object.getOwnPropertySymbols(provider); + + for (var j = 0; j < names.length; j++) { + var key = names[j]; + + if (isEnumerable.call(provider, key)) { + target[key] = provider[key]; + } + } + } + return target; +}; + + +/***/ }), +/* 323 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * arr-flatten + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +module.exports = function (arr) { + return flat(arr, []); +}; + +function flat(arr, res) { + var i = 0, cur; + var len = arr.length; + for (; i < len; i++) { + cur = arr[i]; + Array.isArray(cur) ? flat(cur, res) : res.push(cur); + } + return res; +} + + +/***/ }), +/* 324 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * fill-range + * + * Copyright (c) 2014-2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var util = __webpack_require__(14); +var isNumber = __webpack_require__(77); +var extend = __webpack_require__(20); +var repeat = __webpack_require__(137); +var toRegex = __webpack_require__(325); + +/** + * Return a range of numbers or letters. + * + * @param {String} `start` Start of the range + * @param {String} `stop` End of the range + * @param {String} `step` Increment or decrement to use. + * @param {Function} `fn` Custom function to modify each element in the range. + * @return {Array} + */ + +function fillRange(start, stop, step, options) { + if (typeof start === 'undefined') { + return []; + } + + if (typeof stop === 'undefined' || start === stop) { + // special case, for handling negative zero + var isString = typeof start === 'string'; + if (isNumber(start) && !toNumber(start)) { + return [isString ? '0' : 0]; + } + return [start]; + } + + if (typeof step !== 'number' && typeof step !== 'string') { + options = step; + step = undefined; + } + + if (typeof options === 'function') { + options = { transform: options }; + } + + var opts = extend({step: step}, options); + if (opts.step && !isValidNumber(opts.step)) { + if (opts.strictRanges === true) { + throw new TypeError('expected options.step to be a number'); + } + return []; + } + + opts.isNumber = isValidNumber(start) && isValidNumber(stop); + if (!opts.isNumber && !isValid(start, stop)) { + if (opts.strictRanges === true) { + throw new RangeError('invalid range arguments: ' + util.inspect([start, stop])); + } + return []; + } + + opts.isPadded = isPadded(start) || isPadded(stop); + opts.toString = opts.stringify + || typeof opts.step === 'string' + || typeof start === 'string' + || typeof stop === 'string' + || !opts.isNumber; + + if (opts.isPadded) { + opts.maxLength = Math.max(String(start).length, String(stop).length); + } + + // support legacy minimatch/fill-range options + if (typeof opts.optimize === 'boolean') opts.toRegex = opts.optimize; + if (typeof opts.makeRe === 'boolean') opts.toRegex = opts.makeRe; + return expand(start, stop, opts); +} + +function expand(start, stop, options) { + var a = options.isNumber ? toNumber(start) : start.charCodeAt(0); + var b = options.isNumber ? toNumber(stop) : stop.charCodeAt(0); + + var step = Math.abs(toNumber(options.step)) || 1; + if (options.toRegex && step === 1) { + return toRange(a, b, start, stop, options); + } + + var zero = {greater: [], lesser: []}; + var asc = a < b; + var arr = new Array(Math.round((asc ? b - a : a - b) / step)); + var idx = 0; + + while (asc ? a <= b : a >= b) { + var val = options.isNumber ? a : String.fromCharCode(a); + if (options.toRegex && (val >= 0 || !options.isNumber)) { + zero.greater.push(val); + } else { + zero.lesser.push(Math.abs(val)); + } + + if (options.isPadded) { + val = zeros(val, options); + } + + if (options.toString) { + val = String(val); + } + + if (typeof options.transform === 'function') { + arr[idx++] = options.transform(val, a, b, step, idx, arr, options); + } else { + arr[idx++] = val; + } + + if (asc) { + a += step; + } else { + a -= step; + } + } + + if (options.toRegex === true) { + return toSequence(arr, zero, options); + } + return arr; +} + +function toRange(a, b, start, stop, options) { + if (options.isPadded) { + return toRegex(start, stop, options); + } + + if (options.isNumber) { + return toRegex(Math.min(a, b), Math.max(a, b), options); + } + + var start = String.fromCharCode(Math.min(a, b)); + var stop = String.fromCharCode(Math.max(a, b)); + return '[' + start + '-' + stop + ']'; +} + +function toSequence(arr, zeros, options) { + var greater = '', lesser = ''; + if (zeros.greater.length) { + greater = zeros.greater.join('|'); + } + if (zeros.lesser.length) { + lesser = '-(' + zeros.lesser.join('|') + ')'; + } + var res = greater && lesser + ? greater + '|' + lesser + : greater || lesser; + + if (options.capture) { + return '(' + res + ')'; + } + return res; +} + +function zeros(val, options) { + if (options.isPadded) { + var str = String(val); + var len = str.length; + var dash = ''; + if (str.charAt(0) === '-') { + dash = '-'; + str = str.slice(1); + } + var diff = options.maxLength - len; + var pad = repeat('0', diff); + val = (dash + pad + str); + } + if (options.stringify) { + return String(val); + } + return val; +} + +function toNumber(val) { + return Number(val) || 0; +} + +function isPadded(str) { + return /^-?0\d/.test(str); +} + +function isValid(min, max) { + return (isValidNumber(min) || isValidLetter(min)) + && (isValidNumber(max) || isValidLetter(max)); +} + +function isValidLetter(ch) { + return typeof ch === 'string' && ch.length === 1 && /^\w+$/.test(ch); +} + +function isValidNumber(n) { + return isNumber(n) && !/\./.test(n); +} + +/** + * Expose `fillRange` + * @type {Function} + */ + +module.exports = fillRange; + + +/***/ }), +/* 325 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * to-regex-range + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var repeat = __webpack_require__(137); +var isNumber = __webpack_require__(77); +var cache = {}; + +function toRegexRange(min, max, options) { + if (isNumber(min) === false) { + throw new RangeError('toRegexRange: first argument is invalid.'); + } + + if (typeof max === 'undefined' || min === max) { + return String(min); + } + + if (isNumber(max) === false) { + throw new RangeError('toRegexRange: second argument is invalid.'); + } + + options = options || {}; + var relax = String(options.relaxZeros); + var shorthand = String(options.shorthand); + var capture = String(options.capture); + var key = min + ':' + max + '=' + relax + shorthand + capture; + if (cache.hasOwnProperty(key)) { + return cache[key].result; + } + + var a = Math.min(min, max); + var b = Math.max(min, max); + + if (Math.abs(a - b) === 1) { + var result = min + '|' + max; + if (options.capture) { + return '(' + result + ')'; + } + return result; + } + + var isPadded = padding(min) || padding(max); + var positives = []; + var negatives = []; + + var tok = {min: min, max: max, a: a, b: b}; + if (isPadded) { + tok.isPadded = isPadded; + tok.maxLen = String(tok.max).length; + } + + if (a < 0) { + var newMin = b < 0 ? Math.abs(b) : 1; + var newMax = Math.abs(a); + negatives = splitToPatterns(newMin, newMax, tok, options); + a = tok.a = 0; + } + + if (b >= 0) { + positives = splitToPatterns(a, b, tok, options); + } + + tok.negatives = negatives; + tok.positives = positives; + tok.result = siftPatterns(negatives, positives, options); + + if (options.capture && (positives.length + negatives.length) > 1) { + tok.result = '(' + tok.result + ')'; + } + + cache[key] = tok; + return tok.result; +} + +function siftPatterns(neg, pos, options) { + var onlyNegative = filterPatterns(neg, pos, '-', false, options) || []; + var onlyPositive = filterPatterns(pos, neg, '', false, options) || []; + var intersected = filterPatterns(neg, pos, '-?', true, options) || []; + var subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); + return subpatterns.join('|'); +} + +function splitToRanges(min, max) { + min = Number(min); + max = Number(max); + + var nines = 1; + var stops = [max]; + var stop = +countNines(min, nines); + + while (min <= stop && stop <= max) { + stops = push(stops, stop); + nines += 1; + stop = +countNines(min, nines); + } + + var zeros = 1; + stop = countZeros(max + 1, zeros) - 1; + + while (min < stop && stop <= max) { + stops = push(stops, stop); + zeros += 1; + stop = countZeros(max + 1, zeros) - 1; + } + + stops.sort(compare); + return stops; +} + +/** + * Convert a range to a regex pattern + * @param {Number} `start` + * @param {Number} `stop` + * @return {String} + */ + +function rangeToPattern(start, stop, options) { + if (start === stop) { + return {pattern: String(start), digits: []}; + } + + var zipped = zip(String(start), String(stop)); + var len = zipped.length, i = -1; + + var pattern = ''; + var digits = 0; + + while (++i < len) { + var numbers = zipped[i]; + var startDigit = numbers[0]; + var stopDigit = numbers[1]; + + if (startDigit === stopDigit) { + pattern += startDigit; + + } else if (startDigit !== '0' || stopDigit !== '9') { + pattern += toCharacterClass(startDigit, stopDigit); + + } else { + digits += 1; + } + } + + if (digits) { + pattern += options.shorthand ? '\\d' : '[0-9]'; + } + + return { pattern: pattern, digits: [digits] }; +} + +function splitToPatterns(min, max, tok, options) { + var ranges = splitToRanges(min, max); + var len = ranges.length; + var idx = -1; + + var tokens = []; + var start = min; + var prev; + + while (++idx < len) { + var range = ranges[idx]; + var obj = rangeToPattern(start, range, options); + var zeros = ''; + + if (!tok.isPadded && prev && prev.pattern === obj.pattern) { + if (prev.digits.length > 1) { + prev.digits.pop(); + } + prev.digits.push(obj.digits[0]); + prev.string = prev.pattern + toQuantifier(prev.digits); + start = range + 1; + continue; + } + + if (tok.isPadded) { + zeros = padZeros(range, tok); + } + + obj.string = zeros + obj.pattern + toQuantifier(obj.digits); + tokens.push(obj); + start = range + 1; + prev = obj; + } + + return tokens; +} + +function filterPatterns(arr, comparison, prefix, intersection, options) { + var res = []; + + for (var i = 0; i < arr.length; i++) { + var tok = arr[i]; + var ele = tok.string; + + if (options.relaxZeros !== false) { + if (prefix === '-' && ele.charAt(0) === '0') { + if (ele.charAt(1) === '{') { + ele = '0*' + ele.replace(/^0\{\d+\}/, ''); + } else { + ele = '0*' + ele.slice(1); + } + } + } + + if (!intersection && !contains(comparison, 'string', ele)) { + res.push(prefix + ele); + } + + if (intersection && contains(comparison, 'string', ele)) { + res.push(prefix + ele); + } + } + return res; +} + +/** + * Zip strings (`for in` can be used on string characters) + */ + +function zip(a, b) { + var arr = []; + for (var ch in a) arr.push([a[ch], b[ch]]); + return arr; +} + +function compare(a, b) { + return a > b ? 1 : b > a ? -1 : 0; +} + +function push(arr, ele) { + if (arr.indexOf(ele) === -1) arr.push(ele); + return arr; +} + +function contains(arr, key, val) { + for (var i = 0; i < arr.length; i++) { + if (arr[i][key] === val) { + return true; + } + } + return false; +} + +function countNines(min, len) { + return String(min).slice(0, -len) + repeat('9', len); +} + +function countZeros(integer, zeros) { + return integer - (integer % Math.pow(10, zeros)); +} + +function toQuantifier(digits) { + var start = digits[0]; + var stop = digits[1] ? (',' + digits[1]) : ''; + if (!stop && (!start || start === 1)) { + return ''; + } + return '{' + start + stop + '}'; +} + +function toCharacterClass(a, b) { + return '[' + a + ((b - a === 1) ? '' : '-') + b + ']'; +} + +function padding(str) { + return /^-?(0+)\d/.exec(str); +} + +function padZeros(val, tok) { + if (tok.isPadded) { + var diff = Math.abs(tok.maxLen - String(val).length); + switch (diff) { + case 0: + return ''; + case 1: + return '0'; + default: { + return '0{' + diff + '}'; + } + } + } + return val; +} + +/** + * Expose `toRegexRange` + */ + +module.exports = toRegexRange; + + +/***/ }), +/* 326 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * repeat-element + * + * Copyright (c) 2015 Jon Schlinkert. + * Licensed under the MIT license. + */ + + + +module.exports = function repeat(ele, num) { + var arr = new Array(num); + + for (var i = 0; i < num; i++) { + arr[i] = ele; + } + + return arr; +}; + + +/***/ }), +/* 327 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var isObject = __webpack_require__(30); +var define = __webpack_require__(44); +var utils = __webpack_require__(328); +var ownNames; + +/** + * Create a new AST `Node` with the given `val` and `type`. + * + * ```js + * var node = new Node('*', 'Star'); + * var node = new Node({type: 'star', val: '*'}); + * ``` + * @name Node + * @param {String|Object} `val` Pass a matched substring, or an object to merge onto the node. + * @param {String} `type` The node type to use when `val` is a string. + * @return {Object} node instance + * @api public + */ + +function Node(val, type, parent) { + if (typeof type !== 'string') { + parent = type; + type = null; + } + + define(this, 'parent', parent); + define(this, 'isNode', true); + define(this, 'expect', null); + + if (typeof type !== 'string' && isObject(val)) { + lazyKeys(); + var keys = Object.keys(val); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (ownNames.indexOf(key) === -1) { + this[key] = val[key]; + } + } + } else { + this.type = type; + this.val = val; + } +} + +/** + * Returns true if the given value is a node. + * + * ```js + * var Node = require('snapdragon-node'); + * var node = new Node({type: 'foo'}); + * console.log(Node.isNode(node)); //=> true + * console.log(Node.isNode({})); //=> false + * ``` + * @param {Object} `node` + * @returns {Boolean} + * @api public + */ + +Node.isNode = function(node) { + return utils.isNode(node); +}; + +/** + * Define a non-enumberable property on the node instance. + * Useful for adding properties that shouldn't be extended + * or visible during debugging. + * + * ```js + * var node = new Node(); + * node.define('foo', 'something non-enumerable'); + * ``` + * @param {String} `name` + * @param {any} `val` + * @return {Object} returns the node instance + * @api public + */ + +Node.prototype.define = function(name, val) { + define(this, name, val); + return this; +}; + +/** + * Returns true if `node.val` is an empty string, or `node.nodes` does + * not contain any non-empty text nodes. + * + * ```js + * var node = new Node({type: 'text'}); + * node.isEmpty(); //=> true + * node.val = 'foo'; + * node.isEmpty(); //=> false + * ``` + * @param {Function} `fn` (optional) Filter function that is called on `node` and/or child nodes. `isEmpty` will return false immediately when the filter function returns false on any nodes. + * @return {Boolean} + * @api public + */ + +Node.prototype.isEmpty = function(fn) { + return utils.isEmpty(this, fn); +}; + +/** + * Given node `foo` and node `bar`, push node `bar` onto `foo.nodes`, and + * set `foo` as `bar.parent`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * foo.push(bar); + * ``` + * @param {Object} `node` + * @return {Number} Returns the length of `node.nodes` + * @api public + */ + +Node.prototype.push = function(node) { + assert(Node.isNode(node), 'expected node to be an instance of Node'); + define(node, 'parent', this); + + this.nodes = this.nodes || []; + return this.nodes.push(node); +}; + +/** + * Given node `foo` and node `bar`, unshift node `bar` onto `foo.nodes`, and + * set `foo` as `bar.parent`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * foo.unshift(bar); + * ``` + * @param {Object} `node` + * @return {Number} Returns the length of `node.nodes` + * @api public + */ + +Node.prototype.unshift = function(node) { + assert(Node.isNode(node), 'expected node to be an instance of Node'); + define(node, 'parent', this); + + this.nodes = this.nodes || []; + return this.nodes.unshift(node); +}; + +/** + * Pop a node from `node.nodes`. + * + * ```js + * var node = new Node({type: 'foo'}); + * node.push(new Node({type: 'a'})); + * node.push(new Node({type: 'b'})); + * node.push(new Node({type: 'c'})); + * node.push(new Node({type: 'd'})); + * console.log(node.nodes.length); + * //=> 4 + * node.pop(); + * console.log(node.nodes.length); + * //=> 3 + * ``` + * @return {Number} Returns the popped `node` + * @api public + */ + +Node.prototype.pop = function() { + return this.nodes && this.nodes.pop(); +}; + +/** + * Shift a node from `node.nodes`. + * + * ```js + * var node = new Node({type: 'foo'}); + * node.push(new Node({type: 'a'})); + * node.push(new Node({type: 'b'})); + * node.push(new Node({type: 'c'})); + * node.push(new Node({type: 'd'})); + * console.log(node.nodes.length); + * //=> 4 + * node.shift(); + * console.log(node.nodes.length); + * //=> 3 + * ``` + * @return {Object} Returns the shifted `node` + * @api public + */ + +Node.prototype.shift = function() { + return this.nodes && this.nodes.shift(); +}; + +/** + * Remove `node` from `node.nodes`. + * + * ```js + * node.remove(childNode); + * ``` + * @param {Object} `node` + * @return {Object} Returns the removed node. + * @api public + */ + +Node.prototype.remove = function(node) { + assert(Node.isNode(node), 'expected node to be an instance of Node'); + this.nodes = this.nodes || []; + var idx = node.index; + if (idx !== -1) { + node.index = -1; + return this.nodes.splice(idx, 1); + } + return null; +}; + +/** + * Get the first child node from `node.nodes` that matches the given `type`. + * If `type` is a number, the child node at that index is returned. + * + * ```js + * var child = node.find(1); //<= index of the node to get + * var child = node.find('foo'); //<= node.type of a child node + * var child = node.find(/^(foo|bar)$/); //<= regex to match node.type + * var child = node.find(['foo', 'bar']); //<= array of node.type(s) + * ``` + * @param {String} `type` + * @return {Object} Returns a child node or undefined. + * @api public + */ + +Node.prototype.find = function(type) { + return utils.findNode(this.nodes, type); +}; + +/** + * Return true if the node is the given `type`. + * + * ```js + * var node = new Node({type: 'bar'}); + * cosole.log(node.isType('foo')); // false + * cosole.log(node.isType(/^(foo|bar)$/)); // true + * cosole.log(node.isType(['foo', 'bar'])); // true + * ``` + * @param {String} `type` + * @return {Boolean} + * @api public + */ + +Node.prototype.isType = function(type) { + return utils.isType(this, type); +}; + +/** + * Return true if the `node.nodes` has the given `type`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * foo.push(bar); + * + * cosole.log(foo.hasType('qux')); // false + * cosole.log(foo.hasType(/^(qux|bar)$/)); // true + * cosole.log(foo.hasType(['qux', 'bar'])); // true + * ``` + * @param {String} `type` + * @return {Boolean} + * @api public + */ + +Node.prototype.hasType = function(type) { + return utils.hasType(this, type); +}; + +/** + * Get the siblings array, or `null` if it doesn't exist. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * foo.push(bar); + * foo.push(baz); + * + * console.log(bar.siblings.length) // 2 + * console.log(baz.siblings.length) // 2 + * ``` + * @return {Array} + * @api public + */ + +Object.defineProperty(Node.prototype, 'siblings', { + set: function() { + throw new Error('node.siblings is a getter and cannot be defined'); + }, + get: function() { + return this.parent ? this.parent.nodes : null; + } +}); + +/** + * Get the node's current index from `node.parent.nodes`. + * This should always be correct, even when the parent adds nodes. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * var qux = new Node({type: 'qux'}); + * foo.push(bar); + * foo.push(baz); + * foo.unshift(qux); + * + * console.log(bar.index) // 1 + * console.log(baz.index) // 2 + * console.log(qux.index) // 0 + * ``` + * @return {Number} + * @api public + */ + +Object.defineProperty(Node.prototype, 'index', { + set: function(index) { + define(this, 'idx', index); + }, + get: function() { + if (!Array.isArray(this.siblings)) { + return -1; + } + var tok = this.idx !== -1 ? this.siblings[this.idx] : null; + if (tok !== this) { + this.idx = this.siblings.indexOf(this); + } + return this.idx; + } +}); + +/** + * Get the previous node from the siblings array or `null`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * foo.push(bar); + * foo.push(baz); + * + * console.log(baz.prev.type) // 'bar' + * ``` + * @return {Object} + * @api public + */ + +Object.defineProperty(Node.prototype, 'prev', { + set: function() { + throw new Error('node.prev is a getter and cannot be defined'); + }, + get: function() { + if (Array.isArray(this.siblings)) { + return this.siblings[this.index - 1] || this.parent.prev; + } + return null; + } +}); + +/** + * Get the siblings array, or `null` if it doesn't exist. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * foo.push(bar); + * foo.push(baz); + * + * console.log(bar.siblings.length) // 2 + * console.log(baz.siblings.length) // 2 + * ``` + * @return {Object} + * @api public + */ + +Object.defineProperty(Node.prototype, 'next', { + set: function() { + throw new Error('node.next is a getter and cannot be defined'); + }, + get: function() { + if (Array.isArray(this.siblings)) { + return this.siblings[this.index + 1] || this.parent.next; + } + return null; + } +}); + +/** + * Get the first node from `node.nodes`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * var qux = new Node({type: 'qux'}); + * foo.push(bar); + * foo.push(baz); + * foo.push(qux); + * + * console.log(foo.first.type) // 'bar' + * ``` + * @return {Object} The first node, or undefiend + * @api public + */ + +Object.defineProperty(Node.prototype, 'first', { + get: function() { + return this.nodes ? this.nodes[0] : null; + } +}); + +/** + * Get the last node from `node.nodes`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * var qux = new Node({type: 'qux'}); + * foo.push(bar); + * foo.push(baz); + * foo.push(qux); + * + * console.log(foo.last.type) // 'qux' + * ``` + * @return {Object} The last node, or undefiend + * @api public + */ + +Object.defineProperty(Node.prototype, 'last', { + get: function() { + return this.nodes ? utils.last(this.nodes) : null; + } +}); + +/** + * Get the last node from `node.nodes`. + * + * ```js + * var foo = new Node({type: 'foo'}); + * var bar = new Node({type: 'bar'}); + * var baz = new Node({type: 'baz'}); + * var qux = new Node({type: 'qux'}); + * foo.push(bar); + * foo.push(baz); + * foo.push(qux); + * + * console.log(foo.last.type) // 'qux' + * ``` + * @return {Object} The last node, or undefiend + * @api public + */ + +Object.defineProperty(Node.prototype, 'scope', { + get: function() { + if (this.isScope !== true) { + return this.parent ? this.parent.scope : this; + } + return this; + } +}); + +/** + * Get own property names from Node prototype, but only the + * first time `Node` is instantiated + */ + +function lazyKeys() { + if (!ownNames) { + ownNames = Object.getOwnPropertyNames(Node.prototype); + } +} + +/** + * Simplified assertion. Throws an error is `val` is falsey. + */ + +function assert(val, message) { + if (!val) throw new Error(message); +} + +/** + * Expose `Node` + */ + +exports = module.exports = Node; + + +/***/ }), +/* 328 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var typeOf = __webpack_require__(49); +var utils = module.exports; + +/** + * Returns true if the given value is a node. + * + * ```js + * var Node = require('snapdragon-node'); + * var node = new Node({type: 'foo'}); + * console.log(utils.isNode(node)); //=> true + * console.log(utils.isNode({})); //=> false + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @returns {Boolean} + * @api public + */ + +utils.isNode = function(node) { + return typeOf(node) === 'object' && node.isNode === true; +}; + +/** + * Emit an empty string for the given `node`. + * + * ```js + * // do nothing for beginning-of-string + * snapdragon.compiler.set('bos', utils.noop); + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @returns {undefined} + * @api public + */ + +utils.noop = function(node) { + append(this, '', node); +}; + +/** + * Appdend `node.val` to `compiler.output`, exactly as it was created + * by the parser. + * + * ```js + * snapdragon.compiler.set('text', utils.identity); + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @returns {undefined} + * @api public + */ + +utils.identity = function(node) { + append(this, node.val, node); +}; + +/** + * Previously named `.emit`, this method appends the given `val` + * to `compiler.output` for the given node. Useful when you know + * what value should be appended advance, regardless of the actual + * value of `node.val`. + * + * ```js + * snapdragon.compiler + * .set('i', function(node) { + * this.mapVisit(node); + * }) + * .set('i.open', utils.append('')) + * .set('i.close', utils.append('')) + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @returns {Function} Returns a compiler middleware function. + * @api public + */ + +utils.append = function(val) { + return function(node) { + append(this, val, node); + }; +}; + +/** + * Used in compiler middleware, this onverts an AST node into + * an empty `text` node and deletes `node.nodes` if it exists. + * The advantage of this method is that, as opposed to completely + * removing the node, indices will not need to be re-calculated + * in sibling nodes, and nothing is appended to the output. + * + * ```js + * utils.toNoop(node); + * // convert `node.nodes` to the given value instead of deleting it + * utils.toNoop(node, []); + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Array} `nodes` Optionally pass a new `nodes` value, to replace the existing `node.nodes` array. + * @api public + */ + +utils.toNoop = function(node, nodes) { + if (nodes) { + node.nodes = nodes; + } else { + delete node.nodes; + node.type = 'text'; + node.val = ''; + } +}; + +/** + * Visit `node` with the given `fn`. The built-in `.visit` method in snapdragon + * automatically calls registered compilers, this allows you to pass a visitor + * function. + * + * ```js + * snapdragon.compiler.set('i', function(node) { + * utils.visit(node, function(childNode) { + * // do stuff with "childNode" + * return childNode; + * }); + * }); + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Function} `fn` + * @return {Object} returns the node after recursively visiting all child nodes. + * @api public + */ + +utils.visit = function(node, fn) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isFunction(fn), 'expected a visitor function'); + fn(node); + return node.nodes ? utils.mapVisit(node, fn) : node; +}; + +/** + * Map [visit](#visit) the given `fn` over `node.nodes`. This is called by + * [visit](#visit), use this method if you do not want `fn` to be called on + * the first node. + * + * ```js + * snapdragon.compiler.set('i', function(node) { + * utils.mapVisit(node, function(childNode) { + * // do stuff with "childNode" + * return childNode; + * }); + * }); + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Object} `options` + * @param {Function} `fn` + * @return {Object} returns the node + * @api public + */ + +utils.mapVisit = function(node, fn) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isArray(node.nodes), 'expected node.nodes to be an array'); + assert(isFunction(fn), 'expected a visitor function'); + + for (var i = 0; i < node.nodes.length; i++) { + utils.visit(node.nodes[i], fn); + } + return node; +}; + +/** + * Unshift an `*.open` node onto `node.nodes`. + * + * ```js + * var Node = require('snapdragon-node'); + * snapdragon.parser.set('brace', function(node) { + * var match = this.match(/^{/); + * if (match) { + * var parent = new Node({type: 'brace'}); + * utils.addOpen(parent, Node); + * console.log(parent.nodes[0]): + * // { type: 'brace.open', val: '' }; + * + * // push the parent "brace" node onto the stack + * this.push(parent); + * + * // return the parent node, so it's also added to the AST + * return brace; + * } + * }); + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][]. + * @param {Function} `filter` Optionaly specify a filter function to exclude the node. + * @return {Object} Returns the created opening node. + * @api public + */ + +utils.addOpen = function(node, Node, val, filter) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isFunction(Node), 'expected Node to be a constructor function'); + + if (typeof val === 'function') { + filter = val; + val = ''; + } + + if (typeof filter === 'function' && !filter(node)) return; + var open = new Node({ type: node.type + '.open', val: val}); + var unshift = node.unshift || node.unshiftNode; + if (typeof unshift === 'function') { + unshift.call(node, open); + } else { + utils.unshiftNode(node, open); + } + return open; +}; + +/** + * Push a `*.close` node onto `node.nodes`. + * + * ```js + * var Node = require('snapdragon-node'); + * snapdragon.parser.set('brace', function(node) { + * var match = this.match(/^}/); + * if (match) { + * var parent = this.parent(); + * if (parent.type !== 'brace') { + * throw new Error('missing opening: ' + '}'); + * } + * + * utils.addClose(parent, Node); + * console.log(parent.nodes[parent.nodes.length - 1]): + * // { type: 'brace.close', val: '' }; + * + * // no need to return a node, since the parent + * // was already added to the AST + * return; + * } + * }); + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][]. + * @param {Function} `filter` Optionaly specify a filter function to exclude the node. + * @return {Object} Returns the created closing node. + * @api public + */ + +utils.addClose = function(node, Node, val, filter) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isFunction(Node), 'expected Node to be a constructor function'); + + if (typeof val === 'function') { + filter = val; + val = ''; + } + + if (typeof filter === 'function' && !filter(node)) return; + var close = new Node({ type: node.type + '.close', val: val}); + var push = node.push || node.pushNode; + if (typeof push === 'function') { + push.call(node, close); + } else { + utils.pushNode(node, close); + } + return close; +}; + +/** + * Wraps the given `node` with `*.open` and `*.close` nodes. + * + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][]. + * @param {Function} `filter` Optionaly specify a filter function to exclude the node. + * @return {Object} Returns the node + * @api public + */ + +utils.wrapNodes = function(node, Node, filter) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isFunction(Node), 'expected Node to be a constructor function'); + + utils.addOpen(node, Node, filter); + utils.addClose(node, Node, filter); + return node; +}; + +/** + * Push the given `node` onto `parent.nodes`, and set `parent` as `node.parent. + * + * ```js + * var parent = new Node({type: 'foo'}); + * var node = new Node({type: 'bar'}); + * utils.pushNode(parent, node); + * console.log(parent.nodes[0].type) // 'bar' + * console.log(node.parent.type) // 'foo' + * ``` + * @param {Object} `parent` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Object} Returns the child node + * @api public + */ + +utils.pushNode = function(parent, node) { + assert(utils.isNode(parent), 'expected parent node to be an instance of Node'); + assert(utils.isNode(node), 'expected node to be an instance of Node'); + + node.define('parent', parent); + parent.nodes = parent.nodes || []; + parent.nodes.push(node); + return node; +}; + +/** + * Unshift `node` onto `parent.nodes`, and set `parent` as `node.parent. + * + * ```js + * var parent = new Node({type: 'foo'}); + * var node = new Node({type: 'bar'}); + * utils.unshiftNode(parent, node); + * console.log(parent.nodes[0].type) // 'bar' + * console.log(node.parent.type) // 'foo' + * ``` + * @param {Object} `parent` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {undefined} + * @api public + */ + +utils.unshiftNode = function(parent, node) { + assert(utils.isNode(parent), 'expected parent node to be an instance of Node'); + assert(utils.isNode(node), 'expected node to be an instance of Node'); + + node.define('parent', parent); + parent.nodes = parent.nodes || []; + parent.nodes.unshift(node); +}; + +/** + * Pop the last `node` off of `parent.nodes`. The advantage of + * using this method is that it checks for `node.nodes` and works + * with any version of `snapdragon-node`. + * + * ```js + * var parent = new Node({type: 'foo'}); + * utils.pushNode(parent, new Node({type: 'foo'})); + * utils.pushNode(parent, new Node({type: 'bar'})); + * utils.pushNode(parent, new Node({type: 'baz'})); + * console.log(parent.nodes.length); //=> 3 + * utils.popNode(parent); + * console.log(parent.nodes.length); //=> 2 + * ``` + * @param {Object} `parent` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Number|Undefined} Returns the length of `node.nodes` or undefined. + * @api public + */ + +utils.popNode = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + if (typeof node.pop === 'function') { + return node.pop(); + } + return node.nodes && node.nodes.pop(); +}; + +/** + * Shift the first `node` off of `parent.nodes`. The advantage of + * using this method is that it checks for `node.nodes` and works + * with any version of `snapdragon-node`. + * + * ```js + * var parent = new Node({type: 'foo'}); + * utils.pushNode(parent, new Node({type: 'foo'})); + * utils.pushNode(parent, new Node({type: 'bar'})); + * utils.pushNode(parent, new Node({type: 'baz'})); + * console.log(parent.nodes.length); //=> 3 + * utils.shiftNode(parent); + * console.log(parent.nodes.length); //=> 2 + * ``` + * @param {Object} `parent` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Number|Undefined} Returns the length of `node.nodes` or undefined. + * @api public + */ + +utils.shiftNode = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + if (typeof node.shift === 'function') { + return node.shift(); + } + return node.nodes && node.nodes.shift(); +}; + +/** + * Remove the specified `node` from `parent.nodes`. + * + * ```js + * var parent = new Node({type: 'abc'}); + * var foo = new Node({type: 'foo'}); + * utils.pushNode(parent, foo); + * utils.pushNode(parent, new Node({type: 'bar'})); + * utils.pushNode(parent, new Node({type: 'baz'})); + * console.log(parent.nodes.length); //=> 3 + * utils.removeNode(parent, foo); + * console.log(parent.nodes.length); //=> 2 + * ``` + * @param {Object} `parent` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Object|undefined} Returns the removed node, if successful, or undefined if it does not exist on `parent.nodes`. + * @api public + */ + +utils.removeNode = function(parent, node) { + assert(utils.isNode(parent), 'expected parent.node to be an instance of Node'); + assert(utils.isNode(node), 'expected node to be an instance of Node'); + + if (!parent.nodes) { + return null; + } + + if (typeof parent.remove === 'function') { + return parent.remove(node); + } + + var idx = parent.nodes.indexOf(node); + if (idx !== -1) { + return parent.nodes.splice(idx, 1); + } +}; + +/** + * Returns true if `node.type` matches the given `type`. Throws a + * `TypeError` if `node` is not an instance of `Node`. + * + * ```js + * var Node = require('snapdragon-node'); + * var node = new Node({type: 'foo'}); + * console.log(utils.isType(node, 'foo')); // false + * console.log(utils.isType(node, 'bar')); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {String} `type` + * @return {Boolean} + * @api public + */ + +utils.isType = function(node, type) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + switch (typeOf(type)) { + case 'array': + var types = type.slice(); + for (var i = 0; i < types.length; i++) { + if (utils.isType(node, types[i])) { + return true; + } + } + return false; + case 'string': + return node.type === type; + case 'regexp': + return type.test(node.type); + default: { + throw new TypeError('expected "type" to be an array, string or regexp'); + } + } +}; + +/** + * Returns true if the given `node` has the given `type` in `node.nodes`. + * Throws a `TypeError` if `node` is not an instance of `Node`. + * + * ```js + * var Node = require('snapdragon-node'); + * var node = new Node({ + * type: 'foo', + * nodes: [ + * new Node({type: 'bar'}), + * new Node({type: 'baz'}) + * ] + * }); + * console.log(utils.hasType(node, 'xyz')); // false + * console.log(utils.hasType(node, 'baz')); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {String} `type` + * @return {Boolean} + * @api public + */ + +utils.hasType = function(node, type) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + if (!Array.isArray(node.nodes)) return false; + for (var i = 0; i < node.nodes.length; i++) { + if (utils.isType(node.nodes[i], type)) { + return true; + } + } + return false; +}; + +/** + * Returns the first node from `node.nodes` of the given `type` + * + * ```js + * var node = new Node({ + * type: 'foo', + * nodes: [ + * new Node({type: 'text', val: 'abc'}), + * new Node({type: 'text', val: 'xyz'}) + * ] + * }); + * + * var textNode = utils.firstOfType(node.nodes, 'text'); + * console.log(textNode.val); + * //=> 'abc' + * ``` + * @param {Array} `nodes` + * @param {String} `type` + * @return {Object|undefined} Returns the first matching node or undefined. + * @api public + */ + +utils.firstOfType = function(nodes, type) { + for (var i = 0; i < nodes.length; i++) { + var node = nodes[i]; + if (utils.isType(node, type)) { + return node; + } + } +}; + +/** + * Returns the node at the specified index, or the first node of the + * given `type` from `node.nodes`. + * + * ```js + * var node = new Node({ + * type: 'foo', + * nodes: [ + * new Node({type: 'text', val: 'abc'}), + * new Node({type: 'text', val: 'xyz'}) + * ] + * }); + * + * var nodeOne = utils.findNode(node.nodes, 'text'); + * console.log(nodeOne.val); + * //=> 'abc' + * + * var nodeTwo = utils.findNode(node.nodes, 1); + * console.log(nodeTwo.val); + * //=> 'xyz' + * ``` + * + * @param {Array} `nodes` + * @param {String|Number} `type` Node type or index. + * @return {Object} Returns a node or undefined. + * @api public + */ + +utils.findNode = function(nodes, type) { + if (!Array.isArray(nodes)) { + return null; + } + if (typeof type === 'number') { + return nodes[type]; + } + return utils.firstOfType(nodes, type); +}; + +/** + * Returns true if the given node is an "*.open" node. + * + * ```js + * var Node = require('snapdragon-node'); + * var brace = new Node({type: 'brace'}); + * var open = new Node({type: 'brace.open'}); + * var close = new Node({type: 'brace.close'}); + * + * console.log(utils.isOpen(brace)); // false + * console.log(utils.isOpen(open)); // true + * console.log(utils.isOpen(close)); // false + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Boolean} + * @api public + */ + +utils.isOpen = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + return node.type.slice(-5) === '.open'; +}; + +/** + * Returns true if the given node is a "*.close" node. + * + * ```js + * var Node = require('snapdragon-node'); + * var brace = new Node({type: 'brace'}); + * var open = new Node({type: 'brace.open'}); + * var close = new Node({type: 'brace.close'}); + * + * console.log(utils.isClose(brace)); // false + * console.log(utils.isClose(open)); // false + * console.log(utils.isClose(close)); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Boolean} + * @api public + */ + +utils.isClose = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + return node.type.slice(-6) === '.close'; +}; + +/** + * Returns true if `node.nodes` **has** an `.open` node + * + * ```js + * var Node = require('snapdragon-node'); + * var brace = new Node({ + * type: 'brace', + * nodes: [] + * }); + * + * var open = new Node({type: 'brace.open'}); + * console.log(utils.hasOpen(brace)); // false + * + * brace.pushNode(open); + * console.log(utils.hasOpen(brace)); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Boolean} + * @api public + */ + +utils.hasOpen = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + var first = node.first || node.nodes ? node.nodes[0] : null; + if (utils.isNode(first)) { + return first.type === node.type + '.open'; + } + return false; +}; + +/** + * Returns true if `node.nodes` **has** a `.close` node + * + * ```js + * var Node = require('snapdragon-node'); + * var brace = new Node({ + * type: 'brace', + * nodes: [] + * }); + * + * var close = new Node({type: 'brace.close'}); + * console.log(utils.hasClose(brace)); // false + * + * brace.pushNode(close); + * console.log(utils.hasClose(brace)); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Boolean} + * @api public + */ + +utils.hasClose = function(node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + var last = node.last || node.nodes ? node.nodes[node.nodes.length - 1] : null; + if (utils.isNode(last)) { + return last.type === node.type + '.close'; + } + return false; +}; + +/** + * Returns true if `node.nodes` has both `.open` and `.close` nodes + * + * ```js + * var Node = require('snapdragon-node'); + * var brace = new Node({ + * type: 'brace', + * nodes: [] + * }); + * + * var open = new Node({type: 'brace.open'}); + * var close = new Node({type: 'brace.close'}); + * console.log(utils.hasOpen(brace)); // false + * console.log(utils.hasClose(brace)); // false + * + * brace.pushNode(open); + * brace.pushNode(close); + * console.log(utils.hasOpen(brace)); // true + * console.log(utils.hasClose(brace)); // true + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Boolean} + * @api public + */ + +utils.hasOpenAndClose = function(node) { + return utils.hasOpen(node) && utils.hasClose(node); +}; + +/** + * Push the given `node` onto the `state.inside` array for the + * given type. This array is used as a specialized "stack" for + * only the given `node.type`. + * + * ```js + * var state = { inside: {}}; + * var node = new Node({type: 'brace'}); + * utils.addType(state, node); + * console.log(state.inside); + * //=> { brace: [{type: 'brace'}] } + * ``` + * @param {Object} `state` The `compiler.state` object or custom state object. + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Array} Returns the `state.inside` stack for the given type. + * @api public + */ + +utils.addType = function(state, node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isObject(state), 'expected state to be an object'); + + var type = node.parent + ? node.parent.type + : node.type.replace(/\.open$/, ''); + + if (!state.hasOwnProperty('inside')) { + state.inside = {}; + } + if (!state.inside.hasOwnProperty(type)) { + state.inside[type] = []; + } + + var arr = state.inside[type]; + arr.push(node); + return arr; +}; + +/** + * Remove the given `node` from the `state.inside` array for the + * given type. This array is used as a specialized "stack" for + * only the given `node.type`. + * + * ```js + * var state = { inside: {}}; + * var node = new Node({type: 'brace'}); + * utils.addType(state, node); + * console.log(state.inside); + * //=> { brace: [{type: 'brace'}] } + * utils.removeType(state, node); + * //=> { brace: [] } + * ``` + * @param {Object} `state` The `compiler.state` object or custom state object. + * @param {Object} `node` Instance of [snapdragon-node][] + * @return {Array} Returns the `state.inside` stack for the given type. + * @api public + */ + +utils.removeType = function(state, node) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isObject(state), 'expected state to be an object'); + + var type = node.parent + ? node.parent.type + : node.type.replace(/\.close$/, ''); + + if (state.inside.hasOwnProperty(type)) { + return state.inside[type].pop(); + } +}; + +/** + * Returns true if `node.val` is an empty string, or `node.nodes` does + * not contain any non-empty text nodes. + * + * ```js + * var node = new Node({type: 'text'}); + * utils.isEmpty(node); //=> true + * node.val = 'foo'; + * utils.isEmpty(node); //=> false + * ``` + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {Function} `fn` + * @return {Boolean} + * @api public + */ + +utils.isEmpty = function(node, fn) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + + if (!Array.isArray(node.nodes)) { + if (node.type !== 'text') { + return true; + } + if (typeof fn === 'function') { + return fn(node, node.parent); + } + return !utils.trim(node.val); + } + + for (var i = 0; i < node.nodes.length; i++) { + var child = node.nodes[i]; + if (utils.isOpen(child) || utils.isClose(child)) { + continue; + } + if (!utils.isEmpty(child, fn)) { + return false; + } + } + + return true; +}; + +/** + * Returns true if the `state.inside` stack for the given type exists + * and has one or more nodes on it. + * + * ```js + * var state = { inside: {}}; + * var node = new Node({type: 'brace'}); + * console.log(utils.isInsideType(state, 'brace')); //=> false + * utils.addType(state, node); + * console.log(utils.isInsideType(state, 'brace')); //=> true + * utils.removeType(state, node); + * console.log(utils.isInsideType(state, 'brace')); //=> false + * ``` + * @param {Object} `state` + * @param {String} `type` + * @return {Boolean} + * @api public + */ + +utils.isInsideType = function(state, type) { + assert(isObject(state), 'expected state to be an object'); + assert(isString(type), 'expected type to be a string'); + + if (!state.hasOwnProperty('inside')) { + return false; + } + + if (!state.inside.hasOwnProperty(type)) { + return false; + } + + return state.inside[type].length > 0; +}; + +/** + * Returns true if `node` is either a child or grand-child of the given `type`, + * or `state.inside[type]` is a non-empty array. + * + * ```js + * var state = { inside: {}}; + * var node = new Node({type: 'brace'}); + * var open = new Node({type: 'brace.open'}); + * console.log(utils.isInside(state, open, 'brace')); //=> false + * utils.pushNode(node, open); + * console.log(utils.isInside(state, open, 'brace')); //=> true + * ``` + * @param {Object} `state` Either the `compiler.state` object, if it exists, or a user-supplied state object. + * @param {Object} `node` Instance of [snapdragon-node][] + * @param {String} `type` The `node.type` to check for. + * @return {Boolean} + * @api public + */ + +utils.isInside = function(state, node, type) { + assert(utils.isNode(node), 'expected node to be an instance of Node'); + assert(isObject(state), 'expected state to be an object'); + + if (Array.isArray(type)) { + for (var i = 0; i < type.length; i++) { + if (utils.isInside(state, node, type[i])) { + return true; + } + } + return false; + } + + var parent = node.parent; + if (typeof type === 'string') { + return (parent && parent.type === type) || utils.isInsideType(state, type); + } + + if (typeOf(type) === 'regexp') { + if (parent && parent.type && type.test(parent.type)) { + return true; + } + + var keys = Object.keys(state.inside); + var len = keys.length; + var idx = -1; + while (++idx < len) { + var key = keys[idx]; + var val = state.inside[key]; + + if (Array.isArray(val) && val.length !== 0 && type.test(key)) { + return true; + } + } + } + return false; +}; + +/** + * Get the last `n` element from the given `array`. Used for getting + * a node from `node.nodes.` + * + * @param {Array} `array` + * @param {Number} `n` + * @return {undefined} + * @api public + */ + +utils.last = function(arr, n) { + return arr[arr.length - (n || 1)]; +}; + +/** + * Cast the given `val` to an array. + * + * ```js + * console.log(utils.arrayify('')); + * //=> [] + * console.log(utils.arrayify('foo')); + * //=> ['foo'] + * console.log(utils.arrayify(['foo'])); + * //=> ['foo'] + * ``` + * @param {any} `val` + * @return {Array} + * @api public + */ + +utils.arrayify = function(val) { + if (typeof val === 'string' && val !== '') { + return [val]; + } + if (!Array.isArray(val)) { + return []; + } + return val; +}; + +/** + * Convert the given `val` to a string by joining with `,`. Useful + * for creating a cheerio/CSS/DOM-style selector from a list of strings. + * + * @param {any} `val` + * @return {Array} + * @api public + */ + +utils.stringify = function(val) { + return utils.arrayify(val).join(','); +}; + +/** + * Ensure that the given value is a string and call `.trim()` on it, + * or return an empty string. + * + * @param {String} `str` + * @return {String} + * @api public + */ + +utils.trim = function(str) { + return typeof str === 'string' ? str.trim() : ''; +}; + +/** + * Return true if val is an object + */ + +function isObject(val) { + return typeOf(val) === 'object'; +} + +/** + * Return true if val is a string + */ + +function isString(val) { + return typeof val === 'string'; +} + +/** + * Return true if val is a function + */ + +function isFunction(val) { + return typeof val === 'function'; +} + +/** + * Return true if val is an array + */ + +function isArray(val) { + return Array.isArray(val); +} + +/** + * Shim to ensure the `.append` methods work with any version of snapdragon + */ + +function append(compiler, val, node) { + if (typeof compiler.append !== 'function') { + return compiler.emit(val, node); + } + return compiler.append(val, node); +} + +/** + * Simplified assertion. Throws an error is `val` is falsey. + */ + +function assert(val, message) { + if (!val) throw new Error(message); +} + + +/***/ }), +/* 329 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var Snapdragon = __webpack_require__(66); +var compilers = __webpack_require__(135); +var parsers = __webpack_require__(138); +var utils = __webpack_require__(75); + +/** + * Customize Snapdragon parser and renderer + */ + +function Braces(options) { + this.options = utils.extend({}, options); +} + +/** + * Initialize braces + */ + +Braces.prototype.init = function(options) { + var opts = utils.createOptions({}, this.options, options); + this.snapdragon = this.options.snapdragon || new Snapdragon(opts); + this.compiler = this.snapdragon.compiler; + this.parser = this.snapdragon.parser; + + compilers(this.snapdragon, opts); + parsers(this.snapdragon, opts); + + /** + * Call Snapdragon `.parse` method. When AST is returned, we check to + * see if any unclosed braces are left on the stack and, if so, we iterate + * over the stack and correct the AST so that compilers are called in the correct + * order and unbalance braces are properly escaped. + */ + + utils.define(this.snapdragon, 'parse', function(pattern, options) { + var parsed = Snapdragon.prototype.parse.apply(this, arguments); + this.parser.ast.input = pattern; + + var stack = this.parser.stack; + while (stack.length) { + addParent({type: 'brace.close', val: ''}, stack.pop()); + } + + function addParent(node, parent) { + utils.define(node, 'parent', parent); + parent.nodes.push(node); + } + + // add non-enumerable parser reference + utils.define(parsed, 'parser', this.parser); + return parsed; + }); +}; + +/** + * Lazily initialize braces + */ + +Braces.prototype.lazyInit = function(options) { + if (!this.isInitialized) { + this.isInitialized = true; + this.init(options); + } +}; + +/** + * Decorate `.parse` method + */ + +Braces.prototype.parse = function(ast, options) { + if (utils.isObject(ast) && ast.nodes) return ast; + this.lazyInit(options); + return this.snapdragon.parse(ast, options); +}; + +/** + * Decorate `.compile` method + */ + +Braces.prototype.compile = function(ast, options) { + if (typeof ast === 'string') { + ast = this.parse(ast, options); + } else { + this.lazyInit(options); + } + var res = this.snapdragon.compile(ast, options); + return res; +}; + +/** + * Expand + */ + +Braces.prototype.expand = function(pattern) { + var ast = this.parse(pattern, {expand: true}); + return this.compile(ast, {expand: true}); +}; + +/** + * Optimize + */ + +Braces.prototype.optimize = function(pattern) { + var ast = this.parse(pattern, {optimize: true}); + return this.compile(ast, {optimize: true}); +}; + +/** + * Expose `Braces` + */ + +module.exports = Braces; + + +/***/ }), +/* 330 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var util = __webpack_require__(14); +var define = __webpack_require__(44); +var CacheBase = __webpack_require__(331); +var Emitter = __webpack_require__(139); +var isObject = __webpack_require__(30); +var merge = __webpack_require__(345); +var pascal = __webpack_require__(348); +var cu = __webpack_require__(349); + +/** + * Optionally define a custom `cache` namespace to use. + */ + +function namespace(name) { + var Cache = name ? CacheBase.namespace(name) : CacheBase; + var fns = []; + + /** + * Create an instance of `Base` with the given `config` and `options`. + * + * ```js + * // initialize with `config` and `options` + * var app = new Base({isApp: true}, {abc: true}); + * app.set('foo', 'bar'); + * + * // values defined with the given `config` object will be on the root of the instance + * console.log(app.baz); //=> undefined + * console.log(app.foo); //=> 'bar' + * // or use `.get` + * console.log(app.get('isApp')); //=> true + * console.log(app.get('foo')); //=> 'bar' + * + * // values defined with the given `options` object will be on `app.options + * console.log(app.options.abc); //=> true + * ``` + * + * @param {Object} `config` If supplied, this object is passed to [cache-base][] to merge onto the the instance upon instantiation. + * @param {Object} `options` If supplied, this object is used to initialize the `base.options` object. + * @api public + */ + + function Base(config, options) { + if (!(this instanceof Base)) { + return new Base(config, options); + } + Cache.call(this, config); + this.is('base'); + this.initBase(config, options); + } + + /** + * Inherit cache-base + */ + + util.inherits(Base, Cache); + + /** + * Add static emitter methods + */ + + Emitter(Base); + + /** + * Initialize `Base` defaults with the given `config` object + */ + + Base.prototype.initBase = function(config, options) { + this.options = merge({}, this.options, options); + this.cache = this.cache || {}; + this.define('registered', {}); + if (name) this[name] = {}; + + // make `app._callbacks` non-enumerable + this.define('_callbacks', this._callbacks); + if (isObject(config)) { + this.visit('set', config); + } + Base.run(this, 'use', fns); + }; + + /** + * Set the given `name` on `app._name` and `app.is*` properties. Used for doing + * lookups in plugins. + * + * ```js + * app.is('foo'); + * console.log(app._name); + * //=> 'foo' + * console.log(app.isFoo); + * //=> true + * app.is('bar'); + * console.log(app.isFoo); + * //=> true + * console.log(app.isBar); + * //=> true + * console.log(app._name); + * //=> 'bar' + * ``` + * @name .is + * @param {String} `name` + * @return {Boolean} + * @api public + */ + + Base.prototype.is = function(name) { + if (typeof name !== 'string') { + throw new TypeError('expected name to be a string'); + } + this.define('is' + pascal(name), true); + this.define('_name', name); + this.define('_appname', name); + return this; + }; + + /** + * Returns true if a plugin has already been registered on an instance. + * + * Plugin implementors are encouraged to use this first thing in a plugin + * to prevent the plugin from being called more than once on the same + * instance. + * + * ```js + * var base = new Base(); + * base.use(function(app) { + * if (app.isRegistered('myPlugin')) return; + * // do stuff to `app` + * }); + * + * // to also record the plugin as being registered + * base.use(function(app) { + * if (app.isRegistered('myPlugin', true)) return; + * // do stuff to `app` + * }); + * ``` + * @name .isRegistered + * @emits `plugin` Emits the name of the plugin being registered. Useful for unit tests, to ensure plugins are only registered once. + * @param {String} `name` The plugin name. + * @param {Boolean} `register` If the plugin if not already registered, to record it as being registered pass `true` as the second argument. + * @return {Boolean} Returns true if a plugin is already registered. + * @api public + */ + + Base.prototype.isRegistered = function(name, register) { + if (this.registered.hasOwnProperty(name)) { + return true; + } + if (register !== false) { + this.registered[name] = true; + this.emit('plugin', name); + } + return false; + }; + + /** + * Define a plugin function to be called immediately upon init. Plugins are chainable + * and expose the following arguments to the plugin function: + * + * - `app`: the current instance of `Base` + * - `base`: the [first ancestor instance](#base) of `Base` + * + * ```js + * var app = new Base() + * .use(foo) + * .use(bar) + * .use(baz) + * ``` + * @name .use + * @param {Function} `fn` plugin function to call + * @return {Object} Returns the item instance for chaining. + * @api public + */ + + Base.prototype.use = function(fn) { + fn.call(this, this); + return this; + }; + + /** + * The `.define` method is used for adding non-enumerable property on the instance. + * Dot-notation is **not supported** with `define`. + * + * ```js + * // arbitrary `render` function using lodash `template` + * app.define('render', function(str, locals) { + * return _.template(str)(locals); + * }); + * ``` + * @name .define + * @param {String} `key` The name of the property to define. + * @param {any} `value` + * @return {Object} Returns the instance for chaining. + * @api public + */ + + Base.prototype.define = function(key, val) { + if (isObject(key)) { + return this.visit('define', key); + } + define(this, key, val); + return this; + }; + + /** + * Mix property `key` onto the Base prototype. If base is inherited using + * `Base.extend` this method will be overridden by a new `mixin` method that will + * only add properties to the prototype of the inheriting application. + * + * ```js + * app.mixin('foo', function() { + * // do stuff + * }); + * ``` + * @name .mixin + * @param {String} `key` + * @param {Object|Array} `val` + * @return {Object} Returns the `base` instance for chaining. + * @api public + */ + + Base.prototype.mixin = function(key, val) { + Base.prototype[key] = val; + return this; + }; + + /** + * Non-enumberable mixin array, used by the static [Base.mixin]() method. + */ + + Base.prototype.mixins = Base.prototype.mixins || []; + + /** + * Getter/setter used when creating nested instances of `Base`, for storing a reference + * to the first ancestor instance. This works by setting an instance of `Base` on the `parent` + * property of a "child" instance. The `base` property defaults to the current instance if + * no `parent` property is defined. + * + * ```js + * // create an instance of `Base`, this is our first ("base") instance + * var first = new Base(); + * first.foo = 'bar'; // arbitrary property, to make it easier to see what's happening later + * + * // create another instance + * var second = new Base(); + * // create a reference to the first instance (`first`) + * second.parent = first; + * + * // create another instance + * var third = new Base(); + * // create a reference to the previous instance (`second`) + * // repeat this pattern every time a "child" instance is created + * third.parent = second; + * + * // we can always access the first instance using the `base` property + * console.log(first.base.foo); + * //=> 'bar' + * console.log(second.base.foo); + * //=> 'bar' + * console.log(third.base.foo); + * //=> 'bar' + * // and now you know how to get to third base ;) + * ``` + * @name .base + * @api public + */ + + Object.defineProperty(Base.prototype, 'base', { + configurable: true, + get: function() { + return this.parent ? this.parent.base : this; + } + }); + + /** + * Static method for adding global plugin functions that will + * be added to an instance when created. + * + * ```js + * Base.use(function(app) { + * app.foo = 'bar'; + * }); + * var app = new Base(); + * console.log(app.foo); + * //=> 'bar' + * ``` + * @name #use + * @param {Function} `fn` Plugin function to use on each instance. + * @return {Object} Returns the `Base` constructor for chaining + * @api public + */ + + define(Base, 'use', function(fn) { + fns.push(fn); + return Base; + }); + + /** + * Run an array of functions by passing each function + * to a method on the given object specified by the given property. + * + * @param {Object} `obj` Object containing method to use. + * @param {String} `prop` Name of the method on the object to use. + * @param {Array} `arr` Array of functions to pass to the method. + */ + + define(Base, 'run', function(obj, prop, arr) { + var len = arr.length, i = 0; + while (len--) { + obj[prop](arr[i++]); + } + return Base; + }); + + /** + * Static method for inheriting the prototype and static methods of the `Base` class. + * This method greatly simplifies the process of creating inheritance-based applications. + * See [static-extend][] for more details. + * + * ```js + * var extend = cu.extend(Parent); + * Parent.extend(Child); + * + * // optional methods + * Parent.extend(Child, { + * foo: function() {}, + * bar: function() {} + * }); + * ``` + * @name #extend + * @param {Function} `Ctor` constructor to extend + * @param {Object} `methods` Optional prototype properties to mix in. + * @return {Object} Returns the `Base` constructor for chaining + * @api public + */ + + define(Base, 'extend', cu.extend(Base, function(Ctor, Parent) { + Ctor.prototype.mixins = Ctor.prototype.mixins || []; + + define(Ctor, 'mixin', function(fn) { + var mixin = fn(Ctor.prototype, Ctor); + if (typeof mixin === 'function') { + Ctor.prototype.mixins.push(mixin); + } + return Ctor; + }); + + define(Ctor, 'mixins', function(Child) { + Base.run(Child, 'mixin', Ctor.prototype.mixins); + return Ctor; + }); + + Ctor.prototype.mixin = function(key, value) { + Ctor.prototype[key] = value; + return this; + }; + return Base; + })); + + /** + * Used for adding methods to the `Base` prototype, and/or to the prototype of child instances. + * When a mixin function returns a function, the returned function is pushed onto the `.mixins` + * array, making it available to be used on inheriting classes whenever `Base.mixins()` is + * called (e.g. `Base.mixins(Child)`). + * + * ```js + * Base.mixin(function(proto) { + * proto.foo = function(msg) { + * return 'foo ' + msg; + * }; + * }); + * ``` + * @name #mixin + * @param {Function} `fn` Function to call + * @return {Object} Returns the `Base` constructor for chaining + * @api public + */ + + define(Base, 'mixin', function(fn) { + var mixin = fn(Base.prototype, Base); + if (typeof mixin === 'function') { + Base.prototype.mixins.push(mixin); + } + return Base; + }); + + /** + * Static method for running global mixin functions against a child constructor. + * Mixins must be registered before calling this method. + * + * ```js + * Base.extend(Child); + * Base.mixins(Child); + * ``` + * @name #mixins + * @param {Function} `Child` Constructor function of a child class + * @return {Object} Returns the `Base` constructor for chaining + * @api public + */ + + define(Base, 'mixins', function(Child) { + Base.run(Child, 'mixin', Base.prototype.mixins); + return Base; + }); + + /** + * Similar to `util.inherit`, but copies all static properties, prototype properties, and + * getters/setters from `Provider` to `Receiver`. See [class-utils][]{#inherit} for more details. + * + * ```js + * Base.inherit(Foo, Bar); + * ``` + * @name #inherit + * @param {Function} `Receiver` Receiving (child) constructor + * @param {Function} `Provider` Providing (parent) constructor + * @return {Object} Returns the `Base` constructor for chaining + * @api public + */ + + define(Base, 'inherit', cu.inherit); + define(Base, 'bubble', cu.bubble); + return Base; +} + +/** + * Expose `Base` with default settings + */ + +module.exports = namespace(); + +/** + * Allow users to define a namespace + */ + +module.exports.namespace = namespace; + + +/***/ }), +/* 331 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var isObject = __webpack_require__(30); +var Emitter = __webpack_require__(139); +var visit = __webpack_require__(332); +var toPath = __webpack_require__(141); +var union = __webpack_require__(334); +var del = __webpack_require__(336); +var get = __webpack_require__(78); +var has = __webpack_require__(341); +var set = __webpack_require__(344); + +/** + * Create a `Cache` constructor that when instantiated will + * store values on the given `prop`. + * + * ```js + * var Cache = require('cache-base').namespace('data'); + * var cache = new Cache(); + * + * cache.set('foo', 'bar'); + * //=> {data: {foo: 'bar'}} + * ``` + * @param {String} `prop` The property name to use for storing values. + * @return {Function} Returns a custom `Cache` constructor + * @api public + */ + +function namespace(prop) { + + /** + * Create a new `Cache`. Internally the `Cache` constructor is created using + * the `namespace` function, with `cache` defined as the storage object. + * + * ```js + * var app = new Cache(); + * ``` + * @param {Object} `cache` Optionally pass an object to initialize with. + * @constructor + * @api public + */ + + function Cache(cache) { + if (prop) { + this[prop] = {}; + } + if (cache) { + this.set(cache); + } + } + + /** + * Inherit Emitter + */ + + Emitter(Cache.prototype); + + /** + * Assign `value` to `key`. Also emits `set` with + * the key and value. + * + * ```js + * app.on('set', function(key, val) { + * // do something when `set` is emitted + * }); + * + * app.set(key, value); + * + * // also takes an object or array + * app.set({name: 'Halle'}); + * app.set([{foo: 'bar'}, {baz: 'quux'}]); + * console.log(app); + * //=> {name: 'Halle', foo: 'bar', baz: 'quux'} + * ``` + * + * @name .set + * @emits `set` with `key` and `value` as arguments. + * @param {String} `key` + * @param {any} `value` + * @return {Object} Returns the instance for chaining. + * @api public + */ + + Cache.prototype.set = function(key, val) { + if (Array.isArray(key) && arguments.length === 2) { + key = toPath(key); + } + if (isObject(key) || Array.isArray(key)) { + this.visit('set', key); + } else { + set(prop ? this[prop] : this, key, val); + this.emit('set', key, val); + } + return this; + }; + + /** + * Union `array` to `key`. Also emits `set` with + * the key and value. + * + * ```js + * app.union('a.b', ['foo']); + * app.union('a.b', ['bar']); + * console.log(app.get('a')); + * //=> {b: ['foo', 'bar']} + * ``` + * @name .union + * @param {String} `key` + * @param {any} `value` + * @return {Object} Returns the instance for chaining. + * @api public + */ + + Cache.prototype.union = function(key, val) { + if (Array.isArray(key) && arguments.length === 2) { + key = toPath(key); + } + var ctx = prop ? this[prop] : this; + union(ctx, key, arrayify(val)); + this.emit('union', val); + return this; + }; + + /** + * Return the value of `key`. Dot notation may be used + * to get [nested property values][get-value]. + * + * ```js + * app.set('a.b.c', 'd'); + * app.get('a.b'); + * //=> {c: 'd'} + * + * app.get(['a', 'b']); + * //=> {c: 'd'} + * ``` + * + * @name .get + * @emits `get` with `key` and `value` as arguments. + * @param {String} `key` The name of the property to get. Dot-notation may be used. + * @return {any} Returns the value of `key` + * @api public + */ + + Cache.prototype.get = function(key) { + key = toPath(arguments); + + var ctx = prop ? this[prop] : this; + var val = get(ctx, key); + + this.emit('get', key, val); + return val; + }; + + /** + * Return true if app has a stored value for `key`, + * false only if value is `undefined`. + * + * ```js + * app.set('foo', 'bar'); + * app.has('foo'); + * //=> true + * ``` + * + * @name .has + * @emits `has` with `key` and true or false as arguments. + * @param {String} `key` + * @return {Boolean} + * @api public + */ + + Cache.prototype.has = function(key) { + key = toPath(arguments); + + var ctx = prop ? this[prop] : this; + var val = get(ctx, key); + + var has = typeof val !== 'undefined'; + this.emit('has', key, has); + return has; + }; + + /** + * Delete one or more properties from the instance. + * + * ```js + * app.del(); // delete all + * // or + * app.del('foo'); + * // or + * app.del(['foo', 'bar']); + * ``` + * @name .del + * @emits `del` with the `key` as the only argument. + * @param {String|Array} `key` Property name or array of property names. + * @return {Object} Returns the instance for chaining. + * @api public + */ + + Cache.prototype.del = function(key) { + if (Array.isArray(key)) { + this.visit('del', key); + } else { + del(prop ? this[prop] : this, key); + this.emit('del', key); + } + return this; + }; + + /** + * Reset the entire cache to an empty object. + * + * ```js + * app.clear(); + * ``` + * @api public + */ + + Cache.prototype.clear = function() { + if (prop) { + this[prop] = {}; + } + }; + + /** + * Visit `method` over the properties in the given object, or map + * visit over the object-elements in an array. + * + * @name .visit + * @param {String} `method` The name of the `base` method to call. + * @param {Object|Array} `val` The object or array to iterate over. + * @return {Object} Returns the instance for chaining. + * @api public + */ + + Cache.prototype.visit = function(method, val) { + visit(this, method, val); + return this; + }; + + return Cache; } -Parser.prototype = parser;parser.Parser = Parser; -return new Parser; -})(); + +/** + * Cast val to an array + */ + +function arrayify(val) { + return val ? (Array.isArray(val) ? val : [val]) : []; +} + +/** + * Expose `Cache` + */ + +module.exports = namespace(); + +/** + * Expose `Cache.namespace` + */ + +module.exports.namespace = namespace; + + +/***/ }), +/* 332 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * collection-visit + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var visit = __webpack_require__(140); +var mapVisit = __webpack_require__(333); + +module.exports = function(collection, method, val) { + var result; + + if (typeof val === 'string' && (method in collection)) { + var args = [].slice.call(arguments, 2); + result = collection[method].apply(collection, args); + } else if (Array.isArray(val)) { + result = mapVisit.apply(null, arguments); + } else { + result = visit.apply(null, arguments); + } + + if (typeof result !== 'undefined') { + return result; + } + + return collection; +}; + + +/***/ }), +/* 333 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var util = __webpack_require__(14); +var visit = __webpack_require__(140); + +/** + * Map `visit` over an array of objects. + * + * @param {Object} `collection` The context in which to invoke `method` + * @param {String} `method` Name of the method to call on `collection` + * @param {Object} `arr` Array of objects. + */ + +module.exports = function mapVisit(collection, method, val) { + if (isObject(val)) { + return visit.apply(null, arguments); + } + + if (!Array.isArray(val)) { + throw new TypeError('expected an array: ' + util.inspect(val)); + } + + var args = [].slice.call(arguments, 3); + + for (var i = 0; i < val.length; i++) { + var ele = val[i]; + if (isObject(ele)) { + visit.apply(null, [collection, method, ele].concat(args)); + } else { + collection[method].apply(collection, [ele].concat(args)); + } + } +}; + +function isObject(val) { + return val && (typeof val === 'function' || (!Array.isArray(val) && typeof val === 'object')); +} + + +/***/ }), +/* 334 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var isObject = __webpack_require__(74); +var union = __webpack_require__(142); +var get = __webpack_require__(78); +var set = __webpack_require__(335); + +module.exports = function unionValue(obj, prop, value) { + if (!isObject(obj)) { + throw new TypeError('union-value expects the first argument to be an object.'); + } + + if (typeof prop !== 'string') { + throw new TypeError('union-value expects `prop` to be a string.'); + } + + var arr = arrayify(get(obj, prop)); + set(obj, prop, union(arr, arrayify(value))); + return obj; +}; + +function arrayify(val) { + if (val === null || typeof val === 'undefined') { + return []; + } + if (Array.isArray(val)) { + return val; + } + return [val]; +} + + +/***/ }), +/* 335 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * set-value + * + * Copyright (c) 2014-2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var toPath = __webpack_require__(141); +var extend = __webpack_require__(20); +var isPlainObject = __webpack_require__(76); +var isObject = __webpack_require__(74); + +module.exports = function(obj, path, val) { + if (!isObject(obj)) { + return obj; + } + + if (Array.isArray(path)) { + path = toPath(path); + } + + if (typeof path !== 'string') { + return obj; + } + + var segs = path.split('.'); + var len = segs.length, i = -1; + var res = obj; + var last; + + while (++i < len) { + var key = segs[i]; + + while (key[key.length - 1] === '\\') { + key = key.slice(0, -1) + '.' + segs[++i]; + } + + if (i === len - 1) { + last = key; + break; + } + + if (!isObject(obj[key])) { + obj[key] = {}; + } + obj = obj[key]; + } + + if (obj.hasOwnProperty(last) && isObject(obj[last])) { + if (isPlainObject(val)) { + extend(obj[last], val); + } else { + obj[last] = val; + } + + } else { + obj[last] = val; + } + return res; +}; + + + +/***/ }), +/* 336 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * unset-value + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isObject = __webpack_require__(30); +var has = __webpack_require__(337); + +module.exports = function unset(obj, prop) { + if (!isObject(obj)) { + throw new TypeError('expected an object.'); + } + if (obj.hasOwnProperty(prop)) { + delete obj[prop]; + return true; + } + + if (has(obj, prop)) { + var segs = prop.split('.'); + var last = segs.pop(); + while (segs.length && segs[segs.length - 1].slice(-1) === '\\') { + last = segs.pop().slice(0, -1) + '.' + last; + } + while (segs.length) obj = obj[prop = segs.shift()]; + return (delete obj[last]); + } + return true; +}; + + +/***/ }), +/* 337 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * has-value + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +var isObject = __webpack_require__(338); +var hasValues = __webpack_require__(340); +var get = __webpack_require__(78); + +module.exports = function(obj, prop, noZero) { + if (isObject(obj)) { + return hasValues(get(obj, prop), noZero); + } + return hasValues(obj, prop); +}; + + +/***/ }), +/* 338 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * isobject + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +var isArray = __webpack_require__(339); + +module.exports = function isObject(val) { + return val != null && typeof val === 'object' && isArray(val) === false; +}; + + +/***/ }), +/* 339 */ +/***/ (function(module, exports) { + +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + + +/***/ }), +/* 340 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * has-values + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +module.exports = function hasValue(o, noZero) { + if (o === null || o === undefined) { + return false; + } + + if (typeof o === 'boolean') { + return true; + } + + if (typeof o === 'number') { + if (o === 0 && noZero === true) { + return false; + } + return true; + } + + if (o.length !== undefined) { + return o.length !== 0; + } + + for (var key in o) { + if (o.hasOwnProperty(key)) { + return true; + } + } + return false; +}; + + +/***/ }), +/* 341 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * has-value + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +var isObject = __webpack_require__(30); +var hasValues = __webpack_require__(342); +var get = __webpack_require__(78); + +module.exports = function(val, prop) { + return hasValues(isObject(val) && prop ? get(val, prop) : val); +}; + + +/***/ }), +/* 342 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * has-values + * + * Copyright (c) 2014-2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var typeOf = __webpack_require__(343); +var isNumber = __webpack_require__(77); + +module.exports = function hasValue(val) { + // is-number checks for NaN and other edge cases + if (isNumber(val)) { + return true; + } + + switch (typeOf(val)) { + case 'null': + case 'boolean': + case 'function': + return true; + case 'string': + case 'arguments': + return val.length !== 0; + case 'error': + return val.message !== ''; + case 'array': + var len = val.length; + if (len === 0) { + return false; + } + for (var i = 0; i < len; i++) { + if (hasValue(val[i])) { + return true; + } + } + return false; + case 'file': + case 'map': + case 'set': + return val.size !== 0; + case 'object': + var keys = Object.keys(val); + if (keys.length === 0) { + return false; + } + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (hasValue(val[key])) { + return true; + } + } + return false; + default: { + return false; + } + } +}; -if (true) { -exports.parser = spdxparse; -exports.Parser = spdxparse.Parser; -exports.parse = function () { return spdxparse.parse.apply(spdxparse, arguments); }; -exports.main = function commonjsMain(args) { - if (!args[1]) { - console.log('Usage: '+args[0]+' FILE'); - process.exit(1); +/***/ }), +/* 343 */ +/***/ (function(module, exports, __webpack_require__) { + +var isBuffer = __webpack_require__(22); +var toString = Object.prototype.toString; + +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ + +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; + } + + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; + } + + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } + + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } + + // other objects + var type = toString.call(val); + + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + if (type === '[object Promise]') { + return 'promise'; + } + + // buffer + if (isBuffer(val)) { + return 'buffer'; + } + + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } + + // must be a plain object + return 'object'; +}; + + +/***/ }), +/* 344 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * set-value + * + * Copyright (c) 2014-2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var split = __webpack_require__(136); +var extend = __webpack_require__(20); +var isPlainObject = __webpack_require__(76); +var isObject = __webpack_require__(74); + +module.exports = function(obj, prop, val) { + if (!isObject(obj)) { + return obj; + } + + if (Array.isArray(prop)) { + prop = [].concat.apply([], prop).join('.'); + } + + if (typeof prop !== 'string') { + return obj; + } + + var keys = split(prop, {sep: '.', brackets: true}); + var len = keys.length; + var idx = -1; + var current = obj; + + while (++idx < len) { + var key = keys[idx]; + if (idx !== len - 1) { + if (!isObject(current[key])) { + current[key] = {}; + } + current = current[key]; + continue; } - var source = __webpack_require__(16).readFileSync(__webpack_require__(7).normalize(args[1]), "utf8"); - return exports.parser.parse(source); + + if (isPlainObject(current[key]) && isPlainObject(val)) { + current[key] = extend({}, current[key], val); + } else { + current[key] = val; + } + } + + return obj; }; -if ( true && __webpack_require__.c[__webpack_require__.s] === module) { - exports.main(process.argv.slice(1)); + + +/***/ }), +/* 345 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var isExtendable = __webpack_require__(346); +var forIn = __webpack_require__(347); + +function mixinDeep(target, objects) { + var len = arguments.length, i = 0; + while (++i < len) { + var obj = arguments[i]; + if (isObject(obj)) { + forIn(obj, copy, target); + } + } + return target; +} + +/** + * Copy properties from the source object to the + * target object. + * + * @param {*} `val` + * @param {String} `key` + */ + +function copy(val, key) { + var obj = this[key]; + if (isObject(val) && isObject(obj)) { + mixinDeep(obj, val); + } else { + this[key] = val; + } } + +/** + * Returns true if `val` is an object or function. + * + * @param {any} val + * @return {Boolean} + */ + +function isObject(val) { + return isExtendable(val) && !Array.isArray(val); } -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(59)(module))) +/** + * Expose `mixinDeep` + */ + +module.exports = mixinDeep; + /***/ }), -/* 156 */ +/* 346 */ /***/ (function(module, exports, __webpack_require__) { -var licenseIDs = __webpack_require__(157); +"use strict"; +/*! + * is-extendable + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ -function valid(string) { - return licenseIDs.indexOf(string) > -1; -} -// Common transpositions of license identifier acronyms -var transpositions = [ - ['APGL', 'AGPL'], - ['Gpl', 'GPL'], - ['GLP', 'GPL'], - ['APL', 'Apache'], - ['ISD', 'ISC'], - ['GLP', 'GPL'], - ['IST', 'ISC'], - ['Claude', 'Clause'], - [' or later', '+'], - [' International', ''], - ['GNU', 'GPL'], - ['GUN', 'GPL'], - ['+', ''], - ['GNU GPL', 'GPL'], - ['GNU/GPL', 'GPL'], - ['GNU GLP', 'GPL'], - ['GNU General Public License', 'GPL'], - ['Gnu public license', 'GPL'], - ['GNU Public License', 'GPL'], - ['GNU GENERAL PUBLIC LICENSE', 'GPL'], - ['MTI', 'MIT'], - ['Mozilla Public License', 'MPL'], - ['WTH', 'WTF'], - ['-License', ''] -]; -var TRANSPOSED = 0; -var CORRECT = 1; +var isPlainObject = __webpack_require__(76); -// Simple corrections to nearly valid identifiers. -var transforms = [ - // e.g. 'mit' - function(argument) { - return argument.toUpperCase(); - }, - // e.g. 'MIT ' - function(argument) { - return argument.trim(); - }, - // e.g. 'M.I.T.' - function(argument) { - return argument.replace(/\./g, ''); - }, - // e.g. 'Apache- 2.0' - function(argument) { - return argument.replace(/\s+/g, ''); - }, - // e.g. 'CC BY 4.0'' - function(argument) { - return argument.replace(/\s+/g, '-'); - }, - // e.g. 'LGPLv2.1' - function(argument) { - return argument.replace('v', '-'); - }, - // e.g. 'Apache 2.0' - function(argument) { - return argument.replace(/,?\s*(\d)/, '-$1'); - }, - // e.g. 'GPL 2' - function(argument) { - return argument.replace(/,?\s*(\d)/, '-$1.0'); - }, - // e.g. 'Apache Version 2.0' - function(argument) { - return argument.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/, '-$2'); - }, - // e.g. 'Apache Version 2' - function(argument) { - return argument.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/, '-$2.0'); - }, - // e.g. 'ZLIB' - function(argument) { - return argument[0].toUpperCase() + argument.slice(1); - }, - // e.g. 'MPL/2.0' - function(argument) { - return argument.replace('/', '-'); - }, - // e.g. 'Apache 2' - function(argument) { - return argument - .replace(/\s*V\s*(\d)/, '-$1') - .replace(/(\d)$/, '$1.0'); - }, - // e.g. 'GPL-2.0-' - function(argument) { - return argument.slice(0, argument.length - 1); - }, - // e.g. 'GPL2' - function(argument) { - return argument.replace(/(\d)$/, '-$1.0'); - }, - // e.g. 'BSD 3' - function(argument) { - return argument.replace(/(-| )?(\d)$/, '-$2-Clause'); - }, - // e.g. 'BSD clause 3' - function(argument) { - return argument.replace(/(-| )clause(-| )(\d)/, '-$3-Clause'); - }, - // e.g. 'BY-NC-4.0' - function(argument) { - return 'CC-' + argument; - }, - // e.g. 'BY-NC' - function(argument) { - return 'CC-' + argument + '-4.0'; - }, - // e.g. 'Attribution-NonCommercial' - function(argument) { - return argument - .replace('Attribution', 'BY') - .replace('NonCommercial', 'NC') - .replace('NoDerivatives', 'ND') - .replace(/ (\d)/, '-$1') - .replace(/ ?International/, ''); - }, - // e.g. 'Attribution-NonCommercial' - function(argument) { - return 'CC-' + - argument - .replace('Attribution', 'BY') - .replace('NonCommercial', 'NC') - .replace('NoDerivatives', 'ND') - .replace(/ (\d)/, '-$1') - .replace(/ ?International/, '') + - '-4.0'; - } -]; +module.exports = function isExtendable(val) { + return isPlainObject(val) || typeof val === 'function' || Array.isArray(val); +}; -// If all else fails, guess that strings containing certain substrings -// meant to identify certain licenses. -var lastResorts = [ - ['UNLI', 'Unlicense'], - ['WTF', 'WTFPL'], - ['2 CLAUSE', 'BSD-2-Clause'], - ['2-CLAUSE', 'BSD-2-Clause'], - ['3 CLAUSE', 'BSD-3-Clause'], - ['3-CLAUSE', 'BSD-3-Clause'], - ['AFFERO', 'AGPL-3.0'], - ['AGPL', 'AGPL-3.0'], - ['APACHE', 'Apache-2.0'], - ['ARTISTIC', 'Artistic-2.0'], - ['Affero', 'AGPL-3.0'], - ['BEER', 'Beerware'], - ['BOOST', 'BSL-1.0'], - ['BSD', 'BSD-2-Clause'], - ['ECLIPSE', 'EPL-1.0'], - ['FUCK', 'WTFPL'], - ['GNU', 'GPL-3.0'], - ['LGPL', 'LGPL-3.0'], - ['GPL', 'GPL-3.0'], - ['MIT', 'MIT'], - ['MPL', 'MPL-2.0'], - ['X11', 'X11'], - ['ZLIB', 'Zlib'] -]; -var SUBSTRING = 0; -var IDENTIFIER = 1; +/***/ }), +/* 347 */ +/***/ (function(module, exports, __webpack_require__) { -var validTransformation = function(identifier) { - for (var i = 0; i < transforms.length; i++) { - var transformed = transforms[i](identifier); - if (transformed !== identifier && valid(transformed)) { - return transformed; +"use strict"; +/*! + * for-in + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +module.exports = function forIn(obj, fn, thisArg) { + for (var key in obj) { + if (fn.call(thisArg, obj[key], key, obj) === false) { + break; } } - return null; }; -var validLastResort = function(identifier) { - var upperCased = identifier.toUpperCase(); - for (var i = 0; i < lastResorts.length; i++) { - var lastResort = lastResorts[i]; - if (upperCased.indexOf(lastResort[SUBSTRING]) > -1) { - return lastResort[IDENTIFIER]; - } + +/***/ }), +/* 348 */ +/***/ (function(module, exports) { + +/*! + * pascalcase + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + +function pascalcase(str) { + if (typeof str !== 'string') { + throw new TypeError('expected a string.'); } - return null; + str = str.replace(/([A-Z])/g, ' $1'); + if (str.length === 1) { return str.toUpperCase(); } + str = str.replace(/^[\W_]+|[\W_]+$/g, '').toLowerCase(); + str = str.charAt(0).toUpperCase() + str.slice(1); + return str.replace(/[\W_]+(\w|$)/g, function (_, ch) { + return ch.toUpperCase(); + }); +} + +module.exports = pascalcase; + + +/***/ }), +/* 349 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var util = __webpack_require__(14); +var utils = __webpack_require__(350); + +/** + * Expose class utils + */ + +var cu = module.exports; + +/** + * Expose class utils: `cu` + */ + +cu.isObject = function isObject(val) { + return utils.isObj(val) || typeof val === 'function'; }; -var anyCorrection = function(identifier, check) { - for (var i = 0; i < transpositions.length; i++) { - var transposition = transpositions[i]; - var transposed = transposition[TRANSPOSED]; - if (identifier.indexOf(transposed) > -1) { - var corrected = identifier.replace( - transposed, - transposition[CORRECT] - ); - var checked = check(corrected); - if (checked !== null) { - return checked; +/** + * Returns true if an array has any of the given elements, or an + * object has any of the give keys. + * + * ```js + * cu.has(['a', 'b', 'c'], 'c'); + * //=> true + * + * cu.has(['a', 'b', 'c'], ['c', 'z']); + * //=> true + * + * cu.has({a: 'b', c: 'd'}, ['c', 'z']); + * //=> true + * ``` + * @param {Object} `obj` + * @param {String|Array} `val` + * @return {Boolean} + * @api public + */ + +cu.has = function has(obj, val) { + val = cu.arrayify(val); + var len = val.length; + + if (cu.isObject(obj)) { + for (var key in obj) { + if (val.indexOf(key) > -1) { + return true; } } + + var keys = cu.nativeKeys(obj); + return cu.has(keys, val); } - return null; + + if (Array.isArray(obj)) { + var arr = obj; + while (len--) { + if (arr.indexOf(val[len]) > -1) { + return true; + } + } + return false; + } + + throw new TypeError('expected an array or object.'); }; -module.exports = function(identifier) { - identifier = identifier.replace(/\+$/, ''); - if (valid(identifier)) { - return identifier; +/** + * Returns true if an array or object has all of the given values. + * + * ```js + * cu.hasAll(['a', 'b', 'c'], 'c'); + * //=> true + * + * cu.hasAll(['a', 'b', 'c'], ['c', 'z']); + * //=> false + * + * cu.hasAll({a: 'b', c: 'd'}, ['c', 'z']); + * //=> false + * ``` + * @param {Object|Array} `val` + * @param {String|Array} `values` + * @return {Boolean} + * @api public + */ + +cu.hasAll = function hasAll(val, values) { + values = cu.arrayify(values); + var len = values.length; + while (len--) { + if (!cu.has(val, values[len])) { + return false; + } } - var transformed = validTransformation(identifier); - if (transformed !== null) { - return transformed; + return true; +}; + +/** + * Cast the given value to an array. + * + * ```js + * cu.arrayify('foo'); + * //=> ['foo'] + * + * cu.arrayify(['foo']); + * //=> ['foo'] + * ``` + * + * @param {String|Array} `val` + * @return {Array} + * @api public + */ + +cu.arrayify = function arrayify(val) { + return val ? (Array.isArray(val) ? val : [val]) : []; +}; + +/** + * Noop + */ + +cu.noop = function noop() { + return; +}; + +/** + * Returns the first argument passed to the function. + */ + +cu.identity = function identity(val) { + return val; +}; + +/** + * Returns true if a value has a `contructor` + * + * ```js + * cu.hasConstructor({}); + * //=> true + * + * cu.hasConstructor(Object.create(null)); + * //=> false + * ``` + * @param {Object} `value` + * @return {Boolean} + * @api public + */ + +cu.hasConstructor = function hasConstructor(val) { + return cu.isObject(val) && typeof val.constructor !== 'undefined'; +}; + +/** + * Get the native `ownPropertyNames` from the constructor of the + * given `object`. An empty array is returned if the object does + * not have a constructor. + * + * ```js + * cu.nativeKeys({a: 'b', b: 'c', c: 'd'}) + * //=> ['a', 'b', 'c'] + * + * cu.nativeKeys(function(){}) + * //=> ['length', 'caller'] + * ``` + * + * @param {Object} `obj` Object that has a `constructor`. + * @return {Array} Array of keys. + * @api public + */ + +cu.nativeKeys = function nativeKeys(val) { + if (!cu.hasConstructor(val)) return []; + return Object.getOwnPropertyNames(val); +}; + +/** + * Returns property descriptor `key` if it's an "own" property + * of the given object. + * + * ```js + * function App() {} + * Object.defineProperty(App.prototype, 'count', { + * get: function() { + * return Object.keys(this).length; + * } + * }); + * cu.getDescriptor(App.prototype, 'count'); + * // returns: + * // { + * // get: [Function], + * // set: undefined, + * // enumerable: false, + * // configurable: false + * // } + * ``` + * + * @param {Object} `obj` + * @param {String} `key` + * @return {Object} Returns descriptor `key` + * @api public + */ + +cu.getDescriptor = function getDescriptor(obj, key) { + if (!cu.isObject(obj)) { + throw new TypeError('expected an object.'); } - transformed = anyCorrection(identifier, function(argument) { - if (valid(argument)) { - return argument; + if (typeof key !== 'string') { + throw new TypeError('expected key to be a string.'); + } + return Object.getOwnPropertyDescriptor(obj, key); +}; + +/** + * Copy a descriptor from one object to another. + * + * ```js + * function App() {} + * Object.defineProperty(App.prototype, 'count', { + * get: function() { + * return Object.keys(this).length; + * } + * }); + * var obj = {}; + * cu.copyDescriptor(obj, App.prototype, 'count'); + * ``` + * @param {Object} `receiver` + * @param {Object} `provider` + * @param {String} `name` + * @return {Object} + * @api public + */ + +cu.copyDescriptor = function copyDescriptor(receiver, provider, name) { + if (!cu.isObject(receiver)) { + throw new TypeError('expected receiving object to be an object.'); + } + if (!cu.isObject(provider)) { + throw new TypeError('expected providing object to be an object.'); + } + if (typeof name !== 'string') { + throw new TypeError('expected name to be a string.'); + } + + var val = cu.getDescriptor(provider, name); + if (val) Object.defineProperty(receiver, name, val); +}; + +/** + * Copy static properties, prototype properties, and descriptors + * from one object to another. + * + * @param {Object} `receiver` + * @param {Object} `provider` + * @param {String|Array} `omit` One or more properties to omit + * @return {Object} + * @api public + */ + +cu.copy = function copy(receiver, provider, omit) { + if (!cu.isObject(receiver)) { + throw new TypeError('expected receiving object to be an object.'); + } + if (!cu.isObject(provider)) { + throw new TypeError('expected providing object to be an object.'); + } + var props = Object.getOwnPropertyNames(provider); + var keys = Object.keys(provider); + var len = props.length, + key; + omit = cu.arrayify(omit); + + while (len--) { + key = props[len]; + + if (cu.has(keys, key)) { + utils.define(receiver, key, provider[key]); + } else if (!(key in receiver) && !cu.has(omit, key)) { + cu.copyDescriptor(receiver, provider, key); } - return validTransformation(argument); - }); - if (transformed !== null) { - return transformed; } - transformed = validLastResort(identifier); - if (transformed !== null) { - return transformed; +}; + +/** + * Inherit the static properties, prototype properties, and descriptors + * from of an object. + * + * @param {Object} `receiver` + * @param {Object} `provider` + * @param {String|Array} `omit` One or more properties to omit + * @return {Object} + * @api public + */ + +cu.inherit = function inherit(receiver, provider, omit) { + if (!cu.isObject(receiver)) { + throw new TypeError('expected receiving object to be an object.'); } - transformed = anyCorrection(identifier, validLastResort); - if (transformed !== null) { - return transformed; + if (!cu.isObject(provider)) { + throw new TypeError('expected providing object to be an object.'); } - return null; + + var keys = []; + for (var key in provider) { + keys.push(key); + receiver[key] = provider[key]; + } + + keys = keys.concat(cu.arrayify(omit)); + + var a = provider.prototype || provider; + var b = receiver.prototype || receiver; + cu.copy(b, a, keys); +}; + +/** + * Returns a function for extending the static properties, + * prototype properties, and descriptors from the `Parent` + * constructor onto `Child` constructors. + * + * ```js + * var extend = cu.extend(Parent); + * Parent.extend(Child); + * + * // optional methods + * Parent.extend(Child, { + * foo: function() {}, + * bar: function() {} + * }); + * ``` + * @param {Function} `Parent` Parent ctor + * @param {Function} `extend` Optional extend function to handle custom extensions. Useful when updating methods that require a specific prototype. + * @param {Function} `Child` Child ctor + * @param {Object} `proto` Optionally pass additional prototype properties to inherit. + * @return {Object} + * @api public + */ + +cu.extend = function() { + // keep it lazy, instead of assigning to `cu.extend` + return utils.staticExtend.apply(null, arguments); }; +/** + * Bubble up events emitted from static methods on the Parent ctor. + * + * @param {Object} `Parent` + * @param {Array} `events` Event names to bubble up + * @api public + */ -/***/ }), -/* 157 */ -/***/ (function(module) { +cu.bubble = function(Parent, events) { + events = events || []; + Parent.bubble = function(Child, arr) { + if (Array.isArray(arr)) { + events = utils.union([], events, arr); + } + var len = events.length; + var idx = -1; + while (++idx < len) { + var name = events[idx]; + Parent.on(name, Child.emit.bind(Child, name)); + } + cu.bubble(Child, events); + }; +}; -module.exports = ["Glide","Abstyles","AFL-1.1","AFL-1.2","AFL-2.0","AFL-2.1","AFL-3.0","AMPAS","APL-1.0","Adobe-Glyph","APAFML","Adobe-2006","AGPL-1.0","Afmparse","Aladdin","ADSL","AMDPLPA","ANTLR-PD","Apache-1.0","Apache-1.1","Apache-2.0","AML","APSL-1.0","APSL-1.1","APSL-1.2","APSL-2.0","Artistic-1.0","Artistic-1.0-Perl","Artistic-1.0-cl8","Artistic-2.0","AAL","Bahyph","Barr","Beerware","BitTorrent-1.0","BitTorrent-1.1","BSL-1.0","Borceux","BSD-2-Clause","BSD-2-Clause-FreeBSD","BSD-2-Clause-NetBSD","BSD-3-Clause","BSD-3-Clause-Clear","BSD-4-Clause","BSD-Protection","BSD-Source-Code","BSD-3-Clause-Attribution","0BSD","BSD-4-Clause-UC","bzip2-1.0.5","bzip2-1.0.6","Caldera","CECILL-1.0","CECILL-1.1","CECILL-2.0","CECILL-2.1","CECILL-B","CECILL-C","ClArtistic","MIT-CMU","CNRI-Jython","CNRI-Python","CNRI-Python-GPL-Compatible","CPOL-1.02","CDDL-1.0","CDDL-1.1","CPAL-1.0","CPL-1.0","CATOSL-1.1","Condor-1.1","CC-BY-1.0","CC-BY-2.0","CC-BY-2.5","CC-BY-3.0","CC-BY-4.0","CC-BY-ND-1.0","CC-BY-ND-2.0","CC-BY-ND-2.5","CC-BY-ND-3.0","CC-BY-ND-4.0","CC-BY-NC-1.0","CC-BY-NC-2.0","CC-BY-NC-2.5","CC-BY-NC-3.0","CC-BY-NC-4.0","CC-BY-NC-ND-1.0","CC-BY-NC-ND-2.0","CC-BY-NC-ND-2.5","CC-BY-NC-ND-3.0","CC-BY-NC-ND-4.0","CC-BY-NC-SA-1.0","CC-BY-NC-SA-2.0","CC-BY-NC-SA-2.5","CC-BY-NC-SA-3.0","CC-BY-NC-SA-4.0","CC-BY-SA-1.0","CC-BY-SA-2.0","CC-BY-SA-2.5","CC-BY-SA-3.0","CC-BY-SA-4.0","CC0-1.0","Crossword","CrystalStacker","CUA-OPL-1.0","Cube","curl","D-FSL-1.0","diffmark","WTFPL","DOC","Dotseqn","DSDP","dvipdfm","EPL-1.0","ECL-1.0","ECL-2.0","eGenix","EFL-1.0","EFL-2.0","MIT-advertising","MIT-enna","Entessa","ErlPL-1.1","EUDatagrid","EUPL-1.0","EUPL-1.1","Eurosym","Fair","MIT-feh","Frameworx-1.0","FreeImage","FTL","FSFAP","FSFUL","FSFULLR","Giftware","GL2PS","Glulxe","AGPL-3.0","GFDL-1.1","GFDL-1.2","GFDL-1.3","GPL-1.0","GPL-2.0","GPL-3.0","LGPL-2.1","LGPL-3.0","LGPL-2.0","gnuplot","gSOAP-1.3b","HaskellReport","HPND","IBM-pibs","IPL-1.0","ICU","ImageMagick","iMatix","Imlib2","IJG","Info-ZIP","Intel-ACPI","Intel","Interbase-1.0","IPA","ISC","JasPer-2.0","JSON","LPPL-1.0","LPPL-1.1","LPPL-1.2","LPPL-1.3a","LPPL-1.3c","Latex2e","BSD-3-Clause-LBNL","Leptonica","LGPLLR","Libpng","libtiff","LAL-1.2","LAL-1.3","LiLiQ-P-1.1","LiLiQ-Rplus-1.1","LiLiQ-R-1.1","LPL-1.02","LPL-1.0","MakeIndex","MTLL","MS-PL","MS-RL","MirOS","MITNFA","MIT","Motosoto","MPL-1.0","MPL-1.1","MPL-2.0","MPL-2.0-no-copyleft-exception","mpich2","Multics","Mup","NASA-1.3","Naumen","NBPL-1.0","NetCDF","NGPL","NOSL","NPL-1.0","NPL-1.1","Newsletr","NLPL","Nokia","NPOSL-3.0","NLOD-1.0","Noweb","NRL","NTP","Nunit","OCLC-2.0","ODbL-1.0","PDDL-1.0","OCCT-PL","OGTSL","OLDAP-2.2.2","OLDAP-1.1","OLDAP-1.2","OLDAP-1.3","OLDAP-1.4","OLDAP-2.0","OLDAP-2.0.1","OLDAP-2.1","OLDAP-2.2","OLDAP-2.2.1","OLDAP-2.3","OLDAP-2.4","OLDAP-2.5","OLDAP-2.6","OLDAP-2.7","OLDAP-2.8","OML","OPL-1.0","OSL-1.0","OSL-1.1","OSL-2.0","OSL-2.1","OSL-3.0","OpenSSL","OSET-PL-2.1","PHP-3.0","PHP-3.01","Plexus","PostgreSQL","psfrag","psutils","Python-2.0","QPL-1.0","Qhull","Rdisc","RPSL-1.0","RPL-1.1","RPL-1.5","RHeCos-1.1","RSCPL","RSA-MD","Ruby","SAX-PD","Saxpath","SCEA","SWL","SMPPL","Sendmail","SGI-B-1.0","SGI-B-1.1","SGI-B-2.0","OFL-1.0","OFL-1.1","SimPL-2.0","Sleepycat","SNIA","Spencer-86","Spencer-94","Spencer-99","SMLNJ","SugarCRM-1.1.3","SISSL","SISSL-1.2","SPL-1.0","Watcom-1.0","TCL","Unlicense","TMate","TORQUE-1.1","TOSL","Unicode-TOU","UPL-1.0","NCSA","Vim","VOSTROM","VSL-1.0","W3C-19980720","W3C","Wsuipa","Xnet","X11","Xerox","XFree86-1.1","xinetd","xpp","XSkat","YPL-1.0","YPL-1.1","Zed","Zend-2.0","Zimbra-1.3","Zimbra-1.4","Zlib","zlib-acknowledgement","ZPL-1.1","ZPL-2.0","ZPL-2.1","BSD-3-Clause-No-Nuclear-License","BSD-3-Clause-No-Nuclear-Warranty","BSD-3-Clause-No-Nuclear-License-2014","eCos-2.0","GPL-2.0-with-autoconf-exception","GPL-2.0-with-bison-exception","GPL-2.0-with-classpath-exception","GPL-2.0-with-font-exception","GPL-2.0-with-GCC-exception","GPL-3.0-with-autoconf-exception","GPL-3.0-with-GCC-exception","StandardML-NJ","WXwindows"]; /***/ }), -/* 158 */ +/* 350 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var url = __webpack_require__(103) -var gitHosts = __webpack_require__(104) -var GitHost = module.exports = __webpack_require__(159) -var protocolToRepresentationMap = { - 'git+ssh': 'sshurl', - 'git+https': 'https', - 'ssh': 'sshurl', - 'git': 'git' -} +var utils = {}; -function protocolToRepresentation (protocol) { - if (protocol.substr(-1) === ':') protocol = protocol.slice(0, -1) - return protocolToRepresentationMap[protocol] || protocol -} -var authProtocols = { - 'git:': true, - 'https:': true, - 'git+https:': true, - 'http:': true, - 'git+http:': true -} -var cache = {} +/** + * Lazily required module dependencies + */ -module.exports.fromUrl = function (giturl, opts) { - var key = giturl + JSON.stringify(opts || {}) +utils.union = __webpack_require__(142); +utils.define = __webpack_require__(351); +utils.isObj = __webpack_require__(30); +utils.staticExtend = __webpack_require__(358); + + +/** + * Expose `utils` + */ + +module.exports = utils; + + +/***/ }), +/* 351 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * define-property + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ - if (!(key in cache)) { - cache[key] = fromUrl(giturl, opts) - } - return cache[key] -} -function fromUrl (giturl, opts) { - if (giturl == null || giturl === '') return - var url = fixupUnqualifiedGist( - isGitHubShorthand(giturl) ? 'github:' + giturl : giturl - ) - var parsed = parseGitUrl(url) - var shortcutMatch = url.match(new RegExp('^([^:]+):(?:(?:[^@:]+(?:[^@]+)?@)?([^/]*))[/](.+?)(?:[.]git)?($|#)')) - var matches = Object.keys(gitHosts).map(function (gitHostName) { - try { - var gitHostInfo = gitHosts[gitHostName] - var auth = null - if (parsed.auth && authProtocols[parsed.protocol]) { - auth = decodeURIComponent(parsed.auth) - } - var committish = parsed.hash ? decodeURIComponent(parsed.hash.substr(1)) : null - var user = null - var project = null - var defaultRepresentation = null - if (shortcutMatch && shortcutMatch[1] === gitHostName) { - user = shortcutMatch[2] && decodeURIComponent(shortcutMatch[2]) - project = decodeURIComponent(shortcutMatch[3]) - defaultRepresentation = 'shortcut' - } else { - if (parsed.host !== gitHostInfo.domain) return - if (!gitHostInfo.protocols_re.test(parsed.protocol)) return - if (!parsed.path) return - var pathmatch = gitHostInfo.pathmatch - var matched = parsed.path.match(pathmatch) - if (!matched) return - if (matched[1] != null) user = decodeURIComponent(matched[1].replace(/^:/, '')) - if (matched[2] != null) project = decodeURIComponent(matched[2]) - defaultRepresentation = protocolToRepresentation(parsed.protocol) - } - return new GitHost(gitHostName, user, auth, project, committish, defaultRepresentation, opts) - } catch (ex) { - if (!(ex instanceof URIError)) throw ex - } - }).filter(function (gitHostInfo) { return gitHostInfo }) - if (matches.length !== 1) return - return matches[0] -} +var isDescriptor = __webpack_require__(352); -function isGitHubShorthand (arg) { - // Note: This does not fully test the git ref format. - // See https://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html - // - // The only way to do this properly would be to shell out to - // git-check-ref-format, and as this is a fast sync function, - // we don't want to do that. Just let git fail if it turns - // out that the commit-ish is invalid. - // GH usernames cannot start with . or - - return /^[^:@%/\s.-][^:@%/\s]*[/][^:@\s/%]+(?:#.*)?$/.test(arg) -} +module.exports = function defineProperty(obj, prop, val) { + if (typeof obj !== 'object' && typeof obj !== 'function') { + throw new TypeError('expected an object or function.'); + } -function fixupUnqualifiedGist (giturl) { - // necessary for round-tripping gists - var parsed = url.parse(giturl) - if (parsed.protocol === 'gist:' && parsed.host && !parsed.path) { - return parsed.protocol + '/' + parsed.host - } else { - return giturl + if (typeof prop !== 'string') { + throw new TypeError('expected `prop` to be a string.'); } -} -function parseGitUrl (giturl) { - if (typeof giturl !== 'string') giturl = '' + giturl - var matched = giturl.match(/^([^@]+)@([^:/]+):[/]?((?:[^/]+[/])?[^/]+?)(?:[.]git)?(#.*)?$/) - if (!matched) return url.parse(giturl) - return { - protocol: 'git+ssh:', - slashes: true, - auth: matched[1], - host: matched[2], - port: null, - hostname: matched[2], - hash: matched[4], - search: null, - query: null, - pathname: '/' + matched[3], - path: '/' + matched[3], - href: 'git+ssh://' + matched[1] + '@' + matched[2] + - '/' + matched[3] + (matched[4] || '') + if (isDescriptor(val) && ('set' in val || 'get' in val)) { + return Object.defineProperty(obj, prop, val); } -} + + return Object.defineProperty(obj, prop, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); +}; /***/ }), -/* 159 */ +/* 352 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/*! + * is-descriptor + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ -var gitHosts = __webpack_require__(104) -var extend = Object.assign || __webpack_require__(19)._extend -var GitHost = module.exports = function (type, user, auth, project, committish, defaultRepresentation, opts) { - var gitHostInfo = this - gitHostInfo.type = type - Object.keys(gitHosts[type]).forEach(function (key) { - gitHostInfo[key] = gitHosts[type][key] - }) - gitHostInfo.user = user - gitHostInfo.auth = auth - gitHostInfo.project = project - gitHostInfo.committish = committish - gitHostInfo.default = defaultRepresentation - gitHostInfo.opts = opts || {} -} -GitHost.prototype = {} -GitHost.prototype.hash = function () { - return this.committish ? '#' + this.committish : '' -} +var typeOf = __webpack_require__(353); +var isAccessor = __webpack_require__(354); +var isData = __webpack_require__(356); -GitHost.prototype._fill = function (template, opts) { - if (!template) return - var vars = extend({}, opts) - opts = extend(extend({}, this.opts), opts) - var self = this - Object.keys(this).forEach(function (key) { - if (self[key] != null && vars[key] == null) vars[key] = self[key] - }) - var rawAuth = vars.auth - var rawComittish = vars.committish - Object.keys(vars).forEach(function (key) { - vars[key] = encodeURIComponent(vars[key]) - }) - vars['auth@'] = rawAuth ? rawAuth + '@' : '' - if (opts.noCommittish) { - vars['#committish'] = '' - vars['/tree/committish'] = '' - vars['/comittish'] = '' - vars.comittish = '' - } else { - vars['#committish'] = rawComittish ? '#' + rawComittish : '' - vars['/tree/committish'] = vars.committish - ? '/' + vars.treepath + '/' + vars.committish - : '' - vars['/committish'] = vars.committish ? '/' + vars.committish : '' - vars.committish = vars.committish || 'master' +module.exports = function isDescriptor(obj, key) { + if (typeOf(obj) !== 'object') { + return false; } - var res = template - Object.keys(vars).forEach(function (key) { - res = res.replace(new RegExp('[{]' + key + '[}]', 'g'), vars[key]) - }) - if (opts.noGitPlus) { - return res.replace(/^git[+]/, '') - } else { - return res + if ('get' in obj) { + return isAccessor(obj, key); } -} + return isData(obj, key); +}; -GitHost.prototype.ssh = function (opts) { - return this._fill(this.sshtemplate, opts) -} -GitHost.prototype.sshurl = function (opts) { - return this._fill(this.sshurltemplate, opts) -} +/***/ }), +/* 353 */ +/***/ (function(module, exports) { -GitHost.prototype.browse = function (opts) { - return this._fill(this.browsetemplate, opts) -} +var toString = Object.prototype.toString; -GitHost.prototype.docs = function (opts) { - return this._fill(this.docstemplate, opts) -} +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ -GitHost.prototype.bugs = function (opts) { - return this._fill(this.bugstemplate, opts) -} +module.exports = function kindOf(val) { + var type = typeof val; -GitHost.prototype.https = function (opts) { - return this._fill(this.httpstemplate, opts) -} + // primitivies + if (type === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (type === 'string' || val instanceof String) { + return 'string'; + } + if (type === 'number' || val instanceof Number) { + return 'number'; + } -GitHost.prototype.git = function (opts) { - return this._fill(this.gittemplate, opts) -} + // functions + if (type === 'function' || val instanceof Function) { + if (typeof val.constructor.name !== 'undefined' && val.constructor.name.slice(0, 9) === 'Generator') { + return 'generatorfunction'; + } + return 'function'; + } -GitHost.prototype.shortcut = function (opts) { - return this._fill(this.shortcuttemplate, opts) -} + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } -GitHost.prototype.path = function (opts) { - return this._fill(this.pathtemplate, opts) -} + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } -GitHost.prototype.tarball = function (opts) { - return this._fill(this.tarballtemplate, opts) -} + // other objects + type = toString.call(val); -GitHost.prototype.file = function (P, opts) { - return this._fill(this.filetemplate, extend({ - path: P.replace(/^[/]+/g, '') - }, opts)) -} + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + if (type === '[object Promise]') { + return 'promise'; + } -GitHost.prototype.getDefaultRepresentation = function () { - return this.default -} + // buffer + if (isBuffer(val)) { + return 'buffer'; + } -GitHost.prototype.toString = function (opts) { - return (this[this.default] || this.sshurl).call(this, opts) + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } + + if (type === '[object Map Iterator]') { + return 'mapiterator'; + } + if (type === '[object Set Iterator]') { + return 'setiterator'; + } + if (type === '[object String Iterator]') { + return 'stringiterator'; + } + if (type === '[object Array Iterator]') { + return 'arrayiterator'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } + + // must be a plain object + return 'object'; +}; + +/** + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer + */ + +function isBuffer(val) { + return val.constructor + && typeof val.constructor.isBuffer === 'function' + && val.constructor.isBuffer(val); } /***/ }), -/* 160 */ +/* 354 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/*! + * is-accessor-descriptor + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ -var builtinModules = __webpack_require__(161); -module.exports = function (str) { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); - } - return builtinModules.indexOf(str) !== -1; -}; +var typeOf = __webpack_require__(355); +// accessor descriptor properties +var accessor = { + get: 'function', + set: 'function', + configurable: 'boolean', + enumerable: 'boolean' +}; -/***/ }), -/* 161 */ -/***/ (function(module, exports, __webpack_require__) { +function isAccessorDescriptor(obj, prop) { + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; + } -"use strict"; + if (typeOf(obj) !== 'object') { + return false; + } + if (has(obj, 'value') || has(obj, 'writable')) { + return false; + } -var blacklist = [ - 'freelist', - 'sys' -]; + if (!has(obj, 'get') || typeof obj.get !== 'function') { + return false; + } -module.exports = Object.keys(process.binding('natives')).filter(function (el) { - return !/^_|^internal|\//.test(el) && blacklist.indexOf(el) === -1; -}).sort(); + // tldr: it's valid to have "set" be undefined + // "set" might be undefined if `Object.getOwnPropertyDescriptor` + // was used to get the value, and only `get` was defined by the user + if (has(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') { + return false; + } + for (var key in obj) { + if (!accessor.hasOwnProperty(key)) { + continue; + } -/***/ }), -/* 162 */ -/***/ (function(module, exports) { + if (typeOf(obj[key]) === accessor[key]) { + continue; + } -module.exports = extractDescription + if (typeof obj[key] !== 'undefined') { + return false; + } + } + return true; +} -// Extracts description from contents of a readme file in markdown format -function extractDescription (d) { - if (!d) return; - if (d === "ERROR: No README data found!") return; - // the first block of text before the first heading - // that isn't the first line heading - d = d.trim().split('\n') - for (var s = 0; d[s] && d[s].trim().match(/^(#|$)/); s ++); - var l = d.length - for (var e = s + 1; e < l && d[e].trim(); e ++); - return d.slice(s, e).join(' ').trim() +function has(obj, key) { + return {}.hasOwnProperty.call(obj, key); } +/** + * Expose `isAccessorDescriptor` + */ -/***/ }), -/* 163 */ -/***/ (function(module) { +module.exports = isAccessorDescriptor; -module.exports = {"topLevel":{"dependancies":"dependencies","dependecies":"dependencies","depdenencies":"dependencies","devEependencies":"devDependencies","depends":"dependencies","dev-dependencies":"devDependencies","devDependences":"devDependencies","devDepenencies":"devDependencies","devdependencies":"devDependencies","repostitory":"repository","repo":"repository","prefereGlobal":"preferGlobal","hompage":"homepage","hampage":"homepage","autohr":"author","autor":"author","contributers":"contributors","publicationConfig":"publishConfig","script":"scripts"},"bugs":{"web":"url","name":"url"},"script":{"server":"start","tests":"test"}}; /***/ }), -/* 164 */ +/* 355 */ /***/ (function(module, exports, __webpack_require__) { -var util = __webpack_require__(19) -var messages = __webpack_require__(165) +var isBuffer = __webpack_require__(22); +var toString = Object.prototype.toString; -module.exports = function() { - var args = Array.prototype.slice.call(arguments, 0) - var warningName = args.shift() - if (warningName == "typo") { - return makeTypoWarning.apply(null,args) +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ + +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; } - else { - var msgTemplate = messages[warningName] ? messages[warningName] : warningName + ": '%s'" - args.unshift(msgTemplate) - return util.format.apply(null, args) + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; } -} -function makeTypoWarning (providedName, probableName, field) { - if (field) { - providedName = field + "['" + providedName + "']" - probableName = field + "['" + probableName + "']" + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; } - return util.format(messages.typo, providedName, probableName) -} + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } -/***/ }), -/* 165 */ -/***/ (function(module) { + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } + + // other objects + var type = toString.call(val); + + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + + // buffer + if (isBuffer(val)) { + return 'buffer'; + } + + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } + + // must be a plain object + return 'object'; +}; -module.exports = {"repositories":"'repositories' (plural) Not supported. Please pick one as the 'repository' field","missingRepository":"No repository field.","brokenGitUrl":"Probably broken git url: %s","nonObjectScripts":"scripts must be an object","nonStringScript":"script values must be string commands","nonArrayFiles":"Invalid 'files' member","invalidFilename":"Invalid filename in 'files' list: %s","nonArrayBundleDependencies":"Invalid 'bundleDependencies' list. Must be array of package names","nonStringBundleDependency":"Invalid bundleDependencies member: %s","nonDependencyBundleDependency":"Non-dependency in bundleDependencies: %s","nonObjectDependencies":"%s field must be an object","nonStringDependency":"Invalid dependency: %s %s","deprecatedArrayDependencies":"specifying %s as array is deprecated","deprecatedModules":"modules field is deprecated","nonArrayKeywords":"keywords should be an array of strings","nonStringKeyword":"keywords should be an array of strings","conflictingName":"%s is also the name of a node core module.","nonStringDescription":"'description' field should be a string","missingDescription":"No description","missingReadme":"No README data","missingLicense":"No license field.","nonEmailUrlBugsString":"Bug string field must be url, email, or {email,url}","nonUrlBugsUrlField":"bugs.url field must be a string url. Deleted.","nonEmailBugsEmailField":"bugs.email field must be a string email. Deleted.","emptyNormalizedBugs":"Normalized value of bugs field is an empty object. Deleted.","nonUrlHomepage":"homepage field must be a string url. Deleted.","invalidLicense":"license should be a valid SPDX license expression","typo":"%s should probably be %s."}; /***/ }), -/* 166 */ +/* 356 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/*! + * is-data-descriptor + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ -const path = __webpack_require__(7); -const writeJsonFile = __webpack_require__(167); -const sortKeys = __webpack_require__(105); -const opts = {detectIndent: true}; -const dependencyKeys = new Set([ - 'dependencies', - 'devDependencies', - 'optionalDependencies', - 'peerDependencies' -]); +var typeOf = __webpack_require__(357); -function normalize(pkg) { - const ret = {}; +// data descriptor properties +var data = { + configurable: 'boolean', + enumerable: 'boolean', + writable: 'boolean' +}; - for (const key of Object.keys(pkg)) { - if (!dependencyKeys.has(key)) { - ret[key] = pkg[key]; - } else if (Object.keys(pkg[key]).length !== 0) { - ret[key] = sortKeys(pkg[key]); - } - } +function isDataDescriptor(obj, prop) { + if (typeOf(obj) !== 'object') { + return false; + } - return ret; + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; + } + + if (!('value' in obj) && !('writable' in obj)) { + return false; + } + + for (var key in obj) { + if (key === 'value') continue; + + if (!data.hasOwnProperty(key)) { + continue; + } + + if (typeOf(obj[key]) === data[key]) { + continue; + } + + if (typeof obj[key] !== 'undefined') { + return false; + } + } + return true; } -module.exports = (fp, data) => { - if (typeof fp !== 'string') { - data = fp; - fp = '.'; - } +/** + * Expose `isDataDescriptor` + */ - fp = path.basename(fp) === 'package.json' ? fp : path.join(fp, 'package.json'); +module.exports = isDataDescriptor; - data = normalize(data); - return writeJsonFile(fp, data, opts); -}; +/***/ }), +/* 357 */ +/***/ (function(module, exports, __webpack_require__) { -module.exports.sync = (fp, data) => { - if (typeof fp !== 'string') { - data = fp; - fp = '.'; - } +var isBuffer = __webpack_require__(22); +var toString = Object.prototype.toString; - fp = path.basename(fp) === 'package.json' ? fp : path.join(fp, 'package.json'); +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ - data = normalize(data); +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; + } - writeJsonFile.sync(fp, data, opts); + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; + } + + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } + + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } + + // other objects + var type = toString.call(val); + + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + + // buffer + if (isBuffer(val)) { + return 'buffer'; + } + + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } + + // must be a plain object + return 'object'; }; /***/ }), -/* 167 */ +/* 358 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/*! + * static-extend + * + * Copyright (c) 2016, Jon Schlinkert. + * Licensed under the MIT License. + */ -const path = __webpack_require__(7); -const fs = __webpack_require__(56); -const writeFileAtomic = __webpack_require__(168); -const sortKeys = __webpack_require__(105); -const makeDir = __webpack_require__(106); -const pify = __webpack_require__(44); -const detectIndent = __webpack_require__(172); - -const init = (fn, fp, data, opts) => { - if (!fp) { - throw new TypeError('Expected a filepath'); - } - if (data === undefined) { - throw new TypeError('Expected data to stringify'); - } - opts = Object.assign({ - indent: '\t', - sortKeys: false - }, opts); +var copy = __webpack_require__(359); +var define = __webpack_require__(366); +var util = __webpack_require__(14); - if (opts.sortKeys) { - data = sortKeys(data, { - deep: true, - compare: typeof opts.sortKeys === 'function' && opts.sortKeys - }); - } +/** + * Returns a function for extending the static properties, + * prototype properties, and descriptors from the `Parent` + * constructor onto `Child` constructors. + * + * ```js + * var extend = require('static-extend'); + * Parent.extend = extend(Parent); + * + * // optionally pass a custom merge function as the second arg + * Parent.extend = extend(Parent, function(Child) { + * Child.prototype.mixin = function(key, val) { + * Child.prototype[key] = val; + * }; + * }); + * + * // extend "child" constructors + * Parent.extend(Child); + * + * // optionally define prototype methods as the second arg + * Parent.extend(Child, { + * foo: function() {}, + * bar: function() {} + * }); + * ``` + * @param {Function} `Parent` Parent ctor + * @param {Function} `extendFn` Optional extend function for handling any necessary custom merging. Useful when updating methods that require a specific prototype. + * @param {Function} `Child` Child ctor + * @param {Object} `proto` Optionally pass additional prototype properties to inherit. + * @return {Object} + * @api public + */ - return fn(fp, data, opts); -}; +function extend(Parent, extendFn) { + if (typeof Parent !== 'function') { + throw new TypeError('expected Parent to be a function.'); + } -const readFile = fp => pify(fs.readFile)(fp, 'utf8').catch(() => {}); + return function(Ctor, proto) { + if (typeof Ctor !== 'function') { + throw new TypeError('expected Ctor to be a function.'); + } -const main = (fp, data, opts) => { - return (opts.detectIndent ? readFile(fp) : Promise.resolve()) - .then(str => { - const indent = str ? detectIndent(str).indent : opts.indent; - const json = JSON.stringify(data, opts.replacer, indent); + util.inherits(Ctor, Parent); + copy(Ctor, Parent); - return pify(writeFileAtomic)(fp, `${json}\n`, {mode: opts.mode}); - }); -}; + // proto can be null or a plain object + if (typeof proto === 'object') { + var obj = Object.create(proto); -const mainSync = (fp, data, opts) => { - let indent = opts.indent; + for (var k in obj) { + Ctor.prototype[k] = obj[k]; + } + } - if (opts.detectIndent) { - try { - const file = fs.readFileSync(fp, 'utf8'); - indent = detectIndent(file).indent; - } catch (err) { - if (err.code !== 'ENOENT') { - throw err; - } - } - } + // keep a reference to the parent prototype + define(Ctor.prototype, '_parent_', { + configurable: true, + set: function() {}, + get: function() { + return Parent.prototype; + } + }); - const json = JSON.stringify(data, opts.replacer, indent); + if (typeof extendFn === 'function') { + extendFn(Ctor, Parent); + } - return writeFileAtomic.sync(fp, `${json}\n`, {mode: opts.mode}); + Ctor.extend = extend(Ctor, extendFn); + }; }; -module.exports = (fp, data, opts) => { - return makeDir(path.dirname(fp), {fs}) - .then(() => init(main, fp, data, opts)); -}; +/** + * Expose `extend` + */ -module.exports.sync = (fp, data, opts) => { - makeDir.sync(path.dirname(fp), {fs}); - init(mainSync, fp, data, opts); -}; +module.exports = extend; /***/ }), -/* 168 */ +/* 359 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = writeFile -module.exports.sync = writeFileSync -module.exports._getTmpname = getTmpname // for testing -module.exports._cleanupOnExit = cleanupOnExit -var fs = __webpack_require__(56) -var MurmurHash3 = __webpack_require__(169) -var onExit = __webpack_require__(89) -var path = __webpack_require__(7) -var activeFiles = {} +var typeOf = __webpack_require__(49); +var copyDescriptor = __webpack_require__(360); +var define = __webpack_require__(361); -var invocations = 0 -function getTmpname (filename) { - return filename + '.' + - MurmurHash3(__filename) - .hash(String(process.pid)) - .hash(String(++invocations)) - .result() -} +/** + * Copy static properties, prototype properties, and descriptors from one object to another. + * + * ```js + * function App() {} + * var proto = App.prototype; + * App.prototype.set = function() {}; + * App.prototype.get = function() {}; + * + * var obj = {}; + * copy(obj, proto); + * ``` + * @param {Object} `receiver` + * @param {Object} `provider` + * @param {String|Array} `omit` One or more properties to omit + * @return {Object} + * @api public + */ -function cleanupOnExit (tmpfile) { - return function () { - try { - fs.unlinkSync(typeof tmpfile === 'function' ? tmpfile() : tmpfile) - } catch (_) {} +function copy(receiver, provider, omit) { + if (!isObject(receiver)) { + throw new TypeError('expected receiving object to be an object.'); + } + if (!isObject(provider)) { + throw new TypeError('expected providing object to be an object.'); } -} -function writeFile (filename, data, options, callback) { - if (options instanceof Function) { - callback = options - options = null + var props = nativeKeys(provider); + var keys = Object.keys(provider); + var len = props.length; + omit = arrayify(omit); + + while (len--) { + var key = props[len]; + + if (has(keys, key)) { + define(receiver, key, provider[key]); + } else if (!(key in receiver) && !has(omit, key)) { + copyDescriptor(receiver, provider, key); + } } - if (!options) options = {} +}; - var Promise = options.Promise || global.Promise - var truename - var fd - var tmpfile - var removeOnExit = cleanupOnExit(() => tmpfile) - var absoluteName = path.resolve(filename) +/** + * Return true if the given value is an object or function + */ - new Promise(function serializeSameFile (resolve) { - // make a queue if it doesn't already exist - if (!activeFiles[absoluteName]) activeFiles[absoluteName] = [] +function isObject(val) { + return typeOf(val) === 'object' || typeof val === 'function'; +} - activeFiles[absoluteName].push(resolve) // add this job to the queue - if (activeFiles[absoluteName].length === 1) resolve() // kick off the first one - }).then(function getRealPath () { - return new Promise(function (resolve) { - fs.realpath(filename, function (_, realname) { - truename = realname || filename - tmpfile = getTmpname(truename) - resolve() - }) - }) - }).then(function stat () { - return new Promise(function stat (resolve) { - if (options.mode && options.chown) resolve() - else { - // Either mode or chown is not explicitly set - // Default behavior is to copy it from original file - fs.stat(truename, function (err, stats) { - if (err || !stats) resolve() - else { - options = Object.assign({}, options) +/** + * Returns true if an array has any of the given elements, or an + * object has any of the give keys. + * + * ```js + * has(['a', 'b', 'c'], 'c'); + * //=> true + * + * has(['a', 'b', 'c'], ['c', 'z']); + * //=> true + * + * has({a: 'b', c: 'd'}, ['c', 'z']); + * //=> true + * ``` + * @param {Object} `obj` + * @param {String|Array} `val` + * @return {Boolean} + */ - if (!options.mode) { - options.mode = stats.mode - } - if (!options.chown && process.getuid) { - options.chown = { uid: stats.uid, gid: stats.gid } - } - resolve() - } - }) +function has(obj, val) { + val = arrayify(val); + var len = val.length; + + if (isObject(obj)) { + for (var key in obj) { + if (val.indexOf(key) > -1) { + return true; } - }) - }).then(function thenWriteFile () { - return new Promise(function (resolve, reject) { - fs.open(tmpfile, 'w', options.mode, function (err, _fd) { - fd = _fd - if (err) reject(err) - else resolve() - }) - }) - }).then(function write () { - return new Promise(function (resolve, reject) { - if (Buffer.isBuffer(data)) { - fs.write(fd, data, 0, data.length, 0, function (err) { - if (err) reject(err) - else resolve() - }) - } else if (data != null) { - fs.write(fd, String(data), 0, String(options.encoding || 'utf8'), function (err) { - if (err) reject(err) - else resolve() - }) - } else resolve() - }) - }).then(function syncAndClose () { - if (options.fsync !== false) { - return new Promise(function (resolve, reject) { - fs.fsync(fd, function (err) { - if (err) reject(err) - else fs.close(fd, resolve) - }) - }) - } - }).then(function chown () { - if (options.chown) { - return new Promise(function (resolve, reject) { - fs.chown(tmpfile, options.chown.uid, options.chown.gid, function (err) { - if (err) reject(err) - else resolve() - }) - }) - } - }).then(function chmod () { - if (options.mode) { - return new Promise(function (resolve, reject) { - fs.chmod(tmpfile, options.mode, function (err) { - if (err) reject(err) - else resolve() - }) - }) } - }).then(function rename () { - return new Promise(function (resolve, reject) { - fs.rename(tmpfile, truename, function (err) { - if (err) reject(err) - else resolve() - }) - }) - }).then(function success () { - removeOnExit() - callback() - }).catch(function fail (err) { - removeOnExit() - fs.unlink(tmpfile, function () { - callback(err) - }) - }).then(function checkQueue () { - activeFiles[absoluteName].shift() // remove the element added by serializeSameFile - if (activeFiles[absoluteName].length > 0) { - activeFiles[absoluteName][0]() // start next job if one is pending - } else delete activeFiles[absoluteName] - }) -} -function writeFileSync (filename, data, options) { - if (!options) options = {} - try { - filename = fs.realpathSync(filename) - } catch (ex) { - // it's ok, it'll happen on a not yet existing file + var keys = nativeKeys(obj); + return has(keys, val); } - var tmpfile = getTmpname(filename) - try { - if (!options.mode || !options.chown) { - // Either mode or chown is not explicitly set - // Default behavior is to copy it from original file - try { - var stats = fs.statSync(filename) - options = Object.assign({}, options) - if (!options.mode) { - options.mode = stats.mode - } - if (!options.chown && process.getuid) { - options.chown = { uid: stats.uid, gid: stats.gid } - } - } catch (ex) { - // ignore stat errors + if (Array.isArray(obj)) { + var arr = obj; + while (len--) { + if (arr.indexOf(val[len]) > -1) { + return true; } } - - var removeOnExit = onExit(cleanupOnExit(tmpfile)) - var fd = fs.openSync(tmpfile, 'w', options.mode) - if (Buffer.isBuffer(data)) { - fs.writeSync(fd, data, 0, data.length, 0) - } else if (data != null) { - fs.writeSync(fd, String(data), 0, String(options.encoding || 'utf8')) - } - if (options.fsync !== false) { - fs.fsyncSync(fd) - } - fs.closeSync(fd) - if (options.chown) fs.chownSync(tmpfile, options.chown.uid, options.chown.gid) - if (options.mode) fs.chmodSync(tmpfile, options.mode) - fs.renameSync(tmpfile, filename) - removeOnExit() - } catch (err) { - removeOnExit() - try { fs.unlinkSync(tmpfile) } catch (e) {} - throw err + return false; } + + throw new TypeError('expected an array or object.'); } +/** + * Cast the given value to an array. + * + * ```js + * arrayify('foo'); + * //=> ['foo'] + * + * arrayify(['foo']); + * //=> ['foo'] + * ``` + * + * @param {String|Array} `val` + * @return {Array} + */ -/***/ }), -/* 169 */ -/***/ (function(module, exports, __webpack_require__) { +function arrayify(val) { + return val ? (Array.isArray(val) ? val : [val]) : []; +} /** - * @preserve - * JS Implementation of incremental MurmurHash3 (r150) (as of May 10, 2013) + * Returns true if a value has a `contructor` * - * @author Jens Taylor - * @see http://github.com/homebrewing/brauhaus-diff - * @author Gary Court - * @see http://github.com/garycourt/murmurhash-js - * @author Austin Appleby - * @see http://sites.google.com/site/murmurhash/ + * ```js + * hasConstructor({}); + * //=> true + * + * hasConstructor(Object.create(null)); + * //=> false + * ``` + * @param {Object} `value` + * @return {Boolean} */ -(function(){ - var cache; - - // Call this function without `new` to use the cached object (good for - // single-threaded environments), or with `new` to create a new object. - // - // @param {string} key A UTF-16 or ASCII string - // @param {number} seed An optional positive integer - // @return {object} A MurmurHash3 object for incremental hashing - function MurmurHash3(key, seed) { - var m = this instanceof MurmurHash3 ? this : cache; - m.reset(seed) - if (typeof key === 'string' && key.length > 0) { - m.hash(key); - } - if (m !== this) { - return m; - } - }; +function hasConstructor(val) { + return isObject(val) && typeof val.constructor !== 'undefined'; +} - // Incrementally add a string to this hash - // - // @param {string} key A UTF-16 or ASCII string - // @return {object} this - MurmurHash3.prototype.hash = function(key) { - var h1, k1, i, top, len; +/** + * Get the native `ownPropertyNames` from the constructor of the + * given `object`. An empty array is returned if the object does + * not have a constructor. + * + * ```js + * nativeKeys({a: 'b', b: 'c', c: 'd'}) + * //=> ['a', 'b', 'c'] + * + * nativeKeys(function(){}) + * //=> ['length', 'caller'] + * ``` + * + * @param {Object} `obj` Object that has a `constructor`. + * @return {Array} Array of keys. + */ - len = key.length; - this.len += len; +function nativeKeys(val) { + if (!hasConstructor(val)) return []; + return Object.getOwnPropertyNames(val); +} - k1 = this.k1; - i = 0; - switch (this.rem) { - case 0: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) : 0; - case 1: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 8 : 0; - case 2: k1 ^= len > i ? (key.charCodeAt(i++) & 0xffff) << 16 : 0; - case 3: - k1 ^= len > i ? (key.charCodeAt(i) & 0xff) << 24 : 0; - k1 ^= len > i ? (key.charCodeAt(i++) & 0xff00) >> 8 : 0; - } +/** + * Expose `copy` + */ - this.rem = (len + this.rem) & 3; // & 3 is same as % 4 - len -= this.rem; - if (len > 0) { - h1 = this.h1; - while (1) { - k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; - k1 = (k1 << 15) | (k1 >>> 17); - k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; +module.exports = copy; - h1 ^= k1; - h1 = (h1 << 13) | (h1 >>> 19); - h1 = (h1 * 5 + 0xe6546b64) & 0xffffffff; +/** + * Expose `copy.has` for tests + */ - if (i >= len) { - break; - } +module.exports.has = has; - k1 = ((key.charCodeAt(i++) & 0xffff)) ^ - ((key.charCodeAt(i++) & 0xffff) << 8) ^ - ((key.charCodeAt(i++) & 0xffff) << 16); - top = key.charCodeAt(i++); - k1 ^= ((top & 0xff) << 24) ^ - ((top & 0xff00) >> 8); - } - k1 = 0; - switch (this.rem) { - case 3: k1 ^= (key.charCodeAt(i + 2) & 0xffff) << 16; - case 2: k1 ^= (key.charCodeAt(i + 1) & 0xffff) << 8; - case 1: k1 ^= (key.charCodeAt(i) & 0xffff); - } +/***/ }), +/* 360 */ +/***/ (function(module, exports, __webpack_require__) { - this.h1 = h1; - } +"use strict"; +/*! + * copy-descriptor + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ - this.k1 = k1; - return this; - }; - // Get the result of this hash - // - // @return {number} The 32-bit hash - MurmurHash3.prototype.result = function() { - var k1, h1; - - k1 = this.k1; - h1 = this.h1; - if (k1 > 0) { - k1 = (k1 * 0x2d51 + (k1 & 0xffff) * 0xcc9e0000) & 0xffffffff; - k1 = (k1 << 15) | (k1 >>> 17); - k1 = (k1 * 0x3593 + (k1 & 0xffff) * 0x1b870000) & 0xffffffff; - h1 ^= k1; - } +/** + * Copy a descriptor from one object to another. + * + * ```js + * function App() { + * this.cache = {}; + * } + * App.prototype.set = function(key, val) { + * this.cache[key] = val; + * return this; + * }; + * Object.defineProperty(App.prototype, 'count', { + * get: function() { + * return Object.keys(this.cache).length; + * } + * }); + * + * copy(App.prototype, 'count', 'len'); + * + * // create an instance + * var app = new App(); + * + * app.set('a', true); + * app.set('b', true); + * app.set('c', true); + * + * console.log(app.count); + * //=> 3 + * console.log(app.len); + * //=> 3 + * ``` + * @name copy + * @param {Object} `receiver` The target object + * @param {Object} `provider` The provider object + * @param {String} `from` The key to copy on provider. + * @param {String} `to` Optionally specify a new key name to use. + * @return {Object} + * @api public + */ - h1 ^= this.len; +module.exports = function copyDescriptor(receiver, provider, from, to) { + if (!isObject(provider) && typeof provider !== 'function') { + to = from; + from = provider; + provider = receiver; + } + if (!isObject(receiver) && typeof receiver !== 'function') { + throw new TypeError('expected the first argument to be an object'); + } + if (!isObject(provider) && typeof provider !== 'function') { + throw new TypeError('expected provider to be an object'); + } - h1 ^= h1 >>> 16; - h1 = (h1 * 0xca6b + (h1 & 0xffff) * 0x85eb0000) & 0xffffffff; - h1 ^= h1 >>> 13; - h1 = (h1 * 0xae35 + (h1 & 0xffff) * 0xc2b20000) & 0xffffffff; - h1 ^= h1 >>> 16; + if (typeof to !== 'string') { + to = from; + } + if (typeof from !== 'string') { + throw new TypeError('expected key to be a string'); + } - return h1 >>> 0; - }; + if (!(from in provider)) { + throw new Error('property "' + from + '" does not exist'); + } - // Reset the hash object for reuse - // - // @param {number} seed An optional positive integer - MurmurHash3.prototype.reset = function(seed) { - this.h1 = typeof seed === 'number' ? seed : 0; - this.rem = this.k1 = this.len = 0; - return this; - }; + var val = Object.getOwnPropertyDescriptor(provider, from); + if (val) Object.defineProperty(receiver, to, val); +}; - // A cached object to use. This can be safely used if you're in a single- - // threaded environment, otherwise you need to create new hashes to use. - cache = new MurmurHash3(); +function isObject(val) { + return {}.toString.call(val) === '[object Object]'; +} - if (true) { - module.exports = MurmurHash3; - } else {} -}()); /***/ }), -/* 170 */ -/***/ (function(module, exports) { +/* 361 */ +/***/ (function(module, exports, __webpack_require__) { -// This is not the set of all possible signals. -// -// It IS, however, the set of all signals that trigger -// an exit on either Linux or BSD systems. Linux is a -// superset of the signal names supported on BSD, and -// the unknown signals just fail to register, so we can -// catch that easily enough. -// -// Don't bother with SIGKILL. It's uncatchable, which -// means that we can't fire any callbacks anyway. -// -// If a user does happen to register a handler on a non- -// fatal signal like SIGWINCH or something, and then -// exit, it'll end up firing `process.emit('exit')`, so -// the handler will be fired anyway. -// -// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised -// artificially, inherently leave the process in a -// state from which it is not safe to try and enter JS -// listeners. -module.exports = [ - 'SIGABRT', - 'SIGALRM', - 'SIGHUP', - 'SIGINT', - 'SIGTERM' -] +"use strict"; +/*! + * define-property + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ -if (process.platform !== 'win32') { - module.exports.push( - 'SIGVTALRM', - 'SIGXCPU', - 'SIGXFSZ', - 'SIGUSR2', - 'SIGTRAP', - 'SIGSYS', - 'SIGQUIT', - 'SIGIOT' - // should detect profiler and enable/disable accordingly. - // see #21 - // 'SIGPROF' - ) -} -if (process.platform === 'linux') { - module.exports.push( - 'SIGIO', - 'SIGPOLL', - 'SIGPWR', - 'SIGSTKFLT', - 'SIGUNUSED' - ) -} + +var isDescriptor = __webpack_require__(362); + +module.exports = function defineProperty(obj, prop, val) { + if (typeof obj !== 'object' && typeof obj !== 'function') { + throw new TypeError('expected an object or function.'); + } + + if (typeof prop !== 'string') { + throw new TypeError('expected `prop` to be a string.'); + } + + if (isDescriptor(val) && ('set' in val || 'get' in val)) { + return Object.defineProperty(obj, prop, val); + } + + return Object.defineProperty(obj, prop, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); +}; /***/ }), -/* 171 */ +/* 362 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/*! + * is-descriptor + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ -var toString = Object.prototype.toString; -module.exports = function (x) { - var prototype; - return toString.call(x) === '[object Object]' && (prototype = Object.getPrototypeOf(x), prototype === null || prototype === Object.getPrototypeOf({})); + +var typeOf = __webpack_require__(363); +var isAccessor = __webpack_require__(364); +var isData = __webpack_require__(365); + +module.exports = function isDescriptor(obj, key) { + if (typeOf(obj) !== 'object') { + return false; + } + if ('get' in obj) { + return isAccessor(obj, key); + } + return isData(obj, key); }; /***/ }), -/* 172 */ -/***/ (function(module, exports, __webpack_require__) { +/* 363 */ +/***/ (function(module, exports) { -"use strict"; +var toString = Object.prototype.toString; +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ -// detect either spaces or tabs but not both to properly handle tabs -// for indentation and spaces for alignment -const INDENT_RE = /^(?:( )+|\t+)/; +module.exports = function kindOf(val) { + var type = typeof val; -function getMostUsed(indents) { - let result = 0; - let maxUsed = 0; - let maxWeight = 0; + // primitivies + if (type === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (type === 'string' || val instanceof String) { + return 'string'; + } + if (type === 'number' || val instanceof Number) { + return 'number'; + } - for (const entry of indents) { - // TODO: use destructuring when targeting Node.js 6 - const key = entry[0]; - const val = entry[1]; + // functions + if (type === 'function' || val instanceof Function) { + if (typeof val.constructor.name !== 'undefined' && val.constructor.name.slice(0, 9) === 'Generator') { + return 'generatorfunction'; + } + return 'function'; + } - const u = val[0]; - const w = val[1]; + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } - if (u > maxUsed || (u === maxUsed && w > maxWeight)) { - maxUsed = u; - maxWeight = w; - result = Number(key); - } - } + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } + + // other objects + type = toString.call(val); + + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + if (type === '[object Promise]') { + return 'promise'; + } + + // buffer + if (isBuffer(val)) { + return 'buffer'; + } + + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } + + if (type === '[object Map Iterator]') { + return 'mapiterator'; + } + if (type === '[object Set Iterator]') { + return 'setiterator'; + } + if (type === '[object String Iterator]') { + return 'stringiterator'; + } + if (type === '[object Array Iterator]') { + return 'arrayiterator'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } - return result; + // must be a plain object + return 'object'; +}; + +/** + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer + */ + +function isBuffer(val) { + return val.constructor + && typeof val.constructor.isBuffer === 'function' + && val.constructor.isBuffer(val); } -module.exports = str => { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); - } - // used to see if tabs or spaces are the most used - let tabs = 0; - let spaces = 0; +/***/ }), +/* 364 */ +/***/ (function(module, exports, __webpack_require__) { - // remember the size of previous line's indentation - let prev = 0; +"use strict"; +/*! + * is-accessor-descriptor + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ - // remember how many indents/unindents as occurred for a given size - // and how much lines follow a given indentation - // - // indents = { - // 3: [1, 0], - // 4: [1, 5], - // 5: [1, 0], - // 12: [1, 0], - // } - const indents = new Map(); - // pointer to the array of last used indent - let current; - // whether the last action was an indent (opposed to an unindent) - let isIndent; +var typeOf = __webpack_require__(49); - for (const line of str.split(/\n/g)) { - if (!line) { - // ignore empty lines - continue; - } +// accessor descriptor properties +var accessor = { + get: 'function', + set: 'function', + configurable: 'boolean', + enumerable: 'boolean' +}; - let indent; - const matches = line.match(INDENT_RE); +function isAccessorDescriptor(obj, prop) { + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; + } - if (matches) { - indent = matches[0].length; + if (typeOf(obj) !== 'object') { + return false; + } - if (matches[1]) { - spaces++; - } else { - tabs++; - } - } else { - indent = 0; - } + if (has(obj, 'value') || has(obj, 'writable')) { + return false; + } - const diff = indent - prev; - prev = indent; + if (!has(obj, 'get') || typeof obj.get !== 'function') { + return false; + } - if (diff) { - // an indent or unindent has been detected + // tldr: it's valid to have "set" be undefined + // "set" might be undefined if `Object.getOwnPropertyDescriptor` + // was used to get the value, and only `get` was defined by the user + if (has(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') { + return false; + } - isIndent = diff > 0; + for (var key in obj) { + if (!accessor.hasOwnProperty(key)) { + continue; + } - current = indents.get(isIndent ? diff : -diff); + if (typeOf(obj[key]) === accessor[key]) { + continue; + } - if (current) { - current[0]++; - } else { - current = [1, 0]; - indents.set(diff, current); - } - } else if (current) { - // if the last action was an indent, increment the weight - current[1] += Number(isIndent); - } - } + if (typeof obj[key] !== 'undefined') { + return false; + } + } + return true; +} - const amount = getMostUsed(indents); +function has(obj, key) { + return {}.hasOwnProperty.call(obj, key); +} - let type; - let indent; - if (!amount) { - type = null; - indent = ''; - } else if (spaces >= tabs) { - type = 'space'; - indent = ' '.repeat(amount); - } else { - type = 'tab'; - indent = '\t'.repeat(amount); - } +/** + * Expose `isAccessorDescriptor` + */ - return { - amount, - type, - indent - }; -}; +module.exports = isAccessorDescriptor; /***/ }), -/* 173 */ +/* 365 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/*! + * is-data-descriptor + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.runScriptInPackage = exports.installInDir = undefined; -/** - * Install all dependencies in the given directory - */ -let installInDir = exports.installInDir = (() => { - var _ref = _asyncToGenerator(function* (directory, extraArgs = []) { - const options = ['install', '--non-interactive', ...extraArgs]; - // We pass the mutex flag to ensure only one instance of yarn runs at any - // given time (e.g. to avoid conflicts). - yield (0, _child_process.spawn)('yarn', options, { - cwd: directory - }); - }); +var typeOf = __webpack_require__(49); - return function installInDir(_x) { - return _ref.apply(this, arguments); - }; -})(); -/** - * Run script in the given directory - */ +// data descriptor properties +var data = { + configurable: 'boolean', + enumerable: 'boolean', + writable: 'boolean' +}; +function isDataDescriptor(obj, prop) { + if (typeOf(obj) !== 'object') { + return false; + } -let runScriptInPackage = exports.runScriptInPackage = (() => { - var _ref2 = _asyncToGenerator(function* (script, args, pkg) { - const execOpts = { - cwd: pkg.path - }; - yield (0, _child_process.spawn)('yarn', ['run', script, ...args], execOpts); - }); + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; + } - return function runScriptInPackage(_x2, _x3, _x4) { - return _ref2.apply(this, arguments); - }; -})(); -/** - * Run script in the given directory - */ + if (!('value' in obj) && !('writable' in obj)) { + return false; + } + for (var key in obj) { + if (key === 'value') continue; -exports.runScriptInPackageStreaming = runScriptInPackageStreaming; + if (!data.hasOwnProperty(key)) { + continue; + } -var _child_process = __webpack_require__(174); + if (typeOf(obj[key]) === data[key]) { + continue; + } -function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ + if (typeof obj[key] !== 'undefined') { + return false; + } + } + return true; +} +/** + * Expose `isDataDescriptor` + */ + +module.exports = isDataDescriptor; -function runScriptInPackageStreaming(script, args, pkg) { - const execOpts = { - cwd: pkg.path - }; - return (0, _child_process.spawnStreaming)('yarn', ['run', script, ...args], execOpts, { - prefix: pkg.name - }); -} /***/ }), -/* 174 */ +/* 366 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/*! + * define-property + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ -Object.defineProperty(exports, "__esModule", { - value: true -}); -var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ +var isDescriptor = __webpack_require__(367); +module.exports = function defineProperty(obj, prop, val) { + if (typeof obj !== 'object' && typeof obj !== 'function') { + throw new TypeError('expected an object or function.'); + } -exports.spawn = spawn; -exports.spawnStreaming = spawnStreaming; + if (typeof prop !== 'string') { + throw new TypeError('expected `prop` to be a string.'); + } -var _chalk = __webpack_require__(30); + if (isDescriptor(val) && ('set' in val || 'get' in val)) { + return Object.defineProperty(obj, prop, val); + } -var _chalk2 = _interopRequireDefault(_chalk); + return Object.defineProperty(obj, prop, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); +}; -var _execa = __webpack_require__(175); -var _execa2 = _interopRequireDefault(_execa); +/***/ }), +/* 367 */ +/***/ (function(module, exports, __webpack_require__) { -var _logSymbols = __webpack_require__(110); +"use strict"; +/*! + * is-descriptor + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ -var _logSymbols2 = _interopRequireDefault(_logSymbols); -var _strongLogTransformer = __webpack_require__(206); -var _strongLogTransformer2 = _interopRequireDefault(_strongLogTransformer); +var typeOf = __webpack_require__(368); +var isAccessor = __webpack_require__(369); +var isData = __webpack_require__(371); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +module.exports = function isDescriptor(obj, key) { + if (typeOf(obj) !== 'object') { + return false; + } + if ('get' in obj) { + return isAccessor(obj, key); + } + return isData(obj, key); +}; -function generateColors() { - const colorWheel = [_chalk2.default.cyan, _chalk2.default.magenta, _chalk2.default.blue, _chalk2.default.yellow, _chalk2.default.green]; - const count = colorWheel.length; - let children = 0; - return () => colorWheel[children++ % count]; -} -function spawn(command, args, opts) { - return (0, _execa2.default)(command, args, _extends({}, opts, { - stdio: 'inherit' - })); -} -const nextColor = generateColors(); -function spawnStreaming(command, args, opts, { prefix }) { - const spawned = (0, _execa2.default)(command, args, _extends({}, opts, { - stdio: ['ignore', 'pipe', 'pipe'] - })); - const color = nextColor(); - const prefixedStdout = (0, _strongLogTransformer2.default)({ tag: `${color.bold(prefix)}:` }); - const prefixedStderr = (0, _strongLogTransformer2.default)({ - mergeMultiline: true, - tag: `${_logSymbols2.default.error} ${color.bold(prefix)}:` - }); - spawned.stdout.pipe(prefixedStdout).pipe(process.stdout); - spawned.stderr.pipe(prefixedStderr).pipe(process.stderr); - return spawned; -} /***/ }), -/* 175 */ -/***/ (function(module, exports, __webpack_require__) { +/* 368 */ +/***/ (function(module, exports) { -"use strict"; +var toString = Object.prototype.toString; -const path = __webpack_require__(7); -const childProcess = __webpack_require__(90); -const util = __webpack_require__(19); -const crossSpawn = __webpack_require__(176); -const stripEof = __webpack_require__(192); -const npmRunPath = __webpack_require__(193); -const isStream = __webpack_require__(195); -const _getStream = __webpack_require__(196); -const pFinally = __webpack_require__(198); -const onExit = __webpack_require__(89); -const errname = __webpack_require__(199); -const stdio = __webpack_require__(200); +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ -const TEN_MEGABYTES = 1000 * 1000 * 10; +module.exports = function kindOf(val) { + var type = typeof val; -function handleArgs(cmd, args, opts) { - let parsed; + // primitivies + if (type === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (type === 'string' || val instanceof String) { + return 'string'; + } + if (type === 'number' || val instanceof Number) { + return 'number'; + } - opts = Object.assign({ - extendEnv: true, - env: {} - }, opts); + // functions + if (type === 'function' || val instanceof Function) { + if (typeof val.constructor.name !== 'undefined' && val.constructor.name.slice(0, 9) === 'Generator') { + return 'generatorfunction'; + } + return 'function'; + } - if (opts.extendEnv) { - opts.env = Object.assign({}, process.env, opts.env); - } + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } - if (opts.__winShell === true) { - delete opts.__winShell; - parsed = { - command: cmd, - args, - options: opts, - file: cmd, - original: cmd - }; - } else { - parsed = crossSpawn._parse(cmd, args, opts); - } + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } - opts = Object.assign({ - maxBuffer: TEN_MEGABYTES, - stripEof: true, - preferLocal: true, - localDir: parsed.options.cwd || process.cwd(), - encoding: 'utf8', - reject: true, - cleanup: true - }, parsed.options); + // other objects + type = toString.call(val); - opts.stdio = stdio(opts); + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + if (type === '[object Promise]') { + return 'promise'; + } - if (opts.preferLocal) { - opts.env = npmRunPath.env(Object.assign({}, opts, {cwd: opts.localDir})); - } + // buffer + if (isBuffer(val)) { + return 'buffer'; + } - if (opts.detached) { - // #115 - opts.cleanup = false; - } + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } + + if (type === '[object Map Iterator]') { + return 'mapiterator'; + } + if (type === '[object Set Iterator]') { + return 'setiterator'; + } + if (type === '[object String Iterator]') { + return 'stringiterator'; + } + if (type === '[object Array Iterator]') { + return 'arrayiterator'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } - if (process.platform === 'win32' && path.basename(parsed.command) === 'cmd.exe') { - // #116 - parsed.args.unshift('/q'); - } + // must be a plain object + return 'object'; +}; - return { - cmd: parsed.command, - args: parsed.args, - opts, - parsed - }; +/** + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer + */ + +function isBuffer(val) { + return val.constructor + && typeof val.constructor.isBuffer === 'function' + && val.constructor.isBuffer(val); } -function handleInput(spawned, opts) { - const input = opts.input; - if (input === null || input === undefined) { - return; - } +/***/ }), +/* 369 */ +/***/ (function(module, exports, __webpack_require__) { - if (isStream(input)) { - input.pipe(spawned.stdin); - } else { - spawned.stdin.end(input); - } -} +"use strict"; +/*! + * is-accessor-descriptor + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ -function handleOutput(opts, val) { - if (val && opts.stripEof) { - val = stripEof(val); - } - return val; -} -function handleShell(fn, cmd, opts) { - let file = '/bin/sh'; - let args = ['-c', cmd]; +var typeOf = __webpack_require__(370); - opts = Object.assign({}, opts); +// accessor descriptor properties +var accessor = { + get: 'function', + set: 'function', + configurable: 'boolean', + enumerable: 'boolean' +}; - if (process.platform === 'win32') { - opts.__winShell = true; - file = process.env.comspec || 'cmd.exe'; - args = ['/s', '/c', `"${cmd}"`]; - opts.windowsVerbatimArguments = true; - } +function isAccessorDescriptor(obj, prop) { + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; + } - if (opts.shell) { - file = opts.shell; - delete opts.shell; - } + if (typeOf(obj) !== 'object') { + return false; + } - return fn(file, args, opts); -} + if (has(obj, 'value') || has(obj, 'writable')) { + return false; + } -function getStream(process, stream, encoding, maxBuffer) { - if (!process[stream]) { - return null; - } + if (!has(obj, 'get') || typeof obj.get !== 'function') { + return false; + } - let ret; + // tldr: it's valid to have "set" be undefined + // "set" might be undefined if `Object.getOwnPropertyDescriptor` + // was used to get the value, and only `get` was defined by the user + if (has(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') { + return false; + } - if (encoding) { - ret = _getStream(process[stream], { - encoding, - maxBuffer - }); - } else { - ret = _getStream.buffer(process[stream], {maxBuffer}); - } + for (var key in obj) { + if (!accessor.hasOwnProperty(key)) { + continue; + } - return ret.catch(err => { - err.stream = stream; - err.message = `${stream} ${err.message}`; - throw err; - }); + if (typeOf(obj[key]) === accessor[key]) { + continue; + } + + if (typeof obj[key] !== 'undefined') { + return false; + } + } + return true; } -function makeError(result, options) { - const stdout = result.stdout; - const stderr = result.stderr; +function has(obj, key) { + return {}.hasOwnProperty.call(obj, key); +} - let err = result.error; - const code = result.code; - const signal = result.signal; +/** + * Expose `isAccessorDescriptor` + */ - const parsed = options.parsed; - const joinedCmd = options.joinedCmd; - const timedOut = options.timedOut || false; +module.exports = isAccessorDescriptor; - if (!err) { - let output = ''; - if (Array.isArray(parsed.opts.stdio)) { - if (parsed.opts.stdio[2] !== 'inherit') { - output += output.length > 0 ? stderr : `\n${stderr}`; - } +/***/ }), +/* 370 */ +/***/ (function(module, exports, __webpack_require__) { - if (parsed.opts.stdio[1] !== 'inherit') { - output += `\n${stdout}`; - } - } else if (parsed.opts.stdio !== 'inherit') { - output = `\n${stderr}${stdout}`; - } +var isBuffer = __webpack_require__(22); +var toString = Object.prototype.toString; - err = new Error(`Command failed: ${joinedCmd}${output}`); - err.code = code < 0 ? errname(code) : code; - } +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ - err.stdout = stdout; - err.stderr = stderr; - err.failed = true; - err.signal = signal || null; - err.cmd = joinedCmd; - err.timedOut = timedOut; +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; + } - return err; -} + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; + } -function joinCmd(cmd, args) { - let joinedCmd = cmd; + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } - if (Array.isArray(args) && args.length > 0) { - joinedCmd += ' ' + args.join(' '); - } + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } - return joinedCmd; -} + // other objects + var type = toString.call(val); -module.exports = (cmd, args, opts) => { - const parsed = handleArgs(cmd, args, opts); - const encoding = parsed.opts.encoding; - const maxBuffer = parsed.opts.maxBuffer; - const joinedCmd = joinCmd(cmd, args); + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + + // buffer + if (isBuffer(val)) { + return 'buffer'; + } + + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } - let spawned; - try { - spawned = childProcess.spawn(parsed.cmd, parsed.args, parsed.opts); - } catch (err) { - return Promise.reject(err); - } + // must be a plain object + return 'object'; +}; - let removeExitHandler; - if (parsed.opts.cleanup) { - removeExitHandler = onExit(() => { - spawned.kill(); - }); - } - let timeoutId = null; - let timedOut = false; +/***/ }), +/* 371 */ +/***/ (function(module, exports, __webpack_require__) { - const cleanupTimeout = () => { - if (timeoutId) { - clearTimeout(timeoutId); - timeoutId = null; - } - }; +"use strict"; +/*! + * is-data-descriptor + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ - if (parsed.opts.timeout > 0) { - timeoutId = setTimeout(() => { - timeoutId = null; - timedOut = true; - spawned.kill(parsed.opts.killSignal); - }, parsed.opts.timeout); - } - const processDone = new Promise(resolve => { - spawned.on('exit', (code, signal) => { - cleanupTimeout(); - resolve({code, signal}); - }); - spawned.on('error', err => { - cleanupTimeout(); - resolve({error: err}); - }); +var typeOf = __webpack_require__(372); - if (spawned.stdin) { - spawned.stdin.on('error', err => { - cleanupTimeout(); - resolve({error: err}); - }); - } - }); +// data descriptor properties +var data = { + configurable: 'boolean', + enumerable: 'boolean', + writable: 'boolean' +}; - function destroy() { - if (spawned.stdout) { - spawned.stdout.destroy(); - } +function isDataDescriptor(obj, prop) { + if (typeOf(obj) !== 'object') { + return false; + } - if (spawned.stderr) { - spawned.stderr.destroy(); - } - } + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; + } - const handlePromise = () => pFinally(Promise.all([ - processDone, - getStream(spawned, 'stdout', encoding, maxBuffer), - getStream(spawned, 'stderr', encoding, maxBuffer) - ]).then(arr => { - const result = arr[0]; - result.stdout = arr[1]; - result.stderr = arr[2]; + if (!('value' in obj) && !('writable' in obj)) { + return false; + } - if (removeExitHandler) { - removeExitHandler(); - } + for (var key in obj) { + if (key === 'value') continue; - if (result.error || result.code !== 0 || result.signal !== null) { - const err = makeError(result, { - joinedCmd, - parsed, - timedOut - }); + if (!data.hasOwnProperty(key)) { + continue; + } - // TODO: missing some timeout logic for killed - // https://github.com/nodejs/node/blob/master/lib/child_process.js#L203 - // err.killed = spawned.killed || killed; - err.killed = err.killed || spawned.killed; + if (typeOf(obj[key]) === data[key]) { + continue; + } - if (!parsed.opts.reject) { - return err; - } + if (typeof obj[key] !== 'undefined') { + return false; + } + } + return true; +} - throw err; - } +/** + * Expose `isDataDescriptor` + */ - return { - stdout: handleOutput(parsed.opts, result.stdout), - stderr: handleOutput(parsed.opts, result.stderr), - code: 0, - failed: false, - killed: false, - signal: null, - cmd: joinedCmd, - timedOut: false - }; - }), destroy); +module.exports = isDataDescriptor; - crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed); - handleInput(spawned, parsed.opts); +/***/ }), +/* 372 */ +/***/ (function(module, exports, __webpack_require__) { - spawned.then = (onfulfilled, onrejected) => handlePromise().then(onfulfilled, onrejected); - spawned.catch = onrejected => handlePromise().catch(onrejected); +var isBuffer = __webpack_require__(22); +var toString = Object.prototype.toString; - return spawned; -}; +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ -module.exports.stdout = function () { - // TODO: set `stderr: 'ignore'` when that option is implemented - return module.exports.apply(null, arguments).then(x => x.stdout); -}; +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; + } -module.exports.stderr = function () { - // TODO: set `stdout: 'ignore'` when that option is implemented - return module.exports.apply(null, arguments).then(x => x.stderr); -}; + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; + } -module.exports.shell = (cmd, opts) => handleShell(module.exports, cmd, opts); + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } -module.exports.sync = (cmd, args, opts) => { - const parsed = handleArgs(cmd, args, opts); - const joinedCmd = joinCmd(cmd, args); + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } - if (isStream(parsed.opts.input)) { - throw new TypeError('The `input` option cannot be a stream in sync mode'); - } + // other objects + var type = toString.call(val); - const result = childProcess.spawnSync(parsed.cmd, parsed.args, parsed.opts); - result.code = result.status; + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } - if (result.error || result.status !== 0 || result.signal !== null) { - const err = makeError(result, { - joinedCmd, - parsed - }); + // buffer + if (isBuffer(val)) { + return 'buffer'; + } - if (!parsed.opts.reject) { - return err; - } + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } - throw err; - } + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } - return { - stdout: handleOutput(parsed.opts, result.stdout), - stderr: handleOutput(parsed.opts, result.stderr), - code: 0, - failed: false, - signal: null, - cmd: joinedCmd, - timedOut: false - }; + // must be a plain object + return 'object'; }; -module.exports.shellSync = (cmd, opts) => handleShell(module.exports.sync, cmd, opts); - -module.exports.spawn = util.deprecate(module.exports, 'execa.spawn() is deprecated. Use execa() instead.'); - /***/ }), -/* 176 */ +/* 373 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/*! + * is-descriptor + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ -var cp = __webpack_require__(90); -var parse = __webpack_require__(177); -var enoent = __webpack_require__(190); -var cpSpawnSync = cp.spawnSync; +var typeOf = __webpack_require__(374); +var isAccessor = __webpack_require__(375); +var isData = __webpack_require__(377); -function spawn(command, args, options) { - var parsed; - var spawned; +module.exports = function isDescriptor(obj, key) { + if (typeOf(obj) !== 'object') { + return false; + } + if ('get' in obj) { + return isAccessor(obj, key); + } + return isData(obj, key); +}; - // Parse the arguments - parsed = parse(command, args, options); - // Spawn the child process - spawned = cp.spawn(parsed.command, parsed.args, parsed.options); +/***/ }), +/* 374 */ +/***/ (function(module, exports) { - // Hook into child process "exit" event to emit an error if the command - // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 - enoent.hookChildProcess(spawned, parsed); +var toString = Object.prototype.toString; - return spawned; -} +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ -function spawnSync(command, args, options) { - var parsed; - var result; +module.exports = function kindOf(val) { + var type = typeof val; - if (!cpSpawnSync) { - try { - cpSpawnSync = __webpack_require__(191); // eslint-disable-line global-require - } catch (ex) { - throw new Error( - 'In order to use spawnSync on node 0.10 or older, you must ' + - 'install spawn-sync:\n\n' + - ' npm install spawn-sync --save' - ); - } + // primitivies + if (type === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (type === 'string' || val instanceof String) { + return 'string'; + } + if (type === 'number' || val instanceof Number) { + return 'number'; + } + + // functions + if (type === 'function' || val instanceof Function) { + if (typeof val.constructor.name !== 'undefined' && val.constructor.name.slice(0, 9) === 'Generator') { + return 'generatorfunction'; } + return 'function'; + } - // Parse the arguments - parsed = parse(command, args, options); + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } - // Spawn the child process - result = cpSpawnSync(parsed.command, parsed.args, parsed.options); + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } - // Analyze if the command does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 - result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); + // other objects + type = toString.call(val); - return result; -} + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + if (type === '[object Promise]') { + return 'promise'; + } -module.exports = spawn; -module.exports.spawn = spawn; -module.exports.sync = spawnSync; + // buffer + if (isBuffer(val)) { + return 'buffer'; + } -module.exports._parse = parse; -module.exports._enoent = enoent; + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } + + if (type === '[object Map Iterator]') { + return 'mapiterator'; + } + if (type === '[object Set Iterator]') { + return 'setiterator'; + } + if (type === '[object String Iterator]') { + return 'stringiterator'; + } + if (type === '[object Array Iterator]') { + return 'arrayiterator'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } + + // must be a plain object + return 'object'; +}; + +/** + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer + */ + +function isBuffer(val) { + return val.constructor + && typeof val.constructor.isBuffer === 'function' + && val.constructor.isBuffer(val); +} /***/ }), -/* 177 */ +/* 375 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/*! + * is-accessor-descriptor + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ -var resolveCommand = __webpack_require__(107); -var hasEmptyArgumentBug = __webpack_require__(185); -var escapeArgument = __webpack_require__(109); -var escapeCommand = __webpack_require__(186); -var readShebang = __webpack_require__(187); -var isWin = process.platform === 'win32'; -var skipShellRegExp = /\.(?:com|exe)$/i; +var typeOf = __webpack_require__(376); -// Supported in Node >= 6 and >= 4.8 -var supportsShellOption = parseInt(process.version.substr(1).split('.')[0], 10) >= 6 || - parseInt(process.version.substr(1).split('.')[0], 10) === 4 && parseInt(process.version.substr(1).split('.')[1], 10) >= 8; +// accessor descriptor properties +var accessor = { + get: 'function', + set: 'function', + configurable: 'boolean', + enumerable: 'boolean' +}; -function parseNonShell(parsed) { - var shebang; - var needsShell; - var applyQuotes; +function isAccessorDescriptor(obj, prop) { + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; + } - if (!isWin) { - return parsed; - } + if (typeOf(obj) !== 'object') { + return false; + } - // Detect & add support for shebangs - parsed.file = resolveCommand(parsed.command); - parsed.file = parsed.file || resolveCommand(parsed.command, true); - shebang = parsed.file && readShebang(parsed.file); + if (has(obj, 'value') || has(obj, 'writable')) { + return false; + } - if (shebang) { - parsed.args.unshift(parsed.file); - parsed.command = shebang; - needsShell = hasEmptyArgumentBug || !skipShellRegExp.test(resolveCommand(shebang) || resolveCommand(shebang, true)); - } else { - needsShell = hasEmptyArgumentBug || !skipShellRegExp.test(parsed.file); - } + if (!has(obj, 'get') || typeof obj.get !== 'function') { + return false; + } - // If a shell is required, use cmd.exe and take care of escaping everything correctly - if (needsShell) { - // Escape command & arguments - applyQuotes = (parsed.command !== 'echo'); // Do not quote arguments for the special "echo" command - parsed.command = escapeCommand(parsed.command); - parsed.args = parsed.args.map(function (arg) { - return escapeArgument(arg, applyQuotes); - }); + // tldr: it's valid to have "set" be undefined + // "set" might be undefined if `Object.getOwnPropertyDescriptor` + // was used to get the value, and only `get` was defined by the user + if (has(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') { + return false; + } - // Make use of cmd.exe - parsed.args = ['/d', '/s', '/c', '"' + parsed.command + (parsed.args.length ? ' ' + parsed.args.join(' ') : '') + '"']; - parsed.command = process.env.comspec || 'cmd.exe'; - parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped + for (var key in obj) { + if (!accessor.hasOwnProperty(key)) { + continue; } - return parsed; + if (typeOf(obj[key]) === accessor[key]) { + continue; + } + + if (typeof obj[key] !== 'undefined') { + return false; + } + } + return true; } -function parseShell(parsed) { - var shellCommand; +function has(obj, key) { + return {}.hasOwnProperty.call(obj, key); +} - // If node supports the shell option, there's no need to mimic its behavior - if (supportsShellOption) { - return parsed; - } +/** + * Expose `isAccessorDescriptor` + */ - // Mimic node shell option, see: https://github.com/nodejs/node/blob/b9f6a2dc059a1062776133f3d4fd848c4da7d150/lib/child_process.js#L335 - shellCommand = [parsed.command].concat(parsed.args).join(' '); +module.exports = isAccessorDescriptor; - if (isWin) { - parsed.command = typeof parsed.options.shell === 'string' ? parsed.options.shell : process.env.comspec || 'cmd.exe'; - parsed.args = ['/d', '/s', '/c', '"' + shellCommand + '"']; - parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped - } else { - if (typeof parsed.options.shell === 'string') { - parsed.command = parsed.options.shell; - } else if (process.platform === 'android') { - parsed.command = '/system/bin/sh'; - } else { - parsed.command = '/bin/sh'; - } - parsed.args = ['-c', shellCommand]; - } +/***/ }), +/* 376 */ +/***/ (function(module, exports, __webpack_require__) { - return parsed; -} +var isBuffer = __webpack_require__(22); +var toString = Object.prototype.toString; -// ------------------------------------------------ +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ -function parse(command, args, options) { - var parsed; +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; + } - // Normalize arguments, similar to nodejs - if (args && !Array.isArray(args)) { - options = args; - args = null; - } + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; + } - args = args ? args.slice(0) : []; // Clone array to avoid changing the original - options = options || {}; + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } - // Build our parsed object - parsed = { - command: command, - args: args, - options: options, - file: undefined, - original: command, - }; + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } - // Delegate further parsing to shell or non-shell - return options.shell ? parseShell(parsed) : parseNonShell(parsed); -} + // other objects + var type = toString.call(val); -module.exports = parse; + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + // buffer + if (isBuffer(val)) { + return 'buffer'; + } -/***/ }), -/* 178 */ -/***/ (function(module, exports, __webpack_require__) { + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } -module.exports = which -which.sync = whichSync + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } -var isWindows = process.platform === 'win32' || - process.env.OSTYPE === 'cygwin' || - process.env.OSTYPE === 'msys' + // must be a plain object + return 'object'; +}; -var path = __webpack_require__(7) -var COLON = isWindows ? ';' : ':' -var isexe = __webpack_require__(179) -function getNotFoundError (cmd) { - var er = new Error('not found: ' + cmd) - er.code = 'ENOENT' +/***/ }), +/* 377 */ +/***/ (function(module, exports, __webpack_require__) { - return er -} +"use strict"; +/*! + * is-data-descriptor + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ -function getPathInfo (cmd, opt) { - var colon = opt.colon || COLON - var pathEnv = opt.path || process.env.PATH || '' - var pathExt = [''] - pathEnv = pathEnv.split(colon) - var pathExtExe = '' - if (isWindows) { - pathEnv.unshift(process.cwd()) - pathExtExe = (opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM') - pathExt = pathExtExe.split(colon) +var typeOf = __webpack_require__(378); +// data descriptor properties +var data = { + configurable: 'boolean', + enumerable: 'boolean', + writable: 'boolean' +}; - // Always test the cmd itself first. isexe will check to make sure - // it's found in the pathExt set. - if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') - pathExt.unshift('') +function isDataDescriptor(obj, prop) { + if (typeOf(obj) !== 'object') { + return false; } - // If it has a slash, then we don't bother searching the pathenv. - // just check the file itself, and that's it. - if (cmd.match(/\//) || isWindows && cmd.match(/\\/)) - pathEnv = [''] - - return { - env: pathEnv, - ext: pathExt, - extExe: pathExtExe + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; } -} -function which (cmd, opt, cb) { - if (typeof opt === 'function') { - cb = opt - opt = {} + if (!('value' in obj) && !('writable' in obj)) { + return false; } - var info = getPathInfo(cmd, opt) - var pathEnv = info.env - var pathExt = info.ext - var pathExtExe = info.extExe - var found = [] + for (var key in obj) { + if (key === 'value') continue; - ;(function F (i, l) { - if (i === l) { - if (opt.all && found.length) - return cb(null, found) - else - return cb(getNotFoundError(cmd)) + if (!data.hasOwnProperty(key)) { + continue; } - var pathPart = pathEnv[i] - if (pathPart.charAt(0) === '"' && pathPart.slice(-1) === '"') - pathPart = pathPart.slice(1, -1) + if (typeOf(obj[key]) === data[key]) { + continue; + } - var p = path.join(pathPart, cmd) - if (!pathPart && (/^\.[\\\/]/).test(cmd)) { - p = cmd.slice(0, 2) + p + if (typeof obj[key] !== 'undefined') { + return false; } - ;(function E (ii, ll) { - if (ii === ll) return F(i + 1, l) - var ext = pathExt[ii] - isexe(p + ext, { pathExt: pathExtExe }, function (er, is) { - if (!er && is) { - if (opt.all) - found.push(p + ext) - else - return cb(null, p + ext) - } - return E(ii + 1, ll) - }) - })(0, pathExt.length) - })(0, pathEnv.length) + } + return true; } -function whichSync (cmd, opt) { - opt = opt || {} +/** + * Expose `isDataDescriptor` + */ - var info = getPathInfo(cmd, opt) - var pathEnv = info.env - var pathExt = info.ext - var pathExtExe = info.extExe - var found = [] +module.exports = isDataDescriptor; - for (var i = 0, l = pathEnv.length; i < l; i ++) { - var pathPart = pathEnv[i] - if (pathPart.charAt(0) === '"' && pathPart.slice(-1) === '"') - pathPart = pathPart.slice(1, -1) - var p = path.join(pathPart, cmd) - if (!pathPart && /^\.[\\\/]/.test(cmd)) { - p = cmd.slice(0, 2) + p - } - for (var j = 0, ll = pathExt.length; j < ll; j ++) { - var cur = p + pathExt[j] - var is - try { - is = isexe.sync(cur, { pathExt: pathExtExe }) - if (is) { - if (opt.all) - found.push(cur) - else - return cur - } - } catch (ex) {} - } +/***/ }), +/* 378 */ +/***/ (function(module, exports, __webpack_require__) { + +var isBuffer = __webpack_require__(22); +var toString = Object.prototype.toString; + +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ + +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; + } + + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; + } + + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } + + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } + + // other objects + var type = toString.call(val); + + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + + // buffer + if (isBuffer(val)) { + return 'buffer'; + } + + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; } - if (opt.all && found.length) - return found - - if (opt.nothrow) - return null + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } - throw getNotFoundError(cmd) -} + // must be a plain object + return 'object'; +}; /***/ }), -/* 179 */ +/* 379 */ /***/ (function(module, exports, __webpack_require__) { -var fs = __webpack_require__(16) -var core -if (process.platform === 'win32' || global.TESTING_WINDOWS) { - core = __webpack_require__(180) -} else { - core = __webpack_require__(181) +"use strict"; + + +var use = __webpack_require__(143); +var define = __webpack_require__(67); +var debug = __webpack_require__(106)('snapdragon:compiler'); +var utils = __webpack_require__(79); + +/** + * Create a new `Compiler` with the given `options`. + * @param {Object} `options` + */ + +function Compiler(options, state) { + debug('initializing', __filename); + this.options = utils.extend({source: 'string'}, options); + this.state = state || {}; + this.compilers = {}; + this.output = ''; + this.set('eos', function(node) { + return this.emit(node.val, node); + }); + this.set('noop', function(node) { + return this.emit(node.val, node); + }); + this.set('bos', function(node) { + return this.emit(node.val, node); + }); + use(this); } -module.exports = isexe -isexe.sync = sync +/** + * Prototype methods + */ -function isexe (path, options, cb) { - if (typeof options === 'function') { - cb = options - options = {} - } +Compiler.prototype = { - if (!cb) { - if (typeof Promise !== 'function') { - throw new TypeError('callback not provided') - } + /** + * Throw an error message with details including the cursor position. + * @param {String} `msg` Message to use in the Error. + */ - return new Promise(function (resolve, reject) { - isexe(path, options || {}, function (er, is) { - if (er) { - reject(er) - } else { - resolve(is) - } - }) - }) - } + error: function(msg, node) { + var pos = node.position || {start: {column: 0}}; + var message = this.options.source + ' column:' + pos.start.column + ': ' + msg; - core(path, options || {}, function (er, is) { - // ignore EACCES because that just means we aren't allowed to run it - if (er) { - if (er.code === 'EACCES' || options && options.ignoreErrors) { - er = null - is = false - } - } - cb(er, is) - }) -} + var err = new Error(message); + err.reason = msg; + err.column = pos.start.column; + err.source = this.pattern; -function sync (path, options) { - // my kingdom for a filtered catch - try { - return core.sync(path, options || {}) - } catch (er) { - if (options && options.ignoreErrors || er.code === 'EACCES') { - return false + if (this.options.silent) { + this.errors.push(err); } else { - throw er + throw err; } - } -} + }, + /** + * Define a non-enumberable property on the `Compiler` instance. + * + * ```js + * compiler.define('foo', 'bar'); + * ``` + * @name .define + * @param {String} `key` propery name + * @param {any} `val` property value + * @return {Object} Returns the Compiler instance for chaining. + * @api public + */ -/***/ }), -/* 180 */ -/***/ (function(module, exports, __webpack_require__) { + define: function(key, val) { + define(this, key, val); + return this; + }, -module.exports = isexe -isexe.sync = sync + /** + * Emit `node.val` + */ -var fs = __webpack_require__(16) + emit: function(str, node) { + this.output += str; + return str; + }, -function checkPathExt (path, options) { - var pathext = options.pathExt !== undefined ? - options.pathExt : process.env.PATHEXT + /** + * Add a compiler `fn` with the given `name` + */ - if (!pathext) { - return true - } + set: function(name, fn) { + this.compilers[name] = fn; + return this; + }, - pathext = pathext.split(';') - if (pathext.indexOf('') !== -1) { - return true - } - for (var i = 0; i < pathext.length; i++) { - var p = pathext[i].toLowerCase() - if (p && path.substr(-p.length).toLowerCase() === p) { - return true - } - } - return false -} + /** + * Get compiler `name`. + */ -function checkStat (stat, path, options) { - if (!stat.isSymbolicLink() && !stat.isFile()) { - return false - } - return checkPathExt(path, options) -} + get: function(name) { + return this.compilers[name]; + }, -function isexe (path, options, cb) { - fs.stat(path, function (er, stat) { - cb(er, er ? false : checkStat(stat, path, options)) - }) -} + /** + * Get the previous AST node. + */ -function sync (path, options) { - return checkStat(fs.statSync(path), path, options) -} + prev: function(n) { + return this.ast.nodes[this.idx - (n || 1)] || { type: 'bos', val: '' }; + }, + /** + * Get the next AST node. + */ -/***/ }), -/* 181 */ -/***/ (function(module, exports, __webpack_require__) { + next: function(n) { + return this.ast.nodes[this.idx + (n || 1)] || { type: 'eos', val: '' }; + }, -module.exports = isexe -isexe.sync = sync + /** + * Visit `node`. + */ -var fs = __webpack_require__(16) + visit: function(node, nodes, i) { + var fn = this.compilers[node.type]; + this.idx = i; -function isexe (path, options, cb) { - fs.stat(path, function (er, stat) { - cb(er, er ? false : checkStat(stat, options)) - }) -} + if (typeof fn !== 'function') { + throw this.error('compiler "' + node.type + '" is not registered', node); + } + return fn.call(this, node, nodes, i); + }, -function sync (path, options) { - return checkStat(fs.statSync(path), options) -} + /** + * Map visit over array of `nodes`. + */ -function checkStat (stat, options) { - return stat.isFile() && checkMode(stat, options) -} + mapVisit: function(nodes) { + if (!Array.isArray(nodes)) { + throw new TypeError('expected an array'); + } + var len = nodes.length; + var idx = -1; + while (++idx < len) { + this.visit(nodes[idx], nodes, idx); + } + return this; + }, -function checkMode (stat, options) { - var mod = stat.mode - var uid = stat.uid - var gid = stat.gid + /** + * Compile `ast`. + */ - var myUid = options.uid !== undefined ? - options.uid : process.getuid && process.getuid() - var myGid = options.gid !== undefined ? - options.gid : process.getgid && process.getgid() + compile: function(ast, options) { + var opts = utils.extend({}, this.options, options); + this.ast = ast; + this.parsingErrors = this.ast.errors; + this.output = ''; - var u = parseInt('100', 8) - var g = parseInt('010', 8) - var o = parseInt('001', 8) - var ug = u | g + // source map support + if (opts.sourcemap) { + var sourcemaps = __webpack_require__(407); + sourcemaps(this); + this.mapVisit(this.ast.nodes); + this.applySourceMaps(); + this.map = opts.sourcemap === 'generator' ? this.map : this.map.toJSON(); + return this; + } - var ret = (mod & o) || - (mod & g) && gid === myGid || - (mod & u) && uid === myUid || - (mod & ug) && myUid === 0 + this.mapVisit(this.ast.nodes); + return this; + } +}; - return ret -} +/** + * Expose `Compiler` + */ + +module.exports = Compiler; /***/ }), -/* 182 */ +/* 380 */ /***/ (function(module, exports, __webpack_require__) { -if (process.env.npm_package_name === 'pseudomap' && - process.env.npm_lifecycle_script === 'test') - process.env.TEST_PSEUDOMAP = 'true' +"use strict"; -if (typeof Map === 'function' && !process.env.TEST_PSEUDOMAP) { - module.exports = Map -} else { - module.exports = __webpack_require__(183) -} +var utils = {}; -/***/ }), -/* 183 */ -/***/ (function(module, exports) { -var hasOwnProperty = Object.prototype.hasOwnProperty -module.exports = PseudoMap +/** + * Lazily required module dependencies + */ -function PseudoMap (set) { - if (!(this instanceof PseudoMap)) // whyyyyyyy - throw new TypeError("Constructor PseudoMap requires 'new'") +utils.define = __webpack_require__(381); +utils.isObject = __webpack_require__(30); - this.clear() - if (set) { - if ((set instanceof PseudoMap) || - (typeof Map === 'function' && set instanceof Map)) - set.forEach(function (value, key) { - this.set(key, value) - }, this) - else if (Array.isArray(set)) - set.forEach(function (kv) { - this.set(kv[0], kv[1]) - }, this) - else - throw new TypeError('invalid argument') - } -} +utils.isString = function(val) { + return val && typeof val === 'string'; +}; -PseudoMap.prototype.forEach = function (fn, thisp) { - thisp = thisp || this - Object.keys(this._data).forEach(function (k) { - if (k !== 'size') - fn.call(thisp, this._data[k].value, this._data[k].key) - }, this) -} +/** + * Expose `utils` modules + */ -PseudoMap.prototype.has = function (k) { - return !!find(this._data, k) -} +module.exports = utils; -PseudoMap.prototype.get = function (k) { - var res = find(this._data, k) - return res && res.value -} -PseudoMap.prototype.set = function (k, v) { - set(this._data, k, v) -} +/***/ }), +/* 381 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * define-property + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + -PseudoMap.prototype.delete = function (k) { - var res = find(this._data, k) - if (res) { - delete this._data[res._index] - this._data.size-- + +var isDescriptor = __webpack_require__(382); + +module.exports = function defineProperty(obj, prop, val) { + if (typeof obj !== 'object' && typeof obj !== 'function') { + throw new TypeError('expected an object or function.'); + } + + if (typeof prop !== 'string') { + throw new TypeError('expected `prop` to be a string.'); } -} -PseudoMap.prototype.clear = function () { - var data = Object.create(null) - data.size = 0 + if (isDescriptor(val) && ('set' in val || 'get' in val)) { + return Object.defineProperty(obj, prop, val); + } - Object.defineProperty(this, '_data', { - value: data, - enumerable: false, + return Object.defineProperty(obj, prop, { configurable: true, - writable: false - }) -} + enumerable: false, + writable: true, + value: val + }); +}; -Object.defineProperty(PseudoMap.prototype, 'size', { - get: function () { - return this._data.size - }, - set: function (n) {}, - enumerable: true, - configurable: true -}) -PseudoMap.prototype.values = -PseudoMap.prototype.keys = -PseudoMap.prototype.entries = function () { - throw new Error('iterators are not implemented in this version') -} +/***/ }), +/* 382 */ +/***/ (function(module, exports, __webpack_require__) { -// Either identical, or both NaN -function same (a, b) { - return a === b || a !== a && b !== b -} +"use strict"; +/*! + * is-descriptor + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ -function Entry (k, v, i) { - this.key = k - this.value = v - this._index = i -} -function find (data, k) { - for (var i = 0, s = '_' + k, key = s; - hasOwnProperty.call(data, key); - key = s + i++) { - if (same(data[key].key, k)) - return data[key] - } -} -function set (data, k, v) { - for (var i = 0, s = '_' + k, key = s; - hasOwnProperty.call(data, key); - key = s + i++) { - if (same(data[key].key, k)) { - data[key].value = v - return - } +var typeOf = __webpack_require__(383); +var isAccessor = __webpack_require__(384); +var isData = __webpack_require__(386); + +module.exports = function isDescriptor(obj, key) { + if (typeOf(obj) !== 'object') { + return false; } - data.size++ - data[key] = new Entry(k, v, key) -} + if ('get' in obj) { + return isAccessor(obj, key); + } + return isData(obj, key); +}; /***/ }), -/* 184 */ +/* 383 */ /***/ (function(module, exports) { -module.exports = Yallist +var toString = Object.prototype.toString; -Yallist.Node = Node -Yallist.create = Yallist +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ -function Yallist (list) { - var self = this - if (!(self instanceof Yallist)) { - self = new Yallist() - } +module.exports = function kindOf(val) { + var type = typeof val; - self.tail = null - self.head = null - self.length = 0 + // primitivies + if (type === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (type === 'string' || val instanceof String) { + return 'string'; + } + if (type === 'number' || val instanceof Number) { + return 'number'; + } - if (list && typeof list.forEach === 'function') { - list.forEach(function (item) { - self.push(item) - }) - } else if (arguments.length > 0) { - for (var i = 0, l = arguments.length; i < l; i++) { - self.push(arguments[i]) + // functions + if (type === 'function' || val instanceof Function) { + if (typeof val.constructor.name !== 'undefined' && val.constructor.name.slice(0, 9) === 'Generator') { + return 'generatorfunction'; } + return 'function'; } - return self -} + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } -Yallist.prototype.removeNode = function (node) { - if (node.list !== this) { - throw new Error('removing node which does not belong to this list') + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; } - var next = node.next - var prev = node.prev + // other objects + type = toString.call(val); - if (next) { - next.prev = prev + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + if (type === '[object Promise]') { + return 'promise'; } - if (prev) { - prev.next = next + // buffer + if (isBuffer(val)) { + return 'buffer'; } - if (node === this.head) { - this.head = next + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; } - if (node === this.tail) { - this.tail = prev + if (type === '[object Symbol]') { + return 'symbol'; } + + if (type === '[object Map Iterator]') { + return 'mapiterator'; + } + if (type === '[object Set Iterator]') { + return 'setiterator'; + } + if (type === '[object String Iterator]') { + return 'stringiterator'; + } + if (type === '[object Array Iterator]') { + return 'arrayiterator'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } + + // must be a plain object + return 'object'; +}; + +/** + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer + */ - node.list.length-- - node.next = null - node.prev = null - node.list = null +function isBuffer(val) { + return val.constructor + && typeof val.constructor.isBuffer === 'function' + && val.constructor.isBuffer(val); } -Yallist.prototype.unshiftNode = function (node) { - if (node === this.head) { - return - } - if (node.list) { - node.list.removeNode(node) - } +/***/ }), +/* 384 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * is-accessor-descriptor + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +var typeOf = __webpack_require__(385); - var head = this.head - node.list = this - node.next = head - if (head) { - head.prev = node +// accessor descriptor properties +var accessor = { + get: 'function', + set: 'function', + configurable: 'boolean', + enumerable: 'boolean' +}; + +function isAccessorDescriptor(obj, prop) { + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; } - this.head = node - if (!this.tail) { - this.tail = node + if (typeOf(obj) !== 'object') { + return false; } - this.length++ -} -Yallist.prototype.pushNode = function (node) { - if (node === this.tail) { - return + if (has(obj, 'value') || has(obj, 'writable')) { + return false; } - if (node.list) { - node.list.removeNode(node) + if (!has(obj, 'get') || typeof obj.get !== 'function') { + return false; } - var tail = this.tail - node.list = this - node.prev = tail - if (tail) { - tail.next = node + // tldr: it's valid to have "set" be undefined + // "set" might be undefined if `Object.getOwnPropertyDescriptor` + // was used to get the value, and only `get` was defined by the user + if (has(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') { + return false; } - this.tail = node - if (!this.head) { - this.head = node + for (var key in obj) { + if (!accessor.hasOwnProperty(key)) { + continue; + } + + if (typeOf(obj[key]) === accessor[key]) { + continue; + } + + if (typeof obj[key] !== 'undefined') { + return false; + } } - this.length++ + return true; } -Yallist.prototype.push = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - push(this, arguments[i]) - } - return this.length +function has(obj, key) { + return {}.hasOwnProperty.call(obj, key); } -Yallist.prototype.unshift = function () { - for (var i = 0, l = arguments.length; i < l; i++) { - unshift(this, arguments[i]) +/** + * Expose `isAccessorDescriptor` + */ + +module.exports = isAccessorDescriptor; + + +/***/ }), +/* 385 */ +/***/ (function(module, exports, __webpack_require__) { + +var isBuffer = __webpack_require__(22); +var toString = Object.prototype.toString; + +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ + +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; } - return this.length -} -Yallist.prototype.pop = function () { - if (!this.tail) { - return undefined + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; } - var res = this.tail.value - this.tail = this.tail.prev - if (this.tail) { - this.tail.next = null - } else { - this.head = null + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; } - this.length-- - return res -} -Yallist.prototype.shift = function () { - if (!this.head) { - return undefined + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; } - var res = this.head.value - this.head = this.head.next - if (this.head) { - this.head.prev = null - } else { - this.tail = null + // other objects + var type = toString.call(val); + + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; } - this.length-- - return res -} -Yallist.prototype.forEach = function (fn, thisp) { - thisp = thisp || this - for (var walker = this.head, i = 0; walker !== null; i++) { - fn.call(thisp, walker.value, i, this) - walker = walker.next + // buffer + if (isBuffer(val)) { + return 'buffer'; } -} -Yallist.prototype.forEachReverse = function (fn, thisp) { - thisp = thisp || this - for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { - fn.call(thisp, walker.value, i, this) - walker = walker.prev + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; } -} -Yallist.prototype.get = function (n) { - for (var i = 0, walker = this.head; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.next + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; } - if (i === n && walker !== null) { - return walker.value + if (type === '[object Uint8Array]') { + return 'uint8array'; } -} + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } + + // must be a plain object + return 'object'; +}; -Yallist.prototype.getReverse = function (n) { - for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { - // abort out of the list early if we hit a cycle - walker = walker.prev + +/***/ }), +/* 386 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/*! + * is-data-descriptor + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + + + +var typeOf = __webpack_require__(387); + +// data descriptor properties +var data = { + configurable: 'boolean', + enumerable: 'boolean', + writable: 'boolean' +}; + +function isDataDescriptor(obj, prop) { + if (typeOf(obj) !== 'object') { + return false; } - if (i === n && walker !== null) { - return walker.value + + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; } -} -Yallist.prototype.map = function (fn, thisp) { - thisp = thisp || this - var res = new Yallist() - for (var walker = this.head; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)) - walker = walker.next + if (!('value' in obj) && !('writable' in obj)) { + return false; } - return res -} -Yallist.prototype.mapReverse = function (fn, thisp) { - thisp = thisp || this - var res = new Yallist() - for (var walker = this.tail; walker !== null;) { - res.push(fn.call(thisp, walker.value, this)) - walker = walker.prev + for (var key in obj) { + if (key === 'value') continue; + + if (!data.hasOwnProperty(key)) { + continue; + } + + if (typeOf(obj[key]) === data[key]) { + continue; + } + + if (typeof obj[key] !== 'undefined') { + return false; + } } - return res + return true; } -Yallist.prototype.reduce = function (fn, initial) { - var acc - var walker = this.head - if (arguments.length > 1) { - acc = initial - } else if (this.head) { - walker = this.head.next - acc = this.head.value - } else { - throw new TypeError('Reduce of empty list with no initial value') - } +/** + * Expose `isDataDescriptor` + */ - for (var i = 0; walker !== null; i++) { - acc = fn(acc, walker.value, i) - walker = walker.next +module.exports = isDataDescriptor; + + +/***/ }), +/* 387 */ +/***/ (function(module, exports, __webpack_require__) { + +var isBuffer = __webpack_require__(22); +var toString = Object.prototype.toString; + +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ + +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; } - return acc -} + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; + } -Yallist.prototype.reduceReverse = function (fn, initial) { - var acc - var walker = this.tail - if (arguments.length > 1) { - acc = initial - } else if (this.tail) { - walker = this.tail.prev - acc = this.tail.value - } else { - throw new TypeError('Reduce of empty list with no initial value') + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; } - for (var i = this.length - 1; walker !== null; i--) { - acc = fn(acc, walker.value, i) - walker = walker.prev + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; } - return acc -} + // other objects + var type = toString.call(val); -Yallist.prototype.toArray = function () { - var arr = new Array(this.length) - for (var i = 0, walker = this.head; walker !== null; i++) { - arr[i] = walker.value - walker = walker.next + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; } - return arr -} -Yallist.prototype.toArrayReverse = function () { - var arr = new Array(this.length) - for (var i = 0, walker = this.tail; walker !== null; i++) { - arr[i] = walker.value - walker = walker.prev + // buffer + if (isBuffer(val)) { + return 'buffer'; } - return arr -} -Yallist.prototype.slice = function (from, to) { - to = to || this.length - if (to < 0) { - to += this.length + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; } - from = from || 0 - if (from < 0) { - from += this.length + if (type === '[object WeakSet]') { + return 'weakset'; } - var ret = new Yallist() - if (to < from || to < 0) { - return ret + if (type === '[object Map]') { + return 'map'; } - if (from < 0) { - from = 0 + if (type === '[object WeakMap]') { + return 'weakmap'; } - if (to > this.length) { - to = this.length + if (type === '[object Symbol]') { + return 'symbol'; } - for (var i = 0, walker = this.head; walker !== null && i < from; i++) { - walker = walker.next + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; } - for (; walker !== null && i < to; i++, walker = walker.next) { - ret.push(walker.value) + if (type === '[object Uint8Array]') { + return 'uint8array'; } - return ret -} - -Yallist.prototype.sliceReverse = function (from, to) { - to = to || this.length - if (to < 0) { - to += this.length + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; } - from = from || 0 - if (from < 0) { - from += this.length + if (type === '[object Int16Array]') { + return 'int16array'; } - var ret = new Yallist() - if (to < from || to < 0) { - return ret + if (type === '[object Uint16Array]') { + return 'uint16array'; } - if (from < 0) { - from = 0 + if (type === '[object Int32Array]') { + return 'int32array'; } - if (to > this.length) { - to = this.length + if (type === '[object Uint32Array]') { + return 'uint32array'; } - for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { - walker = walker.prev + if (type === '[object Float32Array]') { + return 'float32array'; } - for (; walker !== null && i > from; i--, walker = walker.prev) { - ret.push(walker.value) + if (type === '[object Float64Array]') { + return 'float64array'; } - return ret -} -Yallist.prototype.reverse = function () { - var head = this.head - var tail = this.tail - for (var walker = head; walker !== null; walker = walker.prev) { - var p = walker.prev - walker.prev = walker.next - walker.next = p + // must be a plain object + return 'object'; +}; + + +/***/ }), +/* 388 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = __webpack_require__(144); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; } - this.head = tail - this.tail = head - return this + + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } -function push (self, item) { - self.tail = new Node(item, self.tail, null, self) - if (!self.head) { - self.head = self.tail +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; } - self.length++ +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!useColors) return; + + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') + + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); } -function unshift (self, item) { - self.head = new Node(item, null, self.head, self) - if (!self.tail) { - self.tail = self.head - } - self.length++ +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); } -function Node (value, prev, next, list) { - if (!(this instanceof Node)) { - return new Node(value, prev, next, list) - } +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} - this.list = list - this.value = value +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ - if (prev) { - prev.next = this - this.prev = prev - } else { - this.prev = null - } +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} - if (next) { - next.prev = this - this.next = next - } else { - this.next = null + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; } + + return r; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + return window.localStorage; + } catch (e) {} } /***/ }), -/* 185 */ -/***/ (function(module, exports, __webpack_require__) { +/* 389 */ +/***/ (function(module, exports) { -"use strict"; +/** + * Helpers. + */ +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; -// See: https://github.com/IndigoUnited/node-cross-spawn/pull/34#issuecomment-221623455 -function hasEmptyArgumentBug() { - var nodeVer; +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ - if (process.platform !== 'win32') { - return false; - } +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; - nodeVer = process.version.substr(1).split('.').map(function (num) { - return parseInt(num, 10); - }); +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ - return (nodeVer[0] === 0 && nodeVer[1] < 12); +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } } -module.exports = hasEmptyArgumentBug(); - +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ -/***/ }), -/* 186 */ -/***/ (function(module, exports, __webpack_require__) { +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} -"use strict"; +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} -var escapeArgument = __webpack_require__(109); +/** + * Pluralization helper. + */ -function escapeCommand(command) { - // Do not escape if this command is not dangerous.. - // We do this so that commands like "echo" or "ifconfig" work - // Quoting them, will make them unaccessible - return /^[a-z0-9_-]+$/i.test(command) ? command : escapeArgument(command, true); +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; } -module.exports = escapeCommand; - /***/ }), -/* 187 */ +/* 390 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +/** + * Module dependencies. + */ +var tty = __webpack_require__(391); +var util = __webpack_require__(14); -var fs = __webpack_require__(16); -var LRU = __webpack_require__(108); -var shebangCommand = __webpack_require__(188); +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ -var shebangCache = new LRU({ max: 50, maxAge: 30 * 1000 }); // Cache just for 30sec +exports = module.exports = __webpack_require__(144); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; -function readShebang(command) { - var buffer; - var fd; - var shebang; +/** + * Colors. + */ - // Check if it is in the cache first - if (shebangCache.has(command)) { - return shebangCache.get(command); - } +exports.colors = [6, 2, 3, 4, 5, 1]; - // Read the first 150 bytes from the file - buffer = new Buffer(150); +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ - try { - fd = fs.openSync(command, 'r'); - fs.readSync(fd, buffer, 0, 150, 0); - fs.closeSync(fd); - } catch (e) { /* empty */ } +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); + + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); + + obj[prop] = val; + return obj; +}, {}); - // Attempt to extract shebang (null is returned if not a shebang) - shebang = shebangCommand(buffer.toString()); +/** + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * + * $ DEBUG_FD=3 node script.js 3>debug.log + */ - // Store the shebang in the cache - shebangCache.set(command, shebang); +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; - return shebang; +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() } -module.exports = readShebang; - - -/***/ }), -/* 188 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var shebangRegex = __webpack_require__(189); +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); -module.exports = function (str) { - var match = str.match(shebangRegex); +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ - if (!match) { - return null; - } +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} - var arr = match[0].replace(/#! ?/, '').split(' '); - var bin = arr[0].split('/').pop(); - var arg = arr[1]; +/** + * Map %o to `util.inspect()`, all on a single line. + */ - return (bin === 'env' ? - arg : - bin + (arg ? ' ' + arg : '') - ); +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); }; +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ -/***/ }), -/* 189 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; -module.exports = /^#!.*/; +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; -/***/ }), -/* 190 */ -/***/ (function(module, exports, __webpack_require__) { + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; -"use strict"; + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; + } +} +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ -var isWin = process.platform === 'win32'; -var resolveCommand = __webpack_require__(107); +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} -var isNode10 = process.version.indexOf('v0.10.') === 0; +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ -function notFoundError(command, syscall) { - var err; +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; + } +} - err = new Error(syscall + ' ' + command + ' ENOENT'); - err.code = err.errno = 'ENOENT'; - err.syscall = syscall + ' ' + command; +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ - return err; +function load() { + return process.env.DEBUG; } -function hookChildProcess(cp, parsed) { - var originalEmit; +/** + * Copied from `node/src/node.js`. + * + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + */ - if (!isWin) { - return; - } +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); - originalEmit = cp.emit; - cp.emit = function (name, arg1) { - var err; + // Note stream._type is used for test-module-load-list.js - // If emitting "exit" event and exit code is 1, we need to check if - // the command exists and emit an "error" instead - // See: https://github.com/IndigoUnited/node-cross-spawn/issues/16 - if (name === 'exit') { - err = verifyENOENT(arg1, parsed, 'spawn'); + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; - if (err) { - return originalEmit.call(cp, 'error', err); - } - } + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; - return originalEmit.apply(cp, arguments); - }; -} + case 'FILE': + var fs = __webpack_require__(13); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; -function verifyENOENT(status, parsed) { - if (isWin && status === 1 && !parsed.file) { - return notFoundError(parsed.original, 'spawn'); - } + case 'PIPE': + case 'TCP': + var net = __webpack_require__(392); + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); - return null; -} + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; + + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; -function verifyENOENTSync(status, parsed) { - if (isWin && status === 1 && !parsed.file) { - return notFoundError(parsed.original, 'spawnSync'); - } + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); + } - // If we are in node 10, then we are using spawn-sync; if it exited - // with -1 it probably means that the command does not exist - if (isNode10 && status === -1) { - parsed.file = isWin ? parsed.file : resolveCommand(parsed.original); + // For supporting legacy API we put the FD here. + stream.fd = fd; - if (!parsed.file) { - return notFoundError(parsed.original, 'spawnSync'); - } - } + stream._isStdio = true; - return null; + return stream; } -module.exports.hookChildProcess = hookChildProcess; -module.exports.verifyENOENT = verifyENOENT; -module.exports.verifyENOENTSync = verifyENOENTSync; -module.exports.notFoundError = notFoundError; - +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ -/***/ }), -/* 191 */ -/***/ (function(module, exports, __webpack_require__) { +function init (debug) { + debug.inspectOpts = {}; -"use strict"; + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ -module.exports = __webpack_require__(90).spawnSync; +exports.enable(load()); /***/ }), -/* 192 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -module.exports = function (x) { - var lf = typeof x === 'string' ? '\n' : '\n'.charCodeAt(); - var cr = typeof x === 'string' ? '\r' : '\r'.charCodeAt(); - - if (x[x.length - 1] === lf) { - x = x.slice(0, x.length - 1); - } +/* 391 */ +/***/ (function(module, exports) { - if (x[x.length - 1] === cr) { - x = x.slice(0, x.length - 1); - } +module.exports = require("tty"); - return x; -}; +/***/ }), +/* 392 */ +/***/ (function(module, exports) { +module.exports = require("net"); /***/ }), -/* 193 */ +/* 393 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - -const path = __webpack_require__(7); -const pathKey = __webpack_require__(194); +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +exports.SourceMapGenerator = __webpack_require__(145).SourceMapGenerator; +exports.SourceMapConsumer = __webpack_require__(396).SourceMapConsumer; +exports.SourceNode = __webpack_require__(399).SourceNode; -module.exports = opts => { - opts = Object.assign({ - cwd: process.cwd(), - path: process.env[pathKey()] - }, opts); - let prev; - let pth = path.resolve(opts.cwd); - const ret = []; +/***/ }), +/* 394 */ +/***/ (function(module, exports) { - while (prev !== pth) { - ret.push(path.join(pth, 'node_modules/.bin')); - prev = pth; - pth = path.resolve(pth, '..'); - } +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ - // ensure the running `node` binary is used - ret.push(path.dirname(process.execPath)); +var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); - return ret.concat(opts.path).join(path.delimiter); +/** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ +exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); }; -module.exports.env = opts => { - opts = Object.assign({ - env: process.env - }, opts); +/** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ +exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' - const env = Object.assign({}, opts.env); - const path = pathKey({env}); + var littleA = 97; // 'a' + var littleZ = 122; // 'z' - opts.path = env[path]; - env[path] = module.exports(opts); + var zero = 48; // '0' + var nine = 57; // '9' - return env; -}; + var plus = 43; // '+' + var slash = 47; // '/' + var littleOffset = 26; + var numberOffset = 52; -/***/ }), -/* 194 */ -/***/ (function(module, exports, __webpack_require__) { + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } -"use strict"; + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } -module.exports = opts => { - opts = opts || {}; + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } - const env = opts.env || process.env; - const platform = opts.platform || process.platform; + // 62: + + if (charCode == plus) { + return 62; + } - if (platform !== 'win32') { - return 'PATH'; - } + // 63: / + if (charCode == slash) { + return 63; + } - return Object.keys(env).find(x => x.toUpperCase() === 'PATH') || 'Path'; + // Invalid base64 digit. + return -1; }; /***/ }), -/* 195 */ +/* 395 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ +var util = __webpack_require__(68); -var isStream = module.exports = function (stream) { - return stream !== null && typeof stream === 'object' && typeof stream.pipe === 'function'; -}; +/** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ +function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; +} -isStream.writable = function (stream) { - return isStream(stream) && stream.writable !== false && typeof stream._write === 'function' && typeof stream._writableState === 'object'; -}; +/** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ +function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; +} -isStream.readable = function (stream) { - return isStream(stream) && stream.readable !== false && typeof stream._read === 'function' && typeof stream._readableState === 'object'; -}; +/** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ +MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; -isStream.duplex = function (stream) { - return isStream.writable(stream) && isStream.readable(stream); +/** + * Add the given source mapping. + * + * @param Object aMapping + */ +MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } }; -isStream.transform = function (stream) { - return isStream.duplex(stream) && typeof stream._transform === 'function' && typeof stream._transformState === 'object'; +/** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ +MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; }; +exports.MappingList = MappingList; + /***/ }), -/* 196 */ +/* 396 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - -const bufferStream = __webpack_require__(197); - -function getStream(inputStream, opts) { - if (!inputStream) { - return Promise.reject(new Error('Expected a stream')); - } - - opts = Object.assign({maxBuffer: Infinity}, opts); - - const maxBuffer = opts.maxBuffer; - let stream; - let clean; - - const p = new Promise((resolve, reject) => { - const error = err => { - if (err) { // null check - err.bufferedData = stream.getBufferedValue(); - } - - reject(err); - }; - - stream = bufferStream(opts); - inputStream.once('error', error); - inputStream.pipe(stream); - - stream.on('data', () => { - if (stream.getBufferedLength() > maxBuffer) { - reject(new Error('maxBuffer exceeded')); - } - }); - stream.once('error', error); - stream.on('end', resolve); +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ - clean = () => { - // some streams doesn't implement the `stream.Readable` interface correctly - if (inputStream.unpipe) { - inputStream.unpipe(stream); - } - }; - }); +var util = __webpack_require__(68); +var binarySearch = __webpack_require__(397); +var ArraySet = __webpack_require__(147).ArraySet; +var base64VLQ = __webpack_require__(146); +var quickSort = __webpack_require__(398).quickSort; - p.then(clean, clean); +function SourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } - return p.then(() => stream.getBufferedValue()); + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap) + : new BasicSourceMapConsumer(sourceMap); } -module.exports = getStream; -module.exports.buffer = (stream, opts) => getStream(stream, Object.assign({}, opts, {encoding: 'buffer'})); -module.exports.array = (stream, opts) => getStream(stream, Object.assign({}, opts, {array: true})); - - -/***/ }), -/* 197 */ -/***/ (function(module, exports, __webpack_require__) { +SourceMapConsumer.fromSourceMap = function(aSourceMap) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap); +} -"use strict"; +/** + * The version of the source mapping spec that we are consuming. + */ +SourceMapConsumer.prototype._version = 3; + +// `__generatedMappings` and `__originalMappings` are arrays that hold the +// parsed mapping coordinates from the source map's "mappings" attribute. They +// are lazily instantiated, accessed via the `_generatedMappings` and +// `_originalMappings` getters respectively, and we only parse the mappings +// and create these arrays once queried for a source location. We jump through +// these hoops because there can be many thousands of mappings, and parsing +// them is expensive, so we only want to do it if we must. +// +// Each object in the arrays is of the form: +// +// { +// generatedLine: The line number in the generated code, +// generatedColumn: The column number in the generated code, +// source: The path to the original source file that generated this +// chunk of code, +// originalLine: The line number in the original source that +// corresponds to this chunk of generated code, +// originalColumn: The column number in the original source that +// corresponds to this chunk of generated code, +// name: The name of the original symbol which generated this chunk of +// code. +// } +// +// All properties except for `generatedLine` and `generatedColumn` can be +// `null`. +// +// `_generatedMappings` is ordered by the generated positions. +// +// `_originalMappings` is ordered by the original positions. -const PassThrough = __webpack_require__(41).PassThrough; +SourceMapConsumer.prototype.__generatedMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } -module.exports = opts => { - opts = Object.assign({}, opts); + return this.__generatedMappings; + } +}); - const array = opts.array; - let encoding = opts.encoding; - const buffer = encoding === 'buffer'; - let objectMode = false; +SourceMapConsumer.prototype.__originalMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } - if (array) { - objectMode = !(encoding || buffer); - } else { - encoding = encoding || 'utf8'; - } + return this.__originalMappings; + } +}); - if (buffer) { - encoding = null; - } +SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; - let len = 0; - const ret = []; - const stream = new PassThrough({objectMode}); +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; - if (encoding) { - stream.setEncoding(encoding); - } +SourceMapConsumer.GENERATED_ORDER = 1; +SourceMapConsumer.ORIGINAL_ORDER = 2; - stream.on('data', chunk => { - ret.push(chunk); +SourceMapConsumer.GREATEST_LOWER_BOUND = 1; +SourceMapConsumer.LEAST_UPPER_BOUND = 2; - if (objectMode) { - len = ret.length; - } else { - len += chunk.length; - } - }); +/** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ +SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } - stream.getBufferedValue = () => { - if (array) { - return ret; - } + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + if (source != null && sourceRoot != null) { + source = util.join(sourceRoot, source); + } + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; - return buffer ? Buffer.concat(ret, len) : ret.join(''); - }; +/** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: Optional. the column number in the original source. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ +SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + if (this.sourceRoot != null) { + needle.source = util.relative(this.sourceRoot, needle.source); + } + if (!this._sources.has(needle.source)) { + return []; + } + needle.source = this._sources.indexOf(needle.source); + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } - stream.getBufferedLength = () => len; + return mappings; + }; - return stream; -}; +exports.SourceMapConsumer = SourceMapConsumer; +/** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The only parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ +function BasicSourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); -/***/ }), -/* 198 */ -/***/ (function(module, exports, __webpack_require__) { + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); -"use strict"; + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this.file = file; +} -module.exports = (promise, onFinally) => { - onFinally = onFinally || (() => {}); +BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; - return promise.then( - val => new Promise(resolve => { - resolve(onFinally()); - }).then(() => val), - err => new Promise(resolve => { - resolve(onFinally()); - }).then(() => { - throw err; - }) - ); -}; +/** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @returns BasicSourceMapConsumer + */ +BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + destGeneratedMappings.push(destMapping); + } -/***/ }), -/* 199 */ -/***/ (function(module, exports, __webpack_require__) { + quickSort(smc.__originalMappings, util.compareByOriginalPositions); -"use strict"; + return smc; + }; -// The Node team wants to deprecate `process.bind(...)`. -// https://github.com/nodejs/node/pull/2768 -// -// However, we need the 'uv' binding for errname support. -// This is a defensive wrapper around it so `execa` will not fail entirely if it stops working someday. -// -// If this ever stops working. See: https://github.com/sindresorhus/execa/issues/31#issuecomment-215939939 for another possible solution. -let uv; +/** + * The version of the source mapping spec that we are consuming. + */ +BasicSourceMapConsumer.prototype._version = 3; -try { - uv = process.binding('uv'); +/** + * The list of original sources. + */ +Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._sources.toArray().map(function (s) { + return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; + }, this); + } +}); - if (typeof uv.errname !== 'function') { - throw new TypeError('uv.errname is not a function'); - } -} catch (err) { - console.error('execa/lib/errname: unable to establish process.binding(\'uv\')', err); - uv = null; +/** + * Provide the JIT with a nice shape / hidden class. + */ +function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; } -function errname(uv, code) { - if (uv) { - return uv.errname(code); - } - - if (!(code < 0)) { - throw new Error('err >= 0'); - } - - return `Unknown system error ${code}`; -} +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); -module.exports = code => errname(uv, code); + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } -// Used for testing the fallback behavior -module.exports.__test__ = errname; + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } -/***/ }), -/* 200 */ -/***/ (function(module, exports, __webpack_require__) { + cachedSegments[str] = segment; + } -"use strict"; + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; -const alias = ['stdin', 'stdout', 'stderr']; + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; -const hasAlias = opts => alias.some(x => Boolean(opts[x])); + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; -module.exports = opts => { - if (!opts) { - return null; - } + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; - if (opts.stdio && hasAlias(opts)) { - throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${alias.map(x => `\`${x}\``).join(', ')}`); - } + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } - if (typeof opts.stdio === 'string') { - return opts.stdio; - } + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } - const stdio = opts.stdio || []; + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; - if (!Array.isArray(stdio)) { - throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``); - } + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; - const result = []; - const len = Math.max(stdio.length, alias.length); +/** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ +BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. - for (let i = 0; i < len; i++) { - let value = null; + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } - if (stdio[i] !== undefined) { - value = stdio[i]; - } else if (opts[alias[i]] !== undefined) { - value = opts[alias[i]]; - } + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; - result[i] = value; - } +/** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ +BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } - return result; -}; + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. + * - column: The column number in the generated source. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. + * - column: The column number in the original source, or null. + * - name: The original identifier, or null. + */ +BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); -/***/ }), -/* 201 */ -/***/ (function(module, exports, __webpack_require__) { + if (index >= 0) { + var mapping = this._generatedMappings[index]; -"use strict"; + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + if (this.sourceRoot != null) { + source = util.join(this.sourceRoot, source); + } + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } -const escapeStringRegexp = __webpack_require__(82); -const ansiStyles = __webpack_require__(202); -const supportsColor = __webpack_require__(203); + return { + source: null, + line: null, + column: null, + name: null + }; + }; -const template = __webpack_require__(205); +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; -const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } -// `supportsColor.level` → `ansiStyles.color[name]` mapping -const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; + if (this.sourceRoot != null) { + aSource = util.relative(this.sourceRoot, aSource); + } -// `color-convert` models to exclude from the Chalk API due to conflicts and such -const skipModels = new Set(['gray']); + if (this._sources.has(aSource)) { + return this.sourcesContent[this._sources.indexOf(aSource)]; + } -const styles = Object.create(null); + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } -function applyOptions(obj, options) { - options = options || {}; + if ((!url.path || url.path == "/") + && this._sources.has("/" + aSource)) { + return this.sourcesContent[this._sources.indexOf("/" + aSource)]; + } + } - // Detect level if not set manually - const scLevel = supportsColor ? supportsColor.level : 0; - obj.level = options.level === undefined ? scLevel : options.level; - obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; -} + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; -function Chalk(options) { - // We check for this.template here since calling `chalk.constructor()` - // by itself will have a `this` of a previously constructed chalk object - if (!this || !(this instanceof Chalk) || this.template) { - const chalk = {}; - applyOptions(chalk, options); +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: The column number in the original source. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ +BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + if (this.sourceRoot != null) { + source = util.relative(this.sourceRoot, source); + } + if (!this._sources.has(source)) { + return { + line: null, + column: null, + lastColumn: null + }; + } + source = this._sources.indexOf(source); - chalk.template = function () { - const args = [].slice.call(arguments); - return chalkTag.apply(null, [chalk.template].concat(args)); - }; + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; - Object.setPrototypeOf(chalk, Chalk.prototype); - Object.setPrototypeOf(chalk.template, chalk); + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); - chalk.template.constructor = Chalk; + if (index >= 0) { + var mapping = this._originalMappings[index]; - return chalk.template; - } + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } - applyOptions(this, options); -} + return { + line: null, + column: null, + lastColumn: null + }; + }; -// Use bright blue on Windows as the normal blue color is illegible -if (isSimpleWindowsTerm) { - ansiStyles.blue.open = '\u001B[94m'; -} +exports.BasicSourceMapConsumer = BasicSourceMapConsumer; -for (const key of Object.keys(ansiStyles)) { - ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); +/** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The only parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ +function IndexedSourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } - styles[key] = { - get() { - const codes = ansiStyles[key]; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); - } - }; -} + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); -styles.visible = { - get() { - return build.call(this, this._styles || [], true, 'visible'); - } -}; + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } -ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); -for (const model of Object.keys(ansiStyles.color.ansi)) { - if (skipModels.has(model)) { - continue; - } + this._sources = new ArraySet(); + this._names = new ArraySet(); - styles[model] = { - get() { - const level = this.level; - return function () { - const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); - const codes = { - open, - close: ansiStyles.color.close, - closeRe: ansiStyles.color.closeRe - }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); - }; - } - }; -} + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); -ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); -for (const model of Object.keys(ansiStyles.bgColor.ansi)) { - if (skipModels.has(model)) { - continue; - } + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; - const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); - styles[bgModel] = { - get() { - const level = this.level; - return function () { - const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); - const codes = { - open, - close: ansiStyles.bgColor.close, - closeRe: ansiStyles.bgColor.closeRe - }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); - }; - } - }; + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map')) + } + }); } -const proto = Object.defineProperties(() => {}, styles); +IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; -function build(_styles, _empty, key) { - const builder = function () { - return applyStyle.apply(builder, arguments); - }; +/** + * The version of the source mapping spec that we are consuming. + */ +IndexedSourceMapConsumer.prototype._version = 3; - builder._styles = _styles; - builder._empty = _empty; +/** + * The list of original sources. + */ +Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } +}); - const self = this; +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. + * - column: The column number in the generated source. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. + * - column: The column number in the original source, or null. + * - name: The original identifier, or null. + */ +IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; - Object.defineProperty(builder, 'level', { - enumerable: true, - get() { - return self.level; - }, - set(level) { - self.level = level; - } - }); + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } - Object.defineProperty(builder, 'enabled', { - enumerable: true, - get() { - return self.enabled; - }, - set(enabled) { - self.enabled = enabled; - } - }); + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; - // See below for fix regarding invisible grey/dim combination on Windows - builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } - // `__proto__` is used because we must return a function, but there is - // no way to create a function with a different prototype - builder.__proto__ = proto; // eslint-disable-line no-proto + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; - return builder; -} +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; -function applyStyle() { - // Support varags, but simply cast to string in case there's only one arg - const args = arguments; - const argsLen = args.length; - let str = String(arguments[0]); +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; - if (argsLen === 0) { - return ''; - } +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: The column number in the original source. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ +IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } - if (argsLen > 1) { - // Don't slice `arguments`, it prevents V8 optimizations - for (let a = 1; a < argsLen; a++) { - str += ' ' + args[a]; - } - } + return { + line: null, + column: null + }; + }; - if (!this.enabled || this.level <= 0 || !str) { - return this._empty ? '' : str; - } +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + if (section.consumer.sourceRoot !== null) { + source = util.join(section.consumer.sourceRoot, source); + } + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; - // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, - // see https://github.com/chalk/chalk/issues/58 - // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. - const originalDim = ansiStyles.dim.open; - if (isSimpleWindowsTerm && this.hasGrey) { - ansiStyles.dim.open = ''; - } + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } - for (const code of this._styles.slice().reverse()) { - // Replace any instances already present with a re-opening code - // otherwise only the part of the string until said closing code - // will be colored, and the rest will simply be 'plain'. - str = code.open + str.replace(code.closeRe, code.open) + code.close; + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; - // Close the styling before a linebreak and reopen - // after next line to fix a bleed issue on macOS - // https://github.com/chalk/chalk/pull/92 - str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); - } +exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; - // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue - ansiStyles.dim.open = originalDim; - return str; -} +/***/ }), +/* 397 */ +/***/ (function(module, exports) { -function chalkTag(chalk, strings) { - if (!Array.isArray(strings)) { - // If chalk() was called by itself or with a string, - // return the string itself as a string. - return [].slice.call(arguments, 1).join(' '); - } +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ - const args = [].slice.call(arguments, 2); - const parts = [strings.raw[0]]; +exports.GREATEST_LOWER_BOUND = 1; +exports.LEAST_UPPER_BOUND = 2; - for (let i = 1; i < strings.length; i++) { - parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); - parts.push(String(strings.raw[i])); - } +/** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ +function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } - return template(chalk, parts.join('')); + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } } -Object.defineProperties(Chalk.prototype, styles); - -module.exports = Chalk(); // eslint-disable-line new-cap -module.exports.supportsColor = supportsColor; -module.exports.default = module.exports; // For TypeScript - - -/***/ }), -/* 202 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(module) { -const colorConvert = __webpack_require__(83); +/** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ +exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } -const wrapAnsi16 = (fn, offset) => function () { - const code = fn.apply(colorConvert, arguments); - return `\u001B[${code + offset}m`; -}; + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } -const wrapAnsi256 = (fn, offset) => function () { - const code = fn.apply(colorConvert, arguments); - return `\u001B[${38 + offset};5;${code}m`; -}; + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } -const wrapAnsi16m = (fn, offset) => function () { - const rgb = fn.apply(colorConvert, arguments); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; + return index; }; -function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39], - - // Bright color - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; +/***/ }), +/* 398 */ +/***/ (function(module, exports) { - // Fix humans - styles.color.grey = styles.color.gray; +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ - for (const groupName of Object.keys(styles)) { - const group = styles[groupName]; +// It turns out that some (most?) JavaScript engines don't self-host +// `Array.prototype.sort`. This makes sense because C++ will likely remain +// faster than JS when doing raw CPU-intensive sorting. However, when using a +// custom comparator function, calling back and forth between the VM's C++ and +// JIT'd JS is rather slow *and* loses JIT type information, resulting in +// worse generated code for the comparator function than would be optimal. In +// fact, when sorting with a comparator, these costs outweigh the benefits of +// sorting in C++. By using our own JS-implemented Quick Sort (below), we get +// a ~3500ms mean speed-up in `bench/bench.html`. - for (const styleName of Object.keys(group)) { - const style = group[styleName]; +/** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ +function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; +} - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; +/** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ +function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); +} - group[styleName] = styles[styleName]; +/** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ +function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. - codes.set(style[0], style[1]); - } + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); + swap(ary, i + 1, j); + var q = i + 1; - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); - } + // (2) Recurse on each half. - const rgb2rgb = (r, g, b) => [r, g, b]; + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } +} - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; +/** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ +exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); +}; - styles.color.ansi = {}; - styles.color.ansi256 = {}; - styles.color.ansi16m = { - rgb: wrapAnsi16m(rgb2rgb, 0) - }; - styles.bgColor.ansi = {}; - styles.bgColor.ansi256 = {}; - styles.bgColor.ansi16m = { - rgb: wrapAnsi16m(rgb2rgb, 10) - }; +/***/ }), +/* 399 */ +/***/ (function(module, exports, __webpack_require__) { - for (const key of Object.keys(colorConvert)) { - if (typeof colorConvert[key] !== 'object') { - continue; - } +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ - const suite = colorConvert[key]; +var SourceMapGenerator = __webpack_require__(145).SourceMapGenerator; +var util = __webpack_require__(68); - if ('ansi16' in suite) { - styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); - styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); - } +// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other +// operating systems these days (capturing the result). +var REGEX_NEWLINE = /(\r?\n)/; - if ('ansi256' in suite) { - styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); - styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); - } +// Newline character code for charCodeAt() comparisons +var NEWLINE_CODE = 10; - if ('rgb' in suite) { - styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); - styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); - } - } +// Private symbol for identifying `SourceNode`s when multiple versions of +// the source-map library are loaded. This MUST NOT CHANGE across +// versions! +var isSourceNode = "$$$isSourceNode$$$"; - return styles; +/** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ +function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); } -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); +/** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ +SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(59)(module))) + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex]; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex]; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } -/***/ }), -/* 203 */ -/***/ (function(module, exports, __webpack_require__) { + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); -"use strict"; + return node; -const os = __webpack_require__(84); -const hasFlag = __webpack_require__(204); + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; -const env = process.env; +/** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; -const support = level => { - if (level === 0) { - return false; - } +/** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; +/** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } }; -let supportLevel = (() => { - if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false')) { - return 0; - } +/** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ +SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; +}; - if (hasFlag('color=16m') || - hasFlag('color=full') || - hasFlag('color=truecolor')) { - return 3; - } +/** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ +SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; +}; - if (hasFlag('color=256')) { - return 2; - } +/** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ +SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; - if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - return 1; - } +/** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } - if (process.stdout && !process.stdout.isTTY) { - return 0; - } + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; - if (process.platform === 'win32') { - // Node.js 7.5.0 is the first version of Node.js to include a patch to - // libuv that enables 256 color output on Windows. Anything earlier and it - // won't work. However, here we target Node.js 8 at minimum as it is an LTS - // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows - // release that supports 256 colors. - const osRelease = os.release().split('.'); - if ( - Number(process.versions.node.split('.')[0]) >= 8 && - Number(osRelease[0]) >= 10 && - Number(osRelease[2]) >= 10586 - ) { - return 2; - } +/** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ +SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; +}; - return 1; - } +/** + * Returns the string representation of this source node along with a source + * map. + */ +SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { - return 1; - } + return { code: generated.code, map: map }; +}; - return 0; - } +exports.SourceNode = SourceNode; - if ('TEAMCITY_VERSION' in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } - if ('TERM_PROGRAM' in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); +/***/ }), +/* 400 */ +/***/ (function(module, exports, __webpack_require__) { - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Hyper': - return 3; - case 'Apple_Terminal': - return 2; - // No default - } - } +// Copyright 2014, 2015, 2016, 2017 Simon Lydell +// X11 (“MIT”) Licensed. (See LICENSE.) - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } +var sourceMappingURL = __webpack_require__(401) +var resolveUrl = __webpack_require__(402) +var decodeUriComponent = __webpack_require__(403) +var urix = __webpack_require__(405) +var atob = __webpack_require__(406) - if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } - if ('COLORTERM' in env) { - return 1; - } - if (env.TERM === 'dumb') { - return 0; - } +function callbackAsync(callback, error, result) { + setImmediate(function() { callback(error, result) }) +} - return 0; -})(); +function parseMapToJSON(string, data) { + try { + return JSON.parse(string.replace(/^\)\]\}'/, "")) + } catch (error) { + error.sourceMapData = data + throw error + } +} -if ('FORCE_COLOR' in env) { - supportLevel = parseInt(env.FORCE_COLOR, 10) === 0 ? 0 : (supportLevel || 1); +function readSync(read, url, data) { + var readUrl = decodeUriComponent(url) + try { + return String(read(readUrl)) + } catch (error) { + error.sourceMapData = data + throw error + } } -module.exports = process && support(supportLevel); -/***/ }), -/* 204 */ -/***/ (function(module, exports, __webpack_require__) { +function resolveSourceMap(code, codeUrl, read, callback) { + var mapData + try { + mapData = resolveSourceMapHelper(code, codeUrl) + } catch (error) { + return callbackAsync(callback, error) + } + if (!mapData || mapData.map) { + return callbackAsync(callback, null, mapData) + } + var readUrl = decodeUriComponent(mapData.url) + read(readUrl, function(error, result) { + if (error) { + error.sourceMapData = mapData + return callback(error) + } + mapData.map = String(result) + try { + mapData.map = parseMapToJSON(mapData.map, mapData) + } catch (error) { + return callback(error) + } + callback(null, mapData) + }) +} -"use strict"; +function resolveSourceMapSync(code, codeUrl, read) { + var mapData = resolveSourceMapHelper(code, codeUrl) + if (!mapData || mapData.map) { + return mapData + } + mapData.map = readSync(read, mapData.url, mapData) + mapData.map = parseMapToJSON(mapData.map, mapData) + return mapData +} -module.exports = function (flag, argv) { - argv = argv || process.argv; +var dataUriRegex = /^data:([^,;]*)(;[^,;]*)*(?:,(.*))?$/ +var jsonMimeTypeRegex = /^(?:application|text)\/json$/ - var terminatorPos = argv.indexOf('--'); - var prefix = /^-{1,2}/.test(flag) ? '' : '--'; - var pos = argv.indexOf(prefix + flag); +function resolveSourceMapHelper(code, codeUrl) { + codeUrl = urix(codeUrl) - return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); -}; + var url = sourceMappingURL.getFrom(code) + if (!url) { + return null + } + var dataUri = url.match(dataUriRegex) + if (dataUri) { + var mimeType = dataUri[1] + var lastParameter = dataUri[2] || "" + var encoded = dataUri[3] || "" + var data = { + sourceMappingURL: url, + url: null, + sourcesRelativeTo: codeUrl, + map: encoded + } + if (!jsonMimeTypeRegex.test(mimeType)) { + var error = new Error("Unuseful data uri mime type: " + (mimeType || "text/plain")) + error.sourceMapData = data + throw error + } + data.map = parseMapToJSON( + lastParameter === ";base64" ? atob(encoded) : decodeURIComponent(encoded), + data + ) + return data + } -/***/ }), -/* 205 */ -/***/ (function(module, exports, __webpack_require__) { + var mapUrl = resolveUrl(codeUrl, url) + return { + sourceMappingURL: url, + url: mapUrl, + sourcesRelativeTo: mapUrl, + map: null + } +} -"use strict"; -const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; -const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; -const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; -const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; -const ESCAPES = new Map([ - ['n', '\n'], - ['r', '\r'], - ['t', '\t'], - ['b', '\b'], - ['f', '\f'], - ['v', '\v'], - ['0', '\0'], - ['\\', '\\'], - ['e', '\u001B'], - ['a', '\u0007'] -]); +function resolveSources(map, mapUrl, read, options, callback) { + if (typeof options === "function") { + callback = options + options = {} + } + var pending = map.sources ? map.sources.length : 0 + var result = { + sourcesResolved: [], + sourcesContent: [] + } -function unescape(c) { - if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) { - return String.fromCharCode(parseInt(c.slice(1), 16)); - } + if (pending === 0) { + callbackAsync(callback, null, result) + return + } - return ESCAPES.get(c) || c; + var done = function() { + pending-- + if (pending === 0) { + callback(null, result) + } + } + + resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) { + result.sourcesResolved[index] = fullUrl + if (typeof sourceContent === "string") { + result.sourcesContent[index] = sourceContent + callbackAsync(done, null) + } else { + var readUrl = decodeUriComponent(fullUrl) + read(readUrl, function(error, source) { + result.sourcesContent[index] = error ? error : String(source) + done() + }) + } + }) } -function parseArguments(name, args) { - const results = []; - const chunks = args.trim().split(/\s*,\s*/g); - let matches; +function resolveSourcesSync(map, mapUrl, read, options) { + var result = { + sourcesResolved: [], + sourcesContent: [] + } - for (const chunk of chunks) { - if (!isNaN(chunk)) { - results.push(Number(chunk)); - } else if ((matches = chunk.match(STRING_REGEX))) { - results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr)); - } else { - throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); - } - } + if (!map.sources || map.sources.length === 0) { + return result + } - return results; + resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) { + result.sourcesResolved[index] = fullUrl + if (read !== null) { + if (typeof sourceContent === "string") { + result.sourcesContent[index] = sourceContent + } else { + var readUrl = decodeUriComponent(fullUrl) + try { + result.sourcesContent[index] = String(read(readUrl)) + } catch (error) { + result.sourcesContent[index] = error + } + } + } + }) + + return result } -function parseStyle(style) { - STYLE_REGEX.lastIndex = 0; +var endingSlash = /\/?$/ - const results = []; - let matches; +function resolveSourcesHelper(map, mapUrl, options, fn) { + options = options || {} + mapUrl = urix(mapUrl) + var fullUrl + var sourceContent + var sourceRoot + for (var index = 0, len = map.sources.length; index < len; index++) { + sourceRoot = null + if (typeof options.sourceRoot === "string") { + sourceRoot = options.sourceRoot + } else if (typeof map.sourceRoot === "string" && options.sourceRoot !== false) { + sourceRoot = map.sourceRoot + } + // If the sourceRoot is the empty string, it is equivalent to not setting + // the property at all. + if (sourceRoot === null || sourceRoot === '') { + fullUrl = resolveUrl(mapUrl, map.sources[index]) + } else { + // Make sure that the sourceRoot ends with a slash, so that `/scripts/subdir` becomes + // `/scripts/subdir/`, not `/scripts/`. Pointing to a file as source root + // does not make sense. + fullUrl = resolveUrl(mapUrl, sourceRoot.replace(endingSlash, "/"), map.sources[index]) + } + sourceContent = (map.sourcesContent || [])[index] + fn(fullUrl, sourceContent, index) + } +} - while ((matches = STYLE_REGEX.exec(style)) !== null) { - const name = matches[1]; - if (matches[2]) { - const args = parseArguments(name, matches[2]); - results.push([name].concat(args)); - } else { - results.push([name]); - } - } - return results; -} +function resolve(code, codeUrl, read, options, callback) { + if (typeof options === "function") { + callback = options + options = {} + } + if (code === null) { + var mapUrl = codeUrl + var data = { + sourceMappingURL: null, + url: mapUrl, + sourcesRelativeTo: mapUrl, + map: null + } + var readUrl = decodeUriComponent(mapUrl) + read(readUrl, function(error, result) { + if (error) { + error.sourceMapData = data + return callback(error) + } + data.map = String(result) + try { + data.map = parseMapToJSON(data.map, data) + } catch (error) { + return callback(error) + } + _resolveSources(data) + }) + } else { + resolveSourceMap(code, codeUrl, read, function(error, mapData) { + if (error) { + return callback(error) + } + if (!mapData) { + return callback(null, null) + } + _resolveSources(mapData) + }) + } -function buildStyle(chalk, styles) { - const enabled = {}; + function _resolveSources(mapData) { + resolveSources(mapData.map, mapData.sourcesRelativeTo, read, options, function(error, result) { + if (error) { + return callback(error) + } + mapData.sourcesResolved = result.sourcesResolved + mapData.sourcesContent = result.sourcesContent + callback(null, mapData) + }) + } +} - for (const layer of styles) { - for (const style of layer.styles) { - enabled[style[0]] = layer.inverse ? null : style.slice(1); - } - } +function resolveSync(code, codeUrl, read, options) { + var mapData + if (code === null) { + var mapUrl = codeUrl + mapData = { + sourceMappingURL: null, + url: mapUrl, + sourcesRelativeTo: mapUrl, + map: null + } + mapData.map = readSync(read, mapUrl, mapData) + mapData.map = parseMapToJSON(mapData.map, mapData) + } else { + mapData = resolveSourceMapSync(code, codeUrl, read) + if (!mapData) { + return null + } + } + var result = resolveSourcesSync(mapData.map, mapData.sourcesRelativeTo, read, options) + mapData.sourcesResolved = result.sourcesResolved + mapData.sourcesContent = result.sourcesContent + return mapData +} - let current = chalk; - for (const styleName of Object.keys(enabled)) { - if (Array.isArray(enabled[styleName])) { - if (!(styleName in current)) { - throw new Error(`Unknown Chalk style: ${styleName}`); - } - if (enabled[styleName].length > 0) { - current = current[styleName].apply(current, enabled[styleName]); - } else { - current = current[styleName]; - } - } - } - return current; +module.exports = { + resolveSourceMap: resolveSourceMap, + resolveSourceMapSync: resolveSourceMapSync, + resolveSources: resolveSources, + resolveSourcesSync: resolveSourcesSync, + resolve: resolve, + resolveSync: resolveSync, + parseMapToJSON: parseMapToJSON } -module.exports = (chalk, tmp) => { - const styles = []; - const chunks = []; - let chunk = []; - // eslint-disable-next-line max-params - tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { - if (escapeChar) { - chunk.push(unescape(escapeChar)); - } else if (style) { - const str = chunk.join(''); - chunk = []; - chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); - styles.push({inverse, styles: parseStyle(style)}); - } else if (close) { - if (styles.length === 0) { - throw new Error('Found extraneous } in Chalk template literal'); - } +/***/ }), +/* 401 */ +/***/ (function(module, exports, __webpack_require__) { - chunks.push(buildStyle(chalk, styles)(chunk.join(''))); - chunk = []; - styles.pop(); - } else { - chunk.push(chr); - } - }); +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;// Copyright 2014 Simon Lydell +// X11 (“MIT”) Licensed. (See LICENSE.) + +void (function(root, factory) { + if (true) { + !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : + __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) + } else {} +}(this, function() { + + var innerRegex = /[#@] sourceMappingURL=([^\s'"]*)/ + + var regex = RegExp( + "(?:" + + "/\\*" + + "(?:\\s*\r?\n(?://)?)?" + + "(?:" + innerRegex.source + ")" + + "\\s*" + + "\\*/" + + "|" + + "//(?:" + innerRegex.source + ")" + + ")" + + "\\s*" + ) - chunks.push(chunk.join('')); + return { - if (styles.length > 0) { - const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; - throw new Error(errMsg); - } + regex: regex, + _innerRegex: innerRegex, - return chunks.join(''); -}; + getFrom: function(code) { + var match = code.match(regex) + return (match ? match[1] || match[2] || "" : null) + }, + existsIn: function(code) { + return regex.test(code) + }, -/***/ }), -/* 206 */ -/***/ (function(module, exports, __webpack_require__) { + removeFrom: function(code) { + return code.replace(regex, "") + }, -// Copyright IBM Corp. 2014,2018. All Rights Reserved. -// Node module: strong-log-transformer -// This file is licensed under the Apache License 2.0. -// License text available at https://opensource.org/licenses/Apache-2.0 + insertBefore: function(code, string) { + var match = code.match(regex) + if (match) { + return code.slice(0, match.index) + string + code.slice(match.index) + } else { + return code + string + } + } + } -module.exports = __webpack_require__(111); -module.exports.cli = __webpack_require__(211); +})); /***/ }), -/* 207 */ +/* 402 */ /***/ (function(module, exports, __webpack_require__) { -// Copyright (C) 2011-2015 John Hewson -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to -// deal in the Software without restriction, including without limitation the -// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -// sell copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -// IN THE SOFTWARE. +// Copyright 2014 Simon Lydell +// X11 (“MIT”) Licensed. (See LICENSE.) -var stream = __webpack_require__(41), - util = __webpack_require__(19), - timers = __webpack_require__(208); +var url = __webpack_require__(102) -// convinience API -module.exports = function(readStream, options) { - return module.exports.createStream(readStream, options); -}; +function resolveUrl(/* ...urls */) { + return Array.prototype.reduce.call(arguments, function(resolved, nextUrl) { + return url.resolve(resolved, nextUrl) + }) +} -// basic API -module.exports.createStream = function(readStream, options) { - if (readStream) { - return createLineStream(readStream, options); - } else { - return new LineStream(options); - } -}; +module.exports = resolveUrl -// deprecated API -module.exports.createLineStream = function(readStream) { - console.log('WARNING: byline#createLineStream is deprecated and will be removed soon'); - return createLineStream(readStream); -}; -function createLineStream(readStream, options) { - if (!readStream) { - throw new Error('expected readStream'); - } - if (!readStream.readable) { - throw new Error('readStream must be readable'); - } - var ls = new LineStream(options); - readStream.pipe(ls); - return ls; +/***/ }), +/* 403 */ +/***/ (function(module, exports, __webpack_require__) { + +// Copyright 2017 Simon Lydell +// X11 (“MIT”) Licensed. (See LICENSE.) + +var decodeUriComponent = __webpack_require__(404) + +function customDecodeUriComponent(string) { + // `decodeUriComponent` turns `+` into ` `, but that's not wanted. + return decodeUriComponent(string.replace(/\+/g, "%2B")) } -// -// using the new node v0.10 "streams2" API -// +module.exports = customDecodeUriComponent -module.exports.LineStream = LineStream; -function LineStream(options) { - stream.Transform.call(this, options); - options = options || {}; +/***/ }), +/* 404 */ +/***/ (function(module, exports, __webpack_require__) { - // use objectMode to stop the output from being buffered - // which re-concatanates the lines, just without newlines. - this._readableState.objectMode = true; - this._lineBuffer = []; - this._keepEmptyLines = options.keepEmptyLines || false; - this._lastChunkEndedWithCR = false; +"use strict"; - // take the source's encoding if we don't have one - var self = this; - this.on('pipe', function(src) { - if (!self.encoding) { - // but we can't do this for old-style streams - if (src instanceof stream.Readable) { - self.encoding = src._readableState.encoding; - } - } - }); -} -util.inherits(LineStream, stream.Transform); +var token = '%[a-f0-9]{2}'; +var singleMatcher = new RegExp(token, 'gi'); +var multiMatcher = new RegExp('(' + token + ')+', 'gi'); -LineStream.prototype._transform = function(chunk, encoding, done) { - // decode binary chunks as UTF-8 - encoding = encoding || 'utf8'; - - if (Buffer.isBuffer(chunk)) { - if (encoding == 'buffer') { - chunk = chunk.toString(); // utf8 - encoding = 'utf8'; - } - else { - chunk = chunk.toString(encoding); - } - } - this._chunkEncoding = encoding; - - // see: http://www.unicode.org/reports/tr18/#Line_Boundaries - var lines = chunk.split(/\r\n|[\n\v\f\r\x85\u2028\u2029]/g); - - // don't split CRLF which spans chunks - if (this._lastChunkEndedWithCR && chunk[0] == '\n') { - lines.shift(); - } - - if (this._lineBuffer.length > 0) { - this._lineBuffer[this._lineBuffer.length - 1] += lines[0]; - lines.shift(); - } +function decodeComponents(components, split) { + try { + // Try to decode the entire string first + return decodeURIComponent(components.join('')); + } catch (err) { + // Do nothing + } - this._lastChunkEndedWithCR = chunk[chunk.length - 1] == '\r'; - this._lineBuffer = this._lineBuffer.concat(lines); - this._pushBuffer(encoding, 1, done); -}; + if (components.length === 1) { + return components; + } -LineStream.prototype._pushBuffer = function(encoding, keep, done) { - // always buffer the last (possibly partial) line - while (this._lineBuffer.length > keep) { - var line = this._lineBuffer.shift(); - // skip empty lines - if (this._keepEmptyLines || line.length > 0 ) { - if (!this.push(this._reencode(line, encoding))) { - // when the high-water mark is reached, defer pushes until the next tick - var self = this; - timers.setImmediate(function() { - self._pushBuffer(encoding, keep, done); - }); - return; - } - } - } - done(); -}; + split = split || 1; -LineStream.prototype._flush = function(done) { - this._pushBuffer(this._chunkEncoding, 0, done); -}; + // Split the array in 2 parts + var left = components.slice(0, split); + var right = components.slice(split); -// see Readable::push -LineStream.prototype._reencode = function(line, chunkEncoding) { - if (this.encoding && this.encoding != chunkEncoding) { - return new Buffer(line, chunkEncoding).toString(this.encoding); - } - else if (this.encoding) { - // this should be the most common case, i.e. we're using an encoded source stream - return line; - } - else { - return new Buffer(line, chunkEncoding); - } -}; + return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right)); +} +function decode(input) { + try { + return decodeURIComponent(input); + } catch (err) { + var tokens = input.match(singleMatcher); -/***/ }), -/* 208 */ -/***/ (function(module, exports) { + for (var i = 1; i < tokens.length; i++) { + input = decodeComponents(tokens, i).join(''); -module.exports = require("timers"); + tokens = input.match(singleMatcher); + } -/***/ }), -/* 209 */ -/***/ (function(module, exports, __webpack_require__) { + return input; + } +} -var Stream = __webpack_require__(41) +function customDecodeURIComponent(input) { + // Keep track of all the replacements and prefill the map with the `BOM` + var replaceMap = { + '%FE%FF': '\uFFFD\uFFFD', + '%FF%FE': '\uFFFD\uFFFD' + }; -// through -// -// a stream that does nothing but re-emit the input. -// useful for aggregating a series of changing but not ending streams into one stream) + var match = multiMatcher.exec(input); + while (match) { + try { + // Decode as big chunks as possible + replaceMap[match[0]] = decodeURIComponent(match[0]); + } catch (err) { + var result = decode(match[0]); -exports = module.exports = through -through.through = through + if (result !== match[0]) { + replaceMap[match[0]] = result; + } + } -//create a readable writable stream. + match = multiMatcher.exec(input); + } -function through (write, end, opts) { - write = write || function (data) { this.queue(data) } - end = end || function () { this.queue(null) } + // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else + replaceMap['%C2'] = '\uFFFD'; - var ended = false, destroyed = false, buffer = [], _ended = false - var stream = new Stream() - stream.readable = stream.writable = true - stream.paused = false + var entries = Object.keys(replaceMap); -// stream.autoPause = !(opts && opts.autoPause === false) - stream.autoDestroy = !(opts && opts.autoDestroy === false) + for (var i = 0; i < entries.length; i++) { + // Replace all decoded components + var key = entries[i]; + input = input.replace(new RegExp(key, 'g'), replaceMap[key]); + } - stream.write = function (data) { - write.call(this, data) - return !stream.paused - } + return input; +} - function drain() { - while(buffer.length && !stream.paused) { - var data = buffer.shift() - if(null === data) - return stream.emit('end') - else - stream.emit('data', data) - } - } +module.exports = function (encodedURI) { + if (typeof encodedURI !== 'string') { + throw new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`'); + } - stream.queue = stream.push = function (data) { -// console.error(ended) - if(_ended) return stream - if(data === null) _ended = true - buffer.push(data) - drain() - return stream - } + try { + encodedURI = encodedURI.replace(/\+/g, ' '); - //this will be registered as the first 'end' listener - //must call destroy next tick, to make sure we're after any - //stream piped from here. - //this is only a problem if end is not emitted synchronously. - //a nicer way to do this is to make sure this is the last listener for 'end' + // Try the built in decoder first + return decodeURIComponent(encodedURI); + } catch (err) { + // Fallback to a more advanced decoder + return customDecodeURIComponent(encodedURI); + } +}; - stream.on('end', function () { - stream.readable = false - if(!stream.writable && stream.autoDestroy) - process.nextTick(function () { - stream.destroy() - }) - }) - function _end () { - stream.writable = false - end.call(stream) - if(!stream.readable && stream.autoDestroy) - stream.destroy() - } +/***/ }), +/* 405 */ +/***/ (function(module, exports, __webpack_require__) { - stream.end = function (data) { - if(ended) return - ended = true - if(arguments.length) stream.write(data) - _end() // will emit or queue - return stream - } +// Copyright 2014 Simon Lydell +// X11 (“MIT”) Licensed. (See LICENSE.) + +var path = __webpack_require__(5) + +"use strict" + +function urix(aPath) { + if (path.sep === "\\") { + return aPath + .replace(/\\/g, "/") + .replace(/^[a-z]:\/?/i, "/") + } + return aPath +} + +module.exports = urix - stream.destroy = function () { - if(destroyed) return - destroyed = true - ended = true - buffer.length = 0 - stream.writable = stream.readable = false - stream.emit('close') - return stream - } - stream.pause = function () { - if(stream.paused) return - stream.paused = true - return stream - } +/***/ }), +/* 406 */ +/***/ (function(module, exports, __webpack_require__) { - stream.resume = function () { - if(stream.paused) { - stream.paused = false - stream.emit('resume') - } - drain() - //may have become paused again, - //as drain emits 'data'. - if(!stream.paused) - stream.emit('drain') - return stream - } - return stream +"use strict"; + + +function atob(str) { + return Buffer.from(str, 'base64').toString('binary'); } +module.exports = atob.atob = atob; /***/ }), -/* 210 */ +/* 407 */ /***/ (function(module, exports, __webpack_require__) { -var Stream = __webpack_require__(41) -var writeMethods = ["write", "end", "destroy"] -var readMethods = ["resume", "pause"] -var readEvents = ["data", "close"] -var slice = Array.prototype.slice +"use strict"; -module.exports = duplex -function forEach (arr, fn) { - if (arr.forEach) { - return arr.forEach(fn) - } +var fs = __webpack_require__(13); +var path = __webpack_require__(5); +var define = __webpack_require__(67); +var utils = __webpack_require__(79); - for (var i = 0; i < arr.length; i++) { - fn(arr[i], i) - } -} +/** + * Expose `mixin()`. + * This code is based on `source-maps-support.js` in reworkcss/css + * https://github.com/reworkcss/css/blob/master/lib/stringify/source-map-support.js + * Copyright (c) 2012 TJ Holowaychuk + */ -function duplex(writer, reader) { - var stream = new Stream() - var ended = false +module.exports = mixin; - forEach(writeMethods, proxyWriter) +/** + * Mixin source map support into `compiler`. + * + * @param {Object} `compiler` + * @api public + */ - forEach(readMethods, proxyReader) +function mixin(compiler) { + define(compiler, '_comment', compiler.comment); + compiler.map = new utils.SourceMap.SourceMapGenerator(); + compiler.position = { line: 1, column: 1 }; + compiler.content = {}; + compiler.files = {}; - forEach(readEvents, proxyStream) + for (var key in exports) { + define(compiler, key, exports[key]); + } +} - reader.on("end", handleEnd) +/** + * Update position. + * + * @param {String} str + */ - writer.on("drain", function() { - stream.emit("drain") - }) +exports.updatePosition = function(str) { + var lines = str.match(/\n/g); + if (lines) this.position.line += lines.length; + var i = str.lastIndexOf('\n'); + this.position.column = ~i ? str.length - i : this.position.column + str.length; +}; - writer.on("error", reemit) - reader.on("error", reemit) +/** + * Emit `str` with `position`. + * + * @param {String} str + * @param {Object} [pos] + * @return {String} + */ - stream.writable = writer.writable - stream.readable = reader.readable +exports.emit = function(str, node) { + var position = node.position || {}; + var source = position.source; + if (source) { + if (position.filepath) { + source = utils.unixify(position.filepath); + } + + this.map.addMapping({ + source: source, + generated: { + line: this.position.line, + column: Math.max(this.position.column - 1, 0) + }, + original: { + line: position.start.line, + column: position.start.column - 1 + } + }); - return stream + if (position.content) { + this.addContent(source, position); + } + if (position.filepath) { + this.addFile(source, position); + } - function proxyWriter(methodName) { - stream[methodName] = method + this.updatePosition(str); + this.output += str; + } + return str; +}; - function method() { - return writer[methodName].apply(writer, arguments) - } - } +/** + * Adds a file to the source map output if it has not already been added + * @param {String} `file` + * @param {Object} `pos` + */ - function proxyReader(methodName) { - stream[methodName] = method +exports.addFile = function(file, position) { + if (typeof position.content !== 'string') return; + if (Object.prototype.hasOwnProperty.call(this.files, file)) return; + this.files[file] = position.content; +}; - function method() { - stream.emit(methodName) - var func = reader[methodName] - if (func) { - return func.apply(reader, arguments) - } - reader.emit(methodName) - } - } +/** + * Adds a content source to the source map output if it has not already been added + * @param {String} `source` + * @param {Object} `position` + */ - function proxyStream(methodName) { - reader.on(methodName, reemit) +exports.addContent = function(source, position) { + if (typeof position.content !== 'string') return; + if (Object.prototype.hasOwnProperty.call(this.content, source)) return; + this.map.setSourceContent(source, position.content); +}; - function reemit() { - var args = slice.call(arguments) - args.unshift(methodName) - stream.emit.apply(stream, args) - } - } +/** + * Applies any original source maps to the output and embeds the source file + * contents in the source map. + */ - function handleEnd() { - if (ended) { - return - } - ended = true - var args = slice.call(arguments) - args.unshift("end") - stream.emit.apply(stream, args) +exports.applySourceMaps = function() { + Object.keys(this.files).forEach(function(file) { + var content = this.files[file]; + this.map.setSourceContent(file, content); + + if (this.options.inputSourcemaps === true) { + var originalMap = utils.sourceMapResolve.resolveSync(content, file, fs.readFileSync); + if (originalMap) { + var map = new utils.SourceMap.SourceMapConsumer(originalMap.map); + var relativeTo = originalMap.sourcesRelativeTo; + this.map.applySourceMap(map, file, utils.unixify(path.dirname(relativeTo))); + } } + }, this); +}; - function reemit(err) { - stream.emit("error", err) - } -} +/** + * Process comments, drops sourceMap comments. + * @param {Object} node + */ + +exports.comment = function(node) { + if (/^# sourceMappingURL=/.test(node.comment)) { + return this.emit('', node.position); + } + return this._comment(node); +}; /***/ }), -/* 211 */ +/* 408 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -// Copyright IBM Corp. 2014,2018. All Rights Reserved. -// Node module: strong-log-transformer -// This file is licensed under the Apache License 2.0. -// License text available at https://opensource.org/licenses/Apache-2.0 +var use = __webpack_require__(143); +var util = __webpack_require__(14); +var Cache = __webpack_require__(148); +var define = __webpack_require__(67); +var debug = __webpack_require__(106)('snapdragon:parser'); +var Position = __webpack_require__(409); +var utils = __webpack_require__(79); -var minimist = __webpack_require__(212); -var path = __webpack_require__(7); +/** + * Create a new `Parser` with the given `input` and `options`. + * @param {String} `input` + * @param {Object} `options` + * @api public + */ -var Logger = __webpack_require__(111); -var pkg = __webpack_require__(213); +function Parser(options) { + debug('initializing', __filename); + this.options = utils.extend({source: 'string'}, options); + this.init(this.options); + use(this); +} -module.exports = cli; +/** + * Prototype methods + */ -function cli(args) { - var opts = minimist(args.slice(2)); - var $0 = path.basename(args[1]); - var p = console.log.bind(console); - if (opts.v || opts.version) { - version($0, p); - } else if (opts.h || opts.help) { - usage($0, p); - } else if (args.length < 3) { - process.stdin.pipe(Logger()).pipe(process.stdout); - } else { - process.stdin.pipe(Logger(opts)).pipe(process.stdout); - } -} +Parser.prototype = { + constructor: Parser, -function version($0, p) { - p('%s v%s', pkg.name, pkg.version); -} + init: function(options) { + this.orig = ''; + this.input = ''; + this.parsed = ''; -function usage($0, p) { - var PADDING = ' '; - var opt, def; - p('Usage: %s [options]', $0); - p(''); - p('%s', pkg.description); - p(''); - p('OPTIONS:'); - for (opt in Logger.DEFAULTS) { - def = Logger.DEFAULTS[opt]; - if (typeof def === 'boolean') - boolOpt(opt, Logger.DEFAULTS[opt]); - else - stdOpt(opt, Logger.DEFAULTS[opt]); - } - p(''); + this.column = 1; + this.line = 1; - function boolOpt(name, def) { - name = name + PADDING.slice(0, 20-name.length); - p(' --%s default: %s', name, def); - } + this.regex = new Cache(); + this.errors = this.errors || []; + this.parsers = this.parsers || {}; + this.types = this.types || []; + this.sets = this.sets || {}; + this.fns = this.fns || []; + this.currentType = 'root'; - function stdOpt(name, def) { - var value = name.toUpperCase() + - PADDING.slice(0, 19 - name.length*2); - p(' --%s %s default: %j', name, value, def); - } -} + var pos = this.position(); + this.bos = pos({type: 'bos', val: ''}); + this.ast = { + type: 'root', + errors: this.errors, + nodes: [this.bos] + }; -/***/ }), -/* 212 */ -/***/ (function(module, exports) { + define(this.bos, 'parent', this.ast); + this.nodes = [this.ast]; -module.exports = function (args, opts) { - if (!opts) opts = {}; - - var flags = { bools : {}, strings : {}, unknownFn: null }; + this.count = 0; + this.setCount = 0; + this.stack = []; + }, - if (typeof opts['unknown'] === 'function') { - flags.unknownFn = opts['unknown']; - } + /** + * Throw a formatted error with the cursor column and `msg`. + * @param {String} `msg` Message to use in the Error. + */ - if (typeof opts['boolean'] === 'boolean' && opts['boolean']) { - flags.allBools = true; + error: function(msg, node) { + var pos = node.position || {start: {column: 0, line: 0}}; + var line = pos.start.line; + var column = pos.start.column; + var source = this.options.source; + + var message = source + ' : ' + msg; + var err = new Error(message); + err.source = source; + err.reason = msg; + err.pos = pos; + + if (this.options.silent) { + this.errors.push(err); } else { - [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { - flags.bools[key] = true; - }); + throw err; } - - var aliases = {}; - Object.keys(opts.alias || {}).forEach(function (key) { - aliases[key] = [].concat(opts.alias[key]); - aliases[key].forEach(function (x) { - aliases[x] = [key].concat(aliases[key].filter(function (y) { - return x !== y; - })); - }); - }); + }, - [].concat(opts.string).filter(Boolean).forEach(function (key) { - flags.strings[key] = true; - if (aliases[key]) { - flags.strings[aliases[key]] = true; - } - }); + /** + * Define a non-enumberable property on the `Parser` instance. + * + * ```js + * parser.define('foo', 'bar'); + * ``` + * @name .define + * @param {String} `key` propery name + * @param {any} `val` property value + * @return {Object} Returns the Parser instance for chaining. + * @api public + */ - var defaults = opts['default'] || {}; - - var argv = { _ : [] }; - Object.keys(flags.bools).forEach(function (key) { - setArg(key, defaults[key] === undefined ? false : defaults[key]); - }); - - var notFlags = []; + define: function(key, val) { + define(this, key, val); + return this; + }, - if (args.indexOf('--') !== -1) { - notFlags = args.slice(args.indexOf('--')+1); - args = args.slice(0, args.indexOf('--')); - } + /** + * Mark position and patch `node.position`. + */ - function argDefined(key, arg) { - return (flags.allBools && /^--[^=]+$/.test(arg)) || - flags.strings[key] || flags.bools[key] || aliases[key]; - } + position: function() { + var start = { line: this.line, column: this.column }; + var self = this; - function setArg (key, val, arg) { - if (arg && flags.unknownFn && !argDefined(key, arg)) { - if (flags.unknownFn(arg) === false) return; - } + return function(node) { + define(node, 'position', new Position(start, self)); + return node; + }; + }, - var value = !flags.strings[key] && isNumber(val) - ? Number(val) : val - ; - setKey(argv, key.split('.'), value); - - (aliases[key] || []).forEach(function (x) { - setKey(argv, x.split('.'), value); - }); + /** + * Set parser `name` with the given `fn` + * @param {String} `name` + * @param {Function} `fn` + * @api public + */ + + set: function(type, fn) { + if (this.types.indexOf(type) === -1) { + this.types.push(type); } + this.parsers[type] = fn.bind(this); + return this; + }, - function setKey (obj, keys, value) { - var o = obj; - keys.slice(0,-1).forEach(function (key) { - if (o[key] === undefined) o[key] = {}; - o = o[key]; - }); + /** + * Get parser `name` + * @param {String} `name` + * @api public + */ - var key = keys[keys.length - 1]; - if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') { - o[key] = value; - } - else if (Array.isArray(o[key])) { - o[key].push(value); - } - else { - o[key] = [ o[key], value ]; - } - } - - function aliasIsBoolean(key) { - return aliases[key].some(function (x) { - return flags.bools[x]; - }); - } + get: function(name) { + return this.parsers[name]; + }, - for (var i = 0; i < args.length; i++) { - var arg = args[i]; - - if (/^--.+=/.test(arg)) { - // Using [\s\S] instead of . because js doesn't support the - // 'dotall' regex modifier. See: - // http://stackoverflow.com/a/1068308/13216 - var m = arg.match(/^--([^=]+)=([\s\S]*)$/); - var key = m[1]; - var value = m[2]; - if (flags.bools[key]) { - value = value !== 'false'; - } - setArg(key, value, arg); - } - else if (/^--no-.+/.test(arg)) { - var key = arg.match(/^--no-(.+)/)[1]; - setArg(key, false, arg); - } - else if (/^--.+/.test(arg)) { - var key = arg.match(/^--(.+)/)[1]; - var next = args[i + 1]; - if (next !== undefined && !/^-/.test(next) - && !flags.bools[key] - && !flags.allBools - && (aliases[key] ? !aliasIsBoolean(key) : true)) { - setArg(key, next, arg); - i++; - } - else if (/^(true|false)$/.test(next)) { - setArg(key, next === 'true', arg); - i++; - } - else { - setArg(key, flags.strings[key] ? '' : true, arg); - } - } - else if (/^-[^-]+/.test(arg)) { - var letters = arg.slice(1,-1).split(''); - - var broken = false; - for (var j = 0; j < letters.length; j++) { - var next = arg.slice(j+2); - - if (next === '-') { - setArg(letters[j], next, arg) - continue; - } - - if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) { - setArg(letters[j], next.split('=')[1], arg); - broken = true; - break; - } - - if (/[A-Za-z]/.test(letters[j]) - && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { - setArg(letters[j], next, arg); - broken = true; - break; - } - - if (letters[j+1] && letters[j+1].match(/\W/)) { - setArg(letters[j], arg.slice(j+2), arg); - broken = true; - break; - } - else { - setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg); - } - } - - var key = arg.slice(-1)[0]; - if (!broken && key !== '-') { - if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1]) - && !flags.bools[key] - && (aliases[key] ? !aliasIsBoolean(key) : true)) { - setArg(key, args[i+1], arg); - i++; - } - else if (args[i+1] && /true|false/.test(args[i+1])) { - setArg(key, args[i+1] === 'true', arg); - i++; - } - else { - setArg(key, flags.strings[key] ? '' : true, arg); - } - } - } - else { - if (!flags.unknownFn || flags.unknownFn(arg) !== false) { - argv._.push( - flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) - ); - } - if (opts.stopEarly) { - argv._.push.apply(argv._, args.slice(i + 1)); - break; - } - } - } - - Object.keys(defaults).forEach(function (key) { - if (!hasKey(argv, key.split('.'))) { - setKey(argv, key.split('.'), defaults[key]); - - (aliases[key] || []).forEach(function (x) { - setKey(argv, x.split('.'), defaults[key]); - }); - } - }); - - if (opts['--']) { - argv['--'] = new Array(); - notFlags.forEach(function(key) { - argv['--'].push(key); - }); + /** + * Push a `token` onto the `type` stack. + * + * @param {String} `type` + * @return {Object} `token` + * @api public + */ + + push: function(type, token) { + this.sets[type] = this.sets[type] || []; + this.count++; + this.stack.push(token); + return this.sets[type].push(token); + }, + + /** + * Pop a token off of the `type` stack + * @param {String} `type` + * @returns {Object} Returns a token + * @api public + */ + + pop: function(type) { + this.sets[type] = this.sets[type] || []; + this.count--; + this.stack.pop(); + return this.sets[type].pop(); + }, + + /** + * Return true if inside a `stack` node. Types are `braces`, `parens` or `brackets`. + * + * @param {String} `type` + * @return {Boolean} + * @api public + */ + + isInside: function(type) { + this.sets[type] = this.sets[type] || []; + return this.sets[type].length > 0; + }, + + /** + * Return true if `node` is the given `type`. + * + * ```js + * parser.isType(node, 'brace'); + * ``` + * @param {Object} `node` + * @param {String} `type` + * @return {Boolean} + * @api public + */ + + isType: function(node, type) { + return node && node.type === type; + }, + + /** + * Get the previous AST node + * @return {Object} + */ + + prev: function(n) { + return this.stack.length > 0 + ? utils.last(this.stack, n) + : utils.last(this.nodes, n); + }, + + /** + * Update line and column based on `str`. + */ + + consume: function(len) { + this.input = this.input.substr(len); + }, + + /** + * Update column based on `str`. + */ + + updatePosition: function(str, len) { + var lines = str.match(/\n/g); + if (lines) this.line += lines.length; + var i = str.lastIndexOf('\n'); + this.column = ~i ? len - i : this.column + len; + this.parsed += str; + this.consume(len); + }, + + /** + * Match `regex`, return captures, and update the cursor position by `match[0]` length. + * @param {RegExp} `regex` + * @return {Object} + */ + + match: function(regex) { + var m = regex.exec(this.input); + if (m) { + this.updatePosition(m[0], m[0].length); + return m; } - else { - notFlags.forEach(function(key) { - argv._.push(key); - }); + }, + + /** + * Capture `type` with the given regex. + * @param {String} `type` + * @param {RegExp} `regex` + * @return {Function} + */ + + capture: function(type, regex) { + if (typeof regex === 'function') { + return this.set.apply(this, arguments); } - return argv; -}; + this.regex.set(type, regex); + this.set(type, function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(regex); + if (!m || !m[0]) return; -function hasKey (obj, keys) { - var o = obj; - keys.slice(0,-1).forEach(function (key) { - o = (o[key] || {}); + var prev = this.prev(); + var node = pos({ + type: type, + val: m[0], + parsed: parsed, + rest: this.input + }); + + if (m[1]) { + node.inner = m[1]; + } + + define(node, 'inside', this.stack.length > 0); + define(node, 'parent', prev); + prev.nodes.push(node); + }.bind(this)); + return this; + }, + + /** + * Create a parser with open and close for parens, + * brackets or braces + */ + + capturePair: function(type, openRegex, closeRegex, fn) { + this.sets[type] = this.sets[type] || []; + + /** + * Open + */ + + this.set(type + '.open', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(openRegex); + if (!m || !m[0]) return; + + var val = m[0]; + this.setCount++; + this.specialChars = true; + var open = pos({ + type: type + '.open', + val: val, + rest: this.input + }); + + if (typeof m[1] !== 'undefined') { + open.inner = m[1]; + } + + var prev = this.prev(); + var node = pos({ + type: type, + nodes: [open] + }); + + define(node, 'rest', this.input); + define(node, 'parsed', parsed); + define(node, 'prefix', m[1]); + define(node, 'parent', prev); + define(open, 'parent', node); + + if (typeof fn === 'function') { + fn.call(this, open, node); + } + + this.push(type, node); + prev.nodes.push(node); }); - var key = keys[keys.length - 1]; - return key in o; -} + /** + * Close + */ -function isNumber (x) { - if (typeof x === 'number') return true; - if (/^0x[0-9a-f]+$/i.test(x)) return true; - return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); -} + this.set(type + '.close', function() { + var pos = this.position(); + var m = this.match(closeRegex); + if (!m || !m[0]) return; + + var parent = this.pop(type); + var node = pos({ + type: type + '.close', + rest: this.input, + suffix: m[1], + val: m[0] + }); + if (!this.isType(parent, type)) { + if (this.options.strict) { + throw new Error('missing opening "' + type + '"'); + } + this.setCount--; + node.escaped = true; + return node; + } -/***/ }), -/* 213 */ -/***/ (function(module) { + if (node.suffix === '\\') { + parent.escaped = true; + node.escaped = true; + } -module.exports = {"name":"strong-log-transformer","version":"2.0.0","description":"Stream transformer that prefixes lines with timestamps and other things.","author":"Ryan Graham ","license":"Apache-2.0","repository":{"type":"git","url":"git://github.com/strongloop/strong-log-transformer"},"keywords":["logging","streams"],"bugs":{"url":"https://github.com/strongloop/strong-log-transformer/issues"},"homepage":"https://github.com/strongloop/strong-log-transformer","directories":{"test":"test"},"bin":{"sl-log-transformer":"bin/sl-log-transformer.js"},"main":"index.js","scripts":{"test":"tap --100 test/test-*"},"dependencies":{"byline":"^5.0.0","duplexer":"^0.1.1","minimist":"^1.2.0","through":"^2.3.4"},"devDependencies":{"tap":"^12.0.1"},"engines":{"node":">=4"}}; + parent.nodes.push(node); + define(node, 'parent', parent); + }); -/***/ }), -/* 214 */ -/***/ (function(module, exports, __webpack_require__) { + return this; + }, -"use strict"; + /** + * Capture end-of-string + */ + eos: function() { + var pos = this.position(); + if (this.input) return; + var prev = this.prev(); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.CleanCommand = undefined; + while (prev.type !== 'root' && !prev.visited) { + if (this.options.strict === true) { + throw new SyntaxError('invalid syntax:' + util.inspect(prev, null, 2)); + } -var _chalk = __webpack_require__(30); + if (!hasDelims(prev)) { + prev.parent.escaped = true; + prev.escaped = true; + } -var _chalk2 = _interopRequireDefault(_chalk); + visit(prev, function(node) { + if (!hasDelims(node.parent)) { + node.parent.escaped = true; + node.escaped = true; + } + }); -var _del = __webpack_require__(113); + prev = prev.parent; + } -var _del2 = _interopRequireDefault(_del); + var tok = pos({ + type: 'eos', + val: this.append || '' + }); -var _ora = __webpack_require__(225); + define(tok, 'parent', this.ast); + return tok; + }, -var _ora2 = _interopRequireDefault(_ora); + /** + * Run parsers to advance the cursor position + */ -var _path = __webpack_require__(7); + next: function() { + var parsed = this.parsed; + var len = this.types.length; + var idx = -1; + var tok; + + while (++idx < len) { + if ((tok = this.parsers[this.types[idx]].call(this))) { + define(tok, 'rest', this.input); + define(tok, 'parsed', parsed); + this.last = tok; + return tok; + } + } + }, -var _fs = __webpack_require__(60); + /** + * Parse the given string. + * @return {Array} + */ -var _log = __webpack_require__(36); + parse: function(input) { + if (typeof input !== 'string') { + throw new TypeError('expected a string'); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + this.init(this.options); + this.orig = input; + this.input = input; + var self = this; -function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ + function parse() { + // check input before calling `.next()` + input = self.input; + + // get the next AST ndoe + var node = self.next(); + if (node) { + var prev = self.prev(); + if (prev) { + define(node, 'parent', prev); + if (prev.nodes) { + prev.nodes.push(node); + } + } + if (self.sets.hasOwnProperty(prev.type)) { + self.currentType = prev.type; + } + } -const CleanCommand = exports.CleanCommand = { - description: 'Remove the node_modules and target directories from all projects.', - name: 'clean', - run(projects) { - return _asyncToGenerator(function* () { - const toDelete = []; - for (const project of projects.values()) { - if (yield (0, _fs.isDirectory)(project.nodeModulesLocation)) { - toDelete.push({ - cwd: project.path, - pattern: (0, _path.relative)(project.path, project.nodeModulesLocation) - }); - } - if (yield (0, _fs.isDirectory)(project.targetLocation)) { - toDelete.push({ - cwd: project.path, - pattern: (0, _path.relative)(project.path, project.targetLocation) - }); - } - const { extraPatterns } = project.getCleanConfig(); - if (extraPatterns) { - toDelete.push({ - cwd: project.path, - pattern: extraPatterns - }); - } - } - if (toDelete.length === 0) { - _log.log.write(_chalk2.default.bold.green('\n\nNothing to delete')); - } else { - _log.log.write(_chalk2.default.bold.red('\n\nDeleting:\n')); - /** - * In order to avoid patterns like `/build` in packages from accidentally - * impacting files outside the package we use `process.chdir()` to change - * the cwd to the package and execute `del()` without the `force` option - * so it will check that each file being deleted is within the package. - * - * `del()` does support a `cwd` option, but it's only for resolving the - * patterns and does not impact the cwd check. - */ - const originalCwd = process.cwd(); - try { - for (const _ref of toDelete) { - const { pattern, cwd } = _ref; + // if we got here but input is not changed, throw an error + if (self.input && input === self.input) { + throw new Error('no parsers registered for: "' + self.input.slice(0, 5) + '"'); + } + } - process.chdir(cwd); - const promise = (0, _del2.default)(pattern); - _ora2.default.promise(promise, (0, _path.relative)(originalCwd, (0, _path.join)(cwd, String(pattern)))); - yield promise; - } - } finally { - process.chdir(originalCwd); - } - } - })(); + while (this.input) parse(); + if (this.stack.length && this.options.strict) { + var node = this.stack.pop(); + throw this.error('missing opening ' + node.type + ': "' + this.orig + '"'); } -}; -/***/ }), -/* 215 */ -/***/ (function(module, exports, __webpack_require__) { + var eos = this.eos(); + var tok = this.prev(); + if (tok.type !== 'eos') { + this.ast.nodes.push(eos); + } -"use strict"; + return this.ast; + } +}; -var Promise = __webpack_require__(114); -var arrayUnion = __webpack_require__(115); -var objectAssign = __webpack_require__(116); -var glob = __webpack_require__(43); -var pify = __webpack_require__(218); +/** + * Visit `node` with the given `fn` + */ -var globP = pify(glob, Promise).bind(glob); +function visit(node, fn) { + if (!node.visited) { + define(node, 'visited', true); + return node.nodes ? mapVisit(node.nodes, fn) : fn(node); + } + return node; +} -function isNegative(pattern) { - return pattern[0] === '!'; +/** + * Map visit over array of `nodes`. + */ + +function mapVisit(nodes, fn) { + var len = nodes.length; + var idx = -1; + while (++idx < len) { + visit(nodes[idx], fn); + } } -function isString(value) { - return typeof value === 'string'; +function hasOpen(node) { + return node.nodes && node.nodes[0].type === (node.type + '.open'); } -function assertPatternsInput(patterns) { - if (!patterns.every(isString)) { - throw new TypeError('patterns must be a string or an array of strings'); - } +function hasClose(node) { + return node.nodes && utils.last(node.nodes).type === (node.type + '.close'); } -function generateGlobTasks(patterns, opts) { - patterns = [].concat(patterns); - assertPatternsInput(patterns); +function hasDelims(node) { + return hasOpen(node) && hasClose(node); +} - var globTasks = []; +/** + * Expose `Parser` + */ - opts = objectAssign({ - cache: Object.create(null), - statCache: Object.create(null), - realpathCache: Object.create(null), - symlinks: Object.create(null), - ignore: [] - }, opts); +module.exports = Parser; - patterns.forEach(function (pattern, i) { - if (isNegative(pattern)) { - return; - } - var ignore = patterns.slice(i).filter(isNegative).map(function (pattern) { - return pattern.slice(1); - }); +/***/ }), +/* 409 */ +/***/ (function(module, exports, __webpack_require__) { - globTasks.push({ - pattern: pattern, - opts: objectAssign({}, opts, { - ignore: opts.ignore.concat(ignore) - }) - }); - }); +"use strict"; - return globTasks; -} -module.exports = function (patterns, opts) { - var globTasks; +var define = __webpack_require__(67); - try { - globTasks = generateGlobTasks(patterns, opts); - } catch (err) { - return Promise.reject(err); - } +/** + * Store position for a node + */ - return Promise.all(globTasks.map(function (task) { - return globP(task.pattern, task.opts); - })).then(function (paths) { - return arrayUnion.apply(null, paths); - }); +module.exports = function Position(start, parser) { + this.start = start; + this.end = { line: parser.line, column: parser.column }; + define(this, 'content', parser.orig); + define(this, 'source', parser.options.source); }; -module.exports.sync = function (patterns, opts) { - var globTasks = generateGlobTasks(patterns, opts); - return globTasks.reduce(function (matches, task) { - return arrayUnion(matches, glob.sync(task.pattern, task.opts)); - }, []); -}; +/***/ }), +/* 410 */ +/***/ (function(module, exports, __webpack_require__) { -module.exports.generateGlobTasks = generateGlobTasks; +"use strict"; -module.exports.hasMagic = function (patterns, opts) { - return [].concat(patterns).some(function (pattern) { - return glob.hasMagic(pattern, opts); - }); + +var nanomatch = __webpack_require__(149); +var extglob = __webpack_require__(152); + +module.exports = function(snapdragon) { + var compilers = snapdragon.compiler.compilers; + var opts = snapdragon.options; + + // register nanomatch compilers + snapdragon.use(nanomatch.compilers); + + // get references to some specific nanomatch compilers before they + // are overridden by the extglob and/or custom compilers + var escape = compilers.escape; + var qmark = compilers.qmark; + var slash = compilers.slash; + var star = compilers.star; + var text = compilers.text; + var plus = compilers.plus; + var dot = compilers.dot; + + // register extglob compilers or escape exglobs if disabled + if (opts.extglob === false || opts.noext === true) { + snapdragon.compiler.use(escapeExtglobs); + } else { + snapdragon.use(extglob.compilers); + } + + snapdragon.use(function() { + this.options.star = this.options.star || function(/*node*/) { + return '[^/]*?'; + }; + }); + + // custom micromatch compilers + snapdragon.compiler + + // reset referenced compiler + .set('dot', dot) + .set('escape', escape) + .set('plus', plus) + .set('slash', slash) + .set('qmark', qmark) + .set('star', star) + .set('text', text); }; +function escapeExtglobs(compiler) { + compiler.set('paren', function(node) { + var val = ''; + visit(node, function(tok) { + if (tok.val) val += '\\' + tok.val; + }); + return this.emit(val, node); + }); + + /** + * Visit `node` with the given `fn` + */ + + function visit(node, fn) { + return node.nodes ? mapVisit(node.nodes, fn) : fn(node); + } + + /** + * Map visit over array of `nodes`. + */ + + function mapVisit(nodes, fn) { + var len = nodes.length; + var idx = -1; + while (++idx < len) { + visit(nodes[idx], fn); + } + } +} + /***/ }), -/* 216 */ +/* 411 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var PENDING = 'pending'; -var SETTLED = 'settled'; -var FULFILLED = 'fulfilled'; -var REJECTED = 'rejected'; -var NOOP = function () {}; -var isNode = typeof global !== 'undefined' && typeof global.process !== 'undefined' && typeof global.process.emit === 'function'; +/** + * Nanomatch compilers + */ -var asyncSetTimer = typeof setImmediate === 'undefined' ? setTimeout : setImmediate; -var asyncQueue = []; -var asyncTimer; +module.exports = function(nanomatch, options) { + var star = '[^/]*?'; -function asyncFlush() { - // run promise callbacks - for (var i = 0; i < asyncQueue.length; i++) { - asyncQueue[i][0](asyncQueue[i][1]); - } + var ast = nanomatch.ast = nanomatch.parser.ast; + ast.state = nanomatch.parser.state; + nanomatch.compiler.state = ast.state; + nanomatch.compiler - // reset async asyncQueue - asyncQueue = []; - asyncTimer = false; -} + /** + * Negation / escaping + */ -function asyncCall(callback, arg) { - asyncQueue.push([callback, arg]); + .set('not', function(node) { + var prev = this.prev(); + if (this.options.nonegate === true || prev.type !== 'bos') { + return this.emit('\\' + node.val, node); + } + return this.emit(node.val, node); + }) + .set('escape', function(node) { + if (this.options.unescape && /^[\w_.-]/.test(node.val)) { + return this.emit(node.val, node); + } + return this.emit('\\' + node.val, node); + }) + .set('quoted', function(node) { + return this.emit(node.val, node); + }) - if (!asyncTimer) { - asyncTimer = true; - asyncSetTimer(asyncFlush, 0); - } -} + /** + * Regex + */ -function invokeResolver(resolver, promise) { - function resolvePromise(value) { - resolve(promise, value); - } + .set('dollar', function(node) { + if (node.parent.type === 'bracket') { + return this.emit(node.val, node); + } + return this.emit('\\' + node.val, node); + }) - function rejectPromise(reason) { - reject(promise, reason); - } + /** + * Dot: "." + */ - try { - resolver(resolvePromise, rejectPromise); - } catch (e) { - rejectPromise(e); - } -} + .set('dot', function(node) { + if (node.dotfiles === true) this.dotfiles = true; + return this.emit('\\' + node.val, node); + }) -function invokeCallback(subscriber) { - var owner = subscriber.owner; - var settled = owner._state; - var value = owner._data; - var callback = subscriber[settled]; - var promise = subscriber.then; + /** + * Slashes: "/" and "\" + */ - if (typeof callback === 'function') { - settled = FULFILLED; - try { - value = callback(value); - } catch (e) { - reject(promise, e); - } - } + .set('backslash', function(node) { + return this.emit(node.val, node); + }) + .set('slash', function(node, nodes, i) { + var val = '\\' + node.val; + var parent = node.parent; + var prev = this.prev(); + + // set "node.hasSlash" to true on all ancestor parens nodes + while (parent.type === 'paren' && !parent.hasSlash) { + parent.hasSlash = true; + parent = parent.parent; + } - if (!handleThenable(promise, value)) { - if (settled === FULFILLED) { - resolve(promise, value); - } + if (prev.addQmark) { + val += '?'; + } - if (settled === REJECTED) { - reject(promise, value); - } - } -} + // word boundary + if (node.rest.slice(0, 2) === '\\b') { + return this.emit(val, node); + } -function handleThenable(promise, value) { - var resolved; + // globstars + if (node.parsed === '**' || node.parsed === './**') { + this.output = '(?:' + this.output; + return this.emit(val + ')?', node); + } - try { - if (promise === value) { - throw new TypeError('A promises callback cannot return that same promise.'); - } + // negation + if (node.parsed === '!**' && this.options.nonegate !== true) { + return this.emit(val + '?\\b', node); + } + return this.emit(val, node); + }) - if (value && (typeof value === 'function' || typeof value === 'object')) { - // then should be retrieved only once - var then = value.then; + /** + * Square brackets + */ - if (typeof then === 'function') { - then.call(value, function (val) { - if (!resolved) { - resolved = true; + .set('bracket', function(node) { + var close = node.close; + var open = !node.escaped ? '[' : '\\['; + var negated = node.negated; + var inner = node.inner; + var val = node.val; - if (value === val) { - fulfill(promise, val); - } else { - resolve(promise, val); - } - } - }, function (reason) { - if (!resolved) { - resolved = true; + if (node.escaped === true) { + inner = inner.replace(/\\?(\W)/g, '\\$1'); + negated = ''; + } - reject(promise, reason); - } - }); + if (inner === ']-') { + inner = '\\]\\-'; + } - return true; - } - } - } catch (e) { - if (!resolved) { - reject(promise, e); - } + if (negated && inner.indexOf('.') === -1) { + inner += '.'; + } + if (negated && inner.indexOf('/') === -1) { + inner += '/'; + } - return true; - } + val = open + negated + inner + close; + return this.emit(val, node); + }) - return false; -} + /** + * Square: "[.]" (only matches a single character in brackets) + */ -function resolve(promise, value) { - if (promise === value || !handleThenable(promise, value)) { - fulfill(promise, value); - } -} + .set('square', function(node) { + var val = !/^\w/.test(node.val) ? '\\' + node.val : node.val; + return this.emit(val, node); + }) -function fulfill(promise, value) { - if (promise._state === PENDING) { - promise._state = SETTLED; - promise._data = value; + /** + * Question mark: "?" + */ - asyncCall(publishFulfillment, promise); - } -} + .set('qmark', function(node) { + var prev = this.prev(); + var val = '[^.\\\\/]'; + if (this.options.dot || (prev.type !== 'bos' && prev.type !== 'slash')) { + val = '[^\\\\/]'; + } -function reject(promise, reason) { - if (promise._state === PENDING) { - promise._state = SETTLED; - promise._data = reason; + if (node.parsed.slice(-1) === '(') { + var ch = node.rest.charAt(0); + if (ch === '!' || ch === '=' || ch === ':') { + return this.emit(node.val, node); + } + } - asyncCall(publishRejection, promise); - } -} + if (node.val.length > 1) { + val += '{' + node.val.length + '}'; + } + return this.emit(val, node); + }) -function publish(promise) { - promise._then = promise._then.forEach(invokeCallback); -} + /** + * Plus + */ -function publishFulfillment(promise) { - promise._state = FULFILLED; - publish(promise); -} + .set('plus', function(node) { + var prev = node.parsed.slice(-1); + if (prev === ']' || prev === ')') { + return this.emit(node.val, node); + } + if (!this.output || (/[?*+]/.test(ch) && node.parent.type !== 'bracket')) { + return this.emit('\\+', node); + } + var ch = this.output.slice(-1); + if (/\w/.test(ch) && !node.inside) { + return this.emit('+\\+?', node); + } + return this.emit('+', node); + }) -function publishRejection(promise) { - promise._state = REJECTED; - publish(promise); - if (!promise._handled && isNode) { - global.process.emit('unhandledRejection', promise._data, promise); - } -} + /** + * globstar: '**' + */ -function notifyRejectionHandled(promise) { - global.process.emit('rejectionHandled', promise); -} + .set('globstar', function(node, nodes, i) { + if (!this.output) { + this.state.leadingGlobstar = true; + } -/** - * @class - */ -function Promise(resolver) { - if (typeof resolver !== 'function') { - throw new TypeError('Promise resolver ' + resolver + ' is not a function'); - } + var next = this.next(); + var prev = this.prev(); + var next2 = this.next(2); + var prev2 = this.prev(2); + var type = prev.type; + var val = node.val; + + if (prev.type === 'slash' && next.type === 'slash') { + if (prev2.type === 'text') { + this.output += '?'; + + if (next2.type !== 'text') { + this.output += '\\b'; + } + } + } + + var parsed = node.parsed; + if (parsed.charAt(0) === '!') { + parsed = parsed.slice(1); + } + + var isInside = node.isInside.paren || node.isInside.brace; + if (parsed && type !== 'slash' && type !== 'bos' && !isInside) { + val = star; + } else { + val = this.options.dot !== true + ? '(?:(?!(?:\\/|^)\\.).)*?' + : '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/))(?!\\.{2}).)*?'; + } - if (this instanceof Promise === false) { - throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.'); - } + if ((type === 'slash' || type === 'bos') && this.options.dot !== true) { + val = '(?!\\.)' + val; + } - this._then = []; + if (prev.type === 'slash' && next.type === 'slash' && prev2.type !== 'text') { + if (next2.type === 'text' || next2.type === 'star') { + node.addQmark = true; + } + } - invokeResolver(resolver, this); -} + if (this.options.capture) { + val = '(' + val + ')'; + } -Promise.prototype = { - constructor: Promise, + return this.emit(val, node); + }) - _state: PENDING, - _then: null, - _data: undefined, - _handled: false, + /** + * Star: "*" + */ - then: function (onFulfillment, onRejection) { - var subscriber = { - owner: this, - then: new this.constructor(NOOP), - fulfilled: onFulfillment, - rejected: onRejection - }; + .set('star', function(node, nodes, i) { + var prior = nodes[i - 2] || {}; + var prev = this.prev(); + var next = this.next(); + var type = prev.type; - if ((onRejection || onFulfillment) && !this._handled) { - this._handled = true; - if (this._state === REJECTED && isNode) { - asyncCall(notifyRejectionHandled, this); - } - } + function isStart(n) { + return n.type === 'bos' || n.type === 'slash'; + } - if (this._state === FULFILLED || this._state === REJECTED) { - // already resolved, call callback async - asyncCall(invokeCallback, subscriber); - } else { - // subscribe - this._then.push(subscriber); - } + if (this.output === '' && this.options.contains !== true) { + this.output = '(?!\\/)'; + } - return subscriber.then; - }, + if (type === 'bracket' && this.options.bash === false) { + var str = next && next.type === 'bracket' ? star : '*?'; + if (!prev.nodes || prev.nodes[1].type !== 'posix') { + return this.emit(str, node); + } + } - catch: function (onRejection) { - return this.then(null, onRejection); - } -}; + var prefix = !this.dotfiles && type !== 'text' && type !== 'escape' + ? (this.options.dot ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))' : '(?!\\.)') + : ''; -Promise.all = function (promises) { - if (!Array.isArray(promises)) { - throw new TypeError('You must pass an array to Promise.all().'); - } + if (isStart(prev) || (isStart(prior) && type === 'not')) { + if (prefix !== '(?!\\.)') { + prefix += '(?!(\\.{2}|\\.\\/))(?=.)'; + } else { + prefix += '(?=.)'; + } + } else if (prefix === '(?!\\.)') { + prefix = ''; + } - return new Promise(function (resolve, reject) { - var results = []; - var remaining = 0; + if (prev.type === 'not' && prior.type === 'bos' && this.options.dot === true) { + this.output = '(?!\\.)' + this.output; + } - function resolver(index) { - remaining++; - return function (value) { - results[index] = value; - if (!--remaining) { - resolve(results); - } - }; - } + var output = prefix + star; + if (this.options.capture) { + output = '(' + output + ')'; + } - for (var i = 0, promise; i < promises.length; i++) { - promise = promises[i]; + return this.emit(output, node); + }) - if (promise && typeof promise.then === 'function') { - promise.then(resolver(i), reject); - } else { - results[i] = promise; - } - } + /** + * Text + */ - if (!remaining) { - resolve(results); - } - }); -}; + .set('text', function(node) { + return this.emit(node.val, node); + }) -Promise.race = function (promises) { - if (!Array.isArray(promises)) { - throw new TypeError('You must pass an array to Promise.race().'); - } + /** + * End-of-string + */ - return new Promise(function (resolve, reject) { - for (var i = 0, promise; i < promises.length; i++) { - promise = promises[i]; + .set('eos', function(node) { + var prev = this.prev(); + var val = node.val; - if (promise && typeof promise.then === 'function') { - promise.then(resolve, reject); - } else { - resolve(promise); - } - } - }); -}; + this.output = '(?:(?:\\.(?:\\/|\\\\))(?=.))?' + this.output; + if (this.state.metachar && prev.type !== 'qmark' && prev.type !== 'slash') { + val += (this.options.contains ? '(?:\\/|\\\\)?' : '(?:(?:\\/|\\\\)|$)'); + } -Promise.resolve = function (value) { - if (value && typeof value === 'object' && value.constructor === Promise) { - return value; - } + return this.emit(val, node); + }); - return new Promise(function (resolve) { - resolve(value); - }); -}; + /** + * Allow custom compilers to be passed on options + */ -Promise.reject = function (reason) { - return new Promise(function (resolve, reject) { - reject(reason); - }); + if (options && typeof options.compilers === 'function') { + options.compilers(nanomatch.compiler); + } }; -module.exports = Promise; /***/ }), -/* 217 */ +/* 412 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -// there's 3 implementations written in increasing order of efficiency +var regexNot = __webpack_require__(64); +var toRegex = __webpack_require__(43); +var isOdd = __webpack_require__(413); -// 1 - no Set type is defined -function uniqNoSet(arr) { - var ret = []; +/** + * Characters to use in negation regex (we want to "not" match + * characters that are matched by other parsers) + */ - for (var i = 0; i < arr.length; i++) { - if (ret.indexOf(arr[i]) === -1) { - ret.push(arr[i]); - } - } +var cached; +var NOT_REGEX = '[!*+?$^"\'.\\\\/\\[]+'; +var not = createTextRegex(NOT_REGEX); - return ret; -} +/** + * Nanomatch parsers + */ -// 2 - a simple Set type is defined -function uniqSet(arr) { - var seen = new Set(); - return arr.filter(function (el) { - if (!seen.has(el)) { - seen.add(el); - return true; - } +module.exports = function(nanomatch, options) { + var parser = nanomatch.parser; + var opts = parser.options; - return false; - }); -} + parser.state = { + slashes: 0, + paths: [] + }; -// 3 - a standard Set type is defined and it has a forEach method -function uniqSetWithForEach(arr) { - var ret = []; + parser.ast.state = parser.state; + parser - (new Set(arr)).forEach(function (el) { - ret.push(el); - }); + /** + * Beginning-of-string + */ - return ret; -} + .capture('prefix', function() { + if (this.parsed) return; + var pos = this.position(); + var m = this.match(/^\.[\\/]/); + if (!m) return; + this.state.strictOpen = !!this.options.strictOpen; + this.state.addPrefix = true; + }) -// V8 currently has a broken implementation -// https://github.com/joyent/node/issues/8449 -function doesForEachActuallyWork() { - var ret = false; + /** + * Escape: "\\." + */ - (new Set([true])).forEach(function (el) { - ret = el; - }); + .capture('escape', function() { + if (this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(/^(?:\\(.)|([$^]))/); + if (!m) return; - return ret === true; -} + return pos({ + type: 'escape', + val: m[2] || m[1] + }); + }) -if ('Set' in global) { - if (typeof Set.prototype.forEach === 'function' && doesForEachActuallyWork()) { - module.exports = uniqSetWithForEach; - } else { - module.exports = uniqSet; - } -} else { - module.exports = uniqNoSet; -} + /** + * Quoted strings + */ + .capture('quoted', function() { + var pos = this.position(); + var m = this.match(/^["']/); + if (!m) return; -/***/ }), -/* 218 */ -/***/ (function(module, exports, __webpack_require__) { + var quote = m[0]; + if (this.input.indexOf(quote) === -1) { + return pos({ + type: 'escape', + val: quote + }); + } -"use strict"; + var tok = advanceTo(this.input, quote); + this.consume(tok.len); + return pos({ + type: 'quoted', + val: tok.esc + }); + }) -var processFn = function (fn, P, opts) { - return function () { - var that = this; - var args = new Array(arguments.length); + /** + * Negations: "!" + */ - for (var i = 0; i < arguments.length; i++) { - args[i] = arguments[i]; - } + .capture('not', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(this.notRegex || /^\!+/); + if (!m) return; + var val = m[0]; - return new P(function (resolve, reject) { - args.push(function (err, result) { - if (err) { - reject(err); - } else if (opts.multiArgs) { - var results = new Array(arguments.length - 1); + var isNegated = isOdd(val.length); + if (parsed === '' && !isNegated) { + val = ''; + } - for (var i = 1; i < arguments.length; i++) { - results[i - 1] = arguments[i]; - } + // if nothing has been parsed, we know `!` is at the start, + // so we need to wrap the result in a negation regex + if (parsed === '' && isNegated && this.options.nonegate !== true) { + this.bos.val = '(?!^(?:'; + this.append = ')$).*'; + val = ''; + } + return pos({ + type: 'not', + val: val + }); + }) - resolve(results); - } else { - resolve(result); - } - }); + /** + * Dot: "." + */ - fn.apply(that, args); - }); - }; -}; + .capture('dot', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\.+/); + if (!m) return; -var pify = module.exports = function (obj, P, opts) { - if (typeof P !== 'function') { - opts = P; - P = Promise; - } + var val = m[0]; + this.state.dot = val === '.' && (parsed === '' || parsed.slice(-1) === '/'); - opts = opts || {}; - opts.exclude = opts.exclude || [/.+Sync$/]; + return pos({ + type: 'dot', + dotfiles: this.state.dot, + val: val + }); + }) - var filter = function (key) { - var match = function (pattern) { - return typeof pattern === 'string' ? key === pattern : pattern.test(key); - }; + /** + * Plus: "+" + */ - return opts.include ? opts.include.some(match) : !opts.exclude.some(match); - }; + .capture('plus', /^\+(?!\()/) - var ret = typeof obj === 'function' ? function () { - if (opts.excludeMain) { - return obj.apply(this, arguments); - } + /** + * Question mark: "?" + */ - return processFn(obj, P, opts).apply(this, arguments); - } : {}; + .capture('qmark', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\?+(?!\()/); + if (!m) return; - return Object.keys(obj).reduce(function (ret, key) { - var x = obj[key]; + this.state.metachar = true; + this.state.qmark = true; - ret[key] = typeof x === 'function' && filter(key) ? processFn(x, P, opts) : x; + return pos({ + type: 'qmark', + parsed: parsed, + val: m[0] + }); + }) - return ret; - }, ret); -}; + /** + * Globstar: "**" + */ -pify.all = pify; + .capture('globstar', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\*{2}(?![*(])(?=[,\/)]|$)/); + if (!m) return; + var type = opts.noglobstar !== true ? 'globstar' : 'star'; + var node = pos({type: type, parsed: parsed}); -/***/ }), -/* 219 */ -/***/ (function(module, exports, __webpack_require__) { + while (this.input.slice(0, 4) === '/**/') { + this.input = this.input.slice(3); + } -"use strict"; + node.isInside = { + brace: this.isInside('brace'), + paren: this.isInside('paren') + }; -var path = __webpack_require__(7); + if (type === 'globstar') { + this.state.globstar = true; + node.val = '**'; -module.exports = function (str) { - return path.resolve(str) === path.resolve(process.cwd()); -}; + } else { + this.state.star = true; + node.val = '*'; + } + this.state.metachar = true; + return node; + }) -/***/ }), -/* 220 */ -/***/ (function(module, exports, __webpack_require__) { + /** + * Star: "*" + */ -"use strict"; + .capture('star', function() { + var pos = this.position(); + var starRe = /^(?:\*(?![*(])|[*]{3,}(?!\()|[*]{2}(?![(\/]|$)|\*(?=\*\())/; + var m = this.match(starRe); + if (!m) return; + + this.state.metachar = true; + this.state.star = true; + return pos({ + type: 'star', + val: m[0] + }); + }) -var isPathInside = __webpack_require__(221); + /** + * Slash: "/" + */ -module.exports = function (str) { - return isPathInside(str, process.cwd()); -}; + .capture('slash', function() { + var pos = this.position(); + var m = this.match(/^\//); + if (!m) return; + this.state.slashes++; + return pos({ + type: 'slash', + val: m[0] + }); + }) -/***/ }), -/* 221 */ -/***/ (function(module, exports, __webpack_require__) { + /** + * Backslash: "\\" + */ -"use strict"; + .capture('backslash', function() { + var pos = this.position(); + var m = this.match(/^\\(?![*+?(){}[\]'"])/); + if (!m) return; -var path = __webpack_require__(7); -var pathIsInside = __webpack_require__(222); + var val = m[0]; -module.exports = function (a, b) { - a = path.resolve(a); - b = path.resolve(b); + if (this.isInside('bracket')) { + val = '\\'; + } else if (val.length > 1) { + val = '\\\\'; + } - if (a === b) { - return false; - } + return pos({ + type: 'backslash', + val: val + }); + }) - return pathIsInside(a, b); -}; + /** + * Square: "[.]" + */ + .capture('square', function() { + if (this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(/^\[([^!^\\])\]/); + if (!m) return; -/***/ }), -/* 222 */ -/***/ (function(module, exports, __webpack_require__) { + return pos({ + type: 'square', + val: m[1] + }); + }) -"use strict"; + /** + * Brackets: "[...]" (basic, this can be overridden by other parsers) + */ + .capture('bracket', function() { + var pos = this.position(); + var m = this.match(/^(?:\[([!^]?)([^\]]+|\]\-)(\]|[^*+?]+)|\[)/); + if (!m) return; -var path = __webpack_require__(7); + var val = m[0]; + var negated = m[1] ? '^' : ''; + var inner = (m[2] || '').replace(/\\\\+/, '\\\\'); + var close = m[3] || ''; -module.exports = function (thePath, potentialParent) { - // For inside-directory checking, we want to allow trailing slashes, so normalize. - thePath = stripTrailingSep(thePath); - potentialParent = stripTrailingSep(potentialParent); + if (m[2] && inner.length < m[2].length) { + val = val.replace(/\\\\+/, '\\\\'); + } - // Node treats only Windows as case-insensitive in its path module; we follow those conventions. - if (process.platform === "win32") { - thePath = thePath.toLowerCase(); - potentialParent = potentialParent.toLowerCase(); - } + var esc = this.input.slice(0, 2); + if (inner === '' && esc === '\\]') { + inner += esc; + this.consume(2); - return thePath.lastIndexOf(potentialParent, 0) === 0 && - ( - thePath[potentialParent.length] === path.sep || - thePath[potentialParent.length] === undefined - ); + var str = this.input; + var idx = -1; + var ch; + + while ((ch = str[++idx])) { + this.consume(1); + if (ch === ']') { + close = ch; + break; + } + inner += ch; + } + } + + return pos({ + type: 'bracket', + val: val, + escaped: close !== ']', + negated: negated, + inner: inner, + close: close + }); + }) + + /** + * Text + */ + + .capture('text', function() { + if (this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(not); + if (!m || !m[0]) return; + + return pos({ + type: 'text', + val: m[0] + }); + }); + + /** + * Allow custom parsers to be passed on options + */ + + if (options && typeof options.parsers === 'function') { + options.parsers(nanomatch.parser); + } }; -function stripTrailingSep(thePath) { - if (thePath[thePath.length - 1] === path.sep) { - return thePath.slice(0, -1); +/** + * Advance to the next non-escaped character + */ + +function advanceTo(input, endChar) { + var ch = input.charAt(0); + var tok = { len: 1, val: '', esc: '' }; + var idx = 0; + + function advance() { + if (ch !== '\\') { + tok.esc += '\\' + ch; + tok.val += ch; } - return thePath; -} + ch = input.charAt(++idx); + tok.len++; -/***/ }), -/* 223 */ -/***/ (function(module, exports, __webpack_require__) { + if (ch === '\\') { + advance(); + advance(); + } + } -module.exports = rimraf -rimraf.sync = rimrafSync + while (ch && ch !== endChar) { + advance(); + } + return tok; +} -var assert = __webpack_require__(57) -var path = __webpack_require__(7) -var fs = __webpack_require__(16) -var glob = __webpack_require__(43) -var _0666 = parseInt('666', 8) +/** + * Create text regex + */ -var defaultGlobOpts = { - nosort: true, - silent: true +function createTextRegex(pattern) { + if (cached) return cached; + var opts = {contains: true, strictClose: false}; + var not = regexNot.create(pattern, opts); + var re = toRegex('^(?:[*]\\(|' + not + ')', opts); + return (cached = re); } -// for EMFILE handling -var timeout = 0 +/** + * Expose negation string + */ -var isWindows = (process.platform === "win32") +module.exports.not = NOT_REGEX; -function defaults (options) { - var methods = [ - 'unlink', - 'chmod', - 'stat', - 'lstat', - 'rmdir', - 'readdir' - ] - methods.forEach(function(m) { - options[m] = options[m] || fs[m] - m = m + 'Sync' - options[m] = options[m] || fs[m] - }) - options.maxBusyTries = options.maxBusyTries || 3 - options.emfileWait = options.emfileWait || 1000 - if (options.glob === false) { - options.disableGlob = true - } - options.disableGlob = options.disableGlob || false - options.glob = options.glob || defaultGlobOpts -} +/***/ }), +/* 413 */ +/***/ (function(module, exports, __webpack_require__) { -function rimraf (p, options, cb) { - if (typeof options === 'function') { - cb = options - options = {} +"use strict"; +/*! + * is-odd + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ + + + +var isNumber = __webpack_require__(77); + +module.exports = function isOdd(i) { + if (!isNumber(i)) { + throw new TypeError('is-odd expects a number.'); + } + if (Number(i) !== Math.floor(i)) { + throw new RangeError('is-odd expects an integer.'); } + return !!(~~i & 1); +}; - assert(p, 'rimraf: missing path') - assert.equal(typeof p, 'string', 'rimraf: path should be a string') - assert.equal(typeof cb, 'function', 'rimraf: callback function required') - assert(options, 'rimraf: invalid options argument provided') - assert.equal(typeof options, 'object', 'rimraf: options should be object') - defaults(options) +/***/ }), +/* 414 */ +/***/ (function(module, exports, __webpack_require__) { - var busyTries = 0 - var errState = null - var n = 0 +module.exports = new (__webpack_require__(107))(); - if (options.disableGlob || !glob.hasMagic(p)) - return afterGlob(null, [p]) - options.lstat(p, function (er, stat) { - if (!er) - return afterGlob(null, [p]) +/***/ }), +/* 415 */ +/***/ (function(module, exports, __webpack_require__) { - glob(p, options.glob, afterGlob) - }) +"use strict"; - function next (er) { - errState = errState || er - if (--n === 0) - cb(errState) - } - function afterGlob (er, results) { - if (er) - return cb(er) +var utils = module.exports; +var path = __webpack_require__(5); - n = results.length - if (n === 0) - return cb() +/** + * Module dependencies + */ - results.forEach(function (p) { - rimraf_(p, options, function CB (er) { - if (er) { - if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && - busyTries < options.maxBusyTries) { - busyTries ++ - var time = busyTries * 100 - // try again, with the same exact callback as this one. - return setTimeout(function () { - rimraf_(p, options, CB) - }, time) - } +var Snapdragon = __webpack_require__(66); +utils.define = __webpack_require__(44); +utils.diff = __webpack_require__(150); +utils.extend = __webpack_require__(20); +utils.pick = __webpack_require__(151); +utils.typeOf = __webpack_require__(416); +utils.unique = __webpack_require__(65); - // this one won't happen if graceful-fs is used. - if (er.code === "EMFILE" && timeout < options.emfileWait) { - return setTimeout(function () { - rimraf_(p, options, CB) - }, timeout ++) - } +/** + * Returns true if the given value is effectively an empty string + */ - // already gone - if (er.code === "ENOENT") er = null - } +utils.isEmptyString = function(val) { + return String(val) === '' || String(val) === './'; +}; - timeout = 0 - next(er) - }) - }) - } -} +/** + * Returns true if the platform is windows, or `path.sep` is `\\`. + * This is defined as a function to allow `path.sep` to be set in unit tests, + * or by the user, if there is a reason to do so. + * @return {Boolean} + */ -// Two possible strategies. -// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR -// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR -// -// Both result in an extra syscall when you guess wrong. However, there -// are likely far more normal files in the world than directories. This -// is based on the assumption that a the average number of files per -// directory is >= 1. -// -// If anyone ever complains about this, then I guess the strategy could -// be made configurable somehow. But until then, YAGNI. -function rimraf_ (p, options, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') +utils.isWindows = function() { + return path.sep === '\\' || process.platform === 'win32'; +}; - // sunos lets the root user unlink directories, which is... weird. - // so we have to lstat here and make sure it's not a dir. - options.lstat(p, function (er, st) { - if (er && er.code === "ENOENT") - return cb(null) +/** + * Return the last element from an array + */ + +utils.last = function(arr, n) { + return arr[arr.length - (n || 1)]; +}; + +/** + * Get the `Snapdragon` instance to use + */ - // Windows can EPERM on stat. Life is suffering. - if (er && er.code === "EPERM" && isWindows) - fixWinEPERM(p, options, er, cb) +utils.instantiate = function(ast, options) { + var snapdragon; + // if an instance was created by `.parse`, use that instance + if (utils.typeOf(ast) === 'object' && ast.snapdragon) { + snapdragon = ast.snapdragon; + // if the user supplies an instance on options, use that instance + } else if (utils.typeOf(options) === 'object' && options.snapdragon) { + snapdragon = options.snapdragon; + // create a new instance + } else { + snapdragon = new Snapdragon(options); + } - if (st && st.isDirectory()) - return rmdir(p, options, er, cb) + utils.define(snapdragon, 'parse', function(str, options) { + var parsed = Snapdragon.prototype.parse.apply(this, arguments); + parsed.input = str; - options.unlink(p, function (er) { - if (er) { - if (er.code === "ENOENT") - return cb(null) - if (er.code === "EPERM") - return (isWindows) - ? fixWinEPERM(p, options, er, cb) - : rmdir(p, options, er, cb) - if (er.code === "EISDIR") - return rmdir(p, options, er, cb) + // escape unmatched brace/bracket/parens + var last = this.parser.stack.pop(); + if (last && this.options.strictErrors !== true) { + var open = last.nodes[0]; + var inner = last.nodes[1]; + if (last.type === 'bracket') { + if (inner.val.charAt(0) === '[') { + inner.val = '\\' + inner.val; + } + + } else { + open.val = '\\' + open.val; + var sibling = open.parent.nodes[1]; + if (sibling.type === 'star') { + sibling.loose = true; + } } - return cb(er) - }) - }) -} + } -function fixWinEPERM (p, options, er, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - if (er) - assert(er instanceof Error) + // add non-enumerable parser reference + utils.define(parsed, 'parser', this.parser); + return parsed; + }); - options.chmod(p, _0666, function (er2) { - if (er2) - cb(er2.code === "ENOENT" ? null : er) - else - options.stat(p, function(er3, stats) { - if (er3) - cb(er3.code === "ENOENT" ? null : er) - else if (stats.isDirectory()) - rmdir(p, options, er, cb) - else - options.unlink(p, cb) - }) - }) -} + return snapdragon; +}; -function fixWinEPERMSync (p, options, er) { - assert(p) - assert(options) - if (er) - assert(er instanceof Error) +/** + * Create the key to use for memoization. The key is generated + * by iterating over the options and concatenating key-value pairs + * to the pattern string. + */ - try { - options.chmodSync(p, _0666) - } catch (er2) { - if (er2.code === "ENOENT") - return - else - throw er +utils.createKey = function(pattern, options) { + if (typeof options === 'undefined') { + return pattern; } - - try { - var stats = options.statSync(p) - } catch (er3) { - if (er3.code === "ENOENT") - return - else - throw er + var key = pattern; + for (var prop in options) { + if (options.hasOwnProperty(prop)) { + key += ';' + prop + '=' + String(options[prop]); + } } + return key; +}; - if (stats.isDirectory()) - rmdirSync(p, options, er) - else - options.unlinkSync(p) -} +/** + * Cast `val` to an array + * @return {Array} + */ -function rmdir (p, options, originalEr, cb) { - assert(p) - assert(options) - if (originalEr) - assert(originalEr instanceof Error) - assert(typeof cb === 'function') +utils.arrayify = function(val) { + if (typeof val === 'string') return [val]; + return val ? (Array.isArray(val) ? val : [val]) : []; +}; - // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) - // if we guessed wrong, and it's not a directory, then - // raise the original error. - options.rmdir(p, function (er) { - if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) - rmkids(p, options, cb) - else if (er && er.code === "ENOTDIR") - cb(originalEr) - else - cb(er) - }) -} +/** + * Return true if `val` is a non-empty string + */ -function rmkids(p, options, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') +utils.isString = function(val) { + return typeof val === 'string'; +}; - options.readdir(p, function (er, files) { - if (er) - return cb(er) - var n = files.length - if (n === 0) - return options.rmdir(p, cb) - var errState - files.forEach(function (f) { - rimraf(path.join(p, f), options, function (er) { - if (errState) - return - if (er) - return cb(errState = er) - if (--n === 0) - options.rmdir(p, cb) - }) - }) - }) -} +/** + * Return true if `val` is a non-empty string + */ -// this looks simpler, and is strictly *faster*, but will -// tie up the JavaScript thread and fail on excessively -// deep directory trees. -function rimrafSync (p, options) { - options = options || {} - defaults(options) +utils.isRegex = function(val) { + return utils.typeOf(val) === 'regexp'; +}; - assert(p, 'rimraf: missing path') - assert.equal(typeof p, 'string', 'rimraf: path should be a string') - assert(options, 'rimraf: missing options') - assert.equal(typeof options, 'object', 'rimraf: options should be object') +/** + * Return true if `val` is a non-empty string + */ - var results +utils.isObject = function(val) { + return utils.typeOf(val) === 'object'; +}; - if (options.disableGlob || !glob.hasMagic(p)) { - results = [p] - } else { - try { - options.lstatSync(p) - results = [p] - } catch (er) { - results = glob.sync(p, options.glob) - } - } +/** + * Escape regex characters in the given string + */ - if (!results.length) - return +utils.escapeRegex = function(str) { + return str.replace(/[-[\]{}()^$|*+?.\\\/\s]/g, '\\$&'); +}; - for (var i = 0; i < results.length; i++) { - var p = results[i] +/** + * Combines duplicate characters in the provided `input` string. + * @param {String} `input` + * @returns {String} + */ - try { - var st = options.lstatSync(p) - } catch (er) { - if (er.code === "ENOENT") - return +utils.combineDupes = function(input, patterns) { + patterns = utils.arrayify(patterns).join('|').split('|'); + patterns = patterns.map(function(s) { + return s.replace(/\\?([+*\\/])/g, '\\$1'); + }); + var substr = patterns.join('|'); + var regex = new RegExp('(' + substr + ')(?=\\1)', 'g'); + return input.replace(regex, ''); +}; - // Windows can EPERM on stat. Life is suffering. - if (er.code === "EPERM" && isWindows) - fixWinEPERMSync(p, options, er) - } +/** + * Returns true if the given `str` has special characters + */ - try { - // sunos lets the root user unlink directories, which is... weird. - if (st && st.isDirectory()) - rmdirSync(p, options, null) - else - options.unlinkSync(p) - } catch (er) { - if (er.code === "ENOENT") - return - if (er.code === "EPERM") - return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) - if (er.code !== "EISDIR") - throw er +utils.hasSpecialChars = function(str) { + return /(?:(?:(^|\/)[!.])|[*?+()|\[\]{}]|[+@]\()/.test(str); +}; - rmdirSync(p, options, er) - } - } -} +/** + * Normalize slashes in the given filepath. + * + * @param {String} `filepath` + * @return {String} + */ -function rmdirSync (p, options, originalEr) { - assert(p) - assert(options) - if (originalEr) - assert(originalEr instanceof Error) +utils.toPosixPath = function(str) { + return str.replace(/\\+/g, '/'); +}; - try { - options.rmdirSync(p) - } catch (er) { - if (er.code === "ENOENT") - return - if (er.code === "ENOTDIR") - throw originalEr - if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") - rmkidsSync(p, options) +/** + * Strip backslashes before special characters in a string. + * + * @param {String} `str` + * @return {String} + */ + +utils.unescape = function(str) { + return utils.toPosixPath(str.replace(/\\(?=[*+?!.])/g, '')); +}; + +/** + * Strip the drive letter from a windows filepath + * @param {String} `fp` + * @return {String} + */ + +utils.stripDrive = function(fp) { + return utils.isWindows() ? fp.replace(/^[a-z]:[\\\/]+?/i, '/') : fp; +}; + +/** + * Strip the prefix from a filepath + * @param {String} `fp` + * @return {String} + */ + +utils.stripPrefix = function(str) { + if (str.charAt(0) === '.' && (str.charAt(1) === '/' || str.charAt(1) === '\\')) { + return str.slice(2); } -} + return str; +}; -function rmkidsSync (p, options) { - assert(p) - assert(options) - options.readdirSync(p).forEach(function (f) { - rimrafSync(path.join(p, f), options) - }) +/** + * Returns true if `str` is a common character that doesn't need + * to be processed to be used for matching. + * @param {String} `str` + * @return {Boolean} + */ - // We only end up here once we got ENOTEMPTY at least once, and - // at this point, we are guaranteed to have removed all the kids. - // So, we know that it won't be ENOENT or ENOTDIR or anything else. - // try really hard to delete stuff on windows, because it has a - // PROFOUNDLY annoying habit of not closing handles promptly when - // files are deleted, resulting in spurious ENOTEMPTY errors. - var retries = isWindows ? 100 : 1 - var i = 0 - do { - var threw = true - try { - var ret = options.rmdirSync(p, options) - threw = false - return ret - } finally { - if (++i < retries && threw) - continue - } - } while (true) -} +utils.isSimpleChar = function(str) { + return str === '' || str === ' ' || str === '.'; +}; +/** + * Returns true if the given str is an escaped or + * unescaped path character + */ -/***/ }), -/* 224 */ -/***/ (function(module, exports, __webpack_require__) { +utils.isSlash = function(str) { + return str === '/' || str === '\\/' || str === '\\' || str === '\\\\'; +}; -"use strict"; +/** + * Returns a function that returns true if the given + * pattern matches or contains a `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ -module.exports = (iterable, mapper, opts) => new Promise((resolve, reject) => { - opts = Object.assign({ - concurrency: Infinity - }, opts); +utils.matchPath = function(pattern, options) { + return (options && options.contains) + ? utils.containsPattern(pattern, options) + : utils.equalsPattern(pattern, options); +}; - if (typeof mapper !== 'function') { - throw new TypeError('Mapper function is required'); - } +/** + * Returns true if the given (original) filepath or unixified path are equal + * to the given pattern. + */ - const concurrency = opts.concurrency; +utils._equals = function(filepath, unixPath, pattern) { + return pattern === filepath || pattern === unixPath; +}; - if (!(typeof concurrency === 'number' && concurrency >= 1)) { - throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${concurrency}\` (${typeof concurrency})`); - } +/** + * Returns true if the given (original) filepath or unixified path contain + * the given pattern. + */ - const ret = []; - const iterator = iterable[Symbol.iterator](); - let isRejected = false; - let iterableDone = false; - let resolvingCount = 0; - let currentIdx = 0; +utils._contains = function(filepath, unixPath, pattern) { + return filepath.indexOf(pattern) !== -1 || unixPath.indexOf(pattern) !== -1; +}; - const next = () => { - if (isRejected) { - return; - } +/** + * Returns a function that returns true if the given + * pattern is the same as a given `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ - const nextItem = iterator.next(); - const i = currentIdx; - currentIdx++; +utils.equalsPattern = function(pattern, options) { + var unixify = utils.unixify(options); + options = options || {}; - if (nextItem.done) { - iterableDone = true; + return function fn(filepath) { + var equal = utils._equals(filepath, unixify(filepath), pattern); + if (equal === true || options.nocase !== true) { + return equal; + } + var lower = filepath.toLowerCase(); + return utils._equals(lower, unixify(lower), pattern); + }; +}; - if (resolvingCount === 0) { - resolve(ret); - } +/** + * Returns a function that returns true if the given + * pattern contains a `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ - return; - } +utils.containsPattern = function(pattern, options) { + var unixify = utils.unixify(options); + options = options || {}; - resolvingCount++; + return function(filepath) { + var contains = utils._contains(filepath, unixify(filepath), pattern); + if (contains === true || options.nocase !== true) { + return contains; + } + var lower = filepath.toLowerCase(); + return utils._contains(lower, unixify(lower), pattern); + }; +}; - Promise.resolve(nextItem.value) - .then(el => mapper(el, i)) - .then( - val => { - ret[i] = val; - resolvingCount--; - next(); - }, - err => { - isRejected = true; - reject(err); - } - ); - }; +/** + * Returns a function that returns true if the given + * regex matches the `filename` of a file path. + * + * @param {RegExp} `re` Matching regex + * @return {Function} + */ - for (let i = 0; i < concurrency; i++) { - next(); +utils.matchBasename = function(re) { + return function(filepath) { + return re.test(filepath) || re.test(path.basename(filepath)); + }; +}; - if (iterableDone) { - break; - } - } -}); +/** + * Returns the given value unchanced. + * @return {any} + */ + +utils.identity = function(val) { + return val; +}; + +/** + * Determines the filepath to return based on the provided options. + * @return {any} + */ + +utils.value = function(str, unixify, options) { + if (options && options.unixify === false) { + return str; + } + if (options && typeof options.unixify === 'function') { + return options.unixify(str); + } + return unixify(str); +}; + +/** + * Returns a function that normalizes slashes in a string to forward + * slashes, strips `./` from beginning of paths, and optionally unescapes + * special characters. + * @return {Function} + */ + +utils.unixify = function(options) { + var opts = options || {}; + return function(filepath) { + if (opts.stripPrefix !== false) { + filepath = utils.stripPrefix(filepath); + } + if (opts.unescape === true) { + filepath = utils.unescape(filepath); + } + if (opts.unixify === true || utils.isWindows()) { + filepath = utils.toPosixPath(filepath); + } + return filepath; + }; +}; /***/ }), -/* 225 */ -/***/ (function(module, exports, __webpack_require__) { +/* 416 */ +/***/ (function(module, exports) { -"use strict"; +var toString = Object.prototype.toString; -const chalk = __webpack_require__(226); -const cliCursor = __webpack_require__(230); -const cliSpinners = __webpack_require__(234); -const logSymbols = __webpack_require__(110); +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ -class Ora { - constructor(options) { - if (typeof options === 'string') { - options = { - text: options - }; - } +module.exports = function kindOf(val) { + var type = typeof val; - this.options = Object.assign({ - text: '', - color: 'cyan', - stream: process.stderr - }, options); + // primitivies + if (type === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (type === 'string' || val instanceof String) { + return 'string'; + } + if (type === 'number' || val instanceof Number) { + return 'number'; + } - const sp = this.options.spinner; - this.spinner = typeof sp === 'object' ? sp : (process.platform === 'win32' ? cliSpinners.line : (cliSpinners[sp] || cliSpinners.dots)); // eslint-disable-line no-nested-ternary + // functions + if (type === 'function' || val instanceof Function) { + if (typeof val.constructor.name !== 'undefined' && val.constructor.name.slice(0, 9) === 'Generator') { + return 'generatorfunction'; + } + return 'function'; + } - if (this.spinner.frames === undefined) { - throw new Error('Spinner must define `frames`'); - } + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } - this.text = this.options.text; - this.color = this.options.color; - this.interval = this.options.interval || this.spinner.interval || 100; - this.stream = this.options.stream; - this.id = null; - this.frameIndex = 0; - this.enabled = typeof this.options.enabled === 'boolean' ? this.options.enabled : ((this.stream && this.stream.isTTY) && !process.env.CI); - } - frame() { - const frames = this.spinner.frames; - let frame = frames[this.frameIndex]; + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } - if (this.color) { - frame = chalk[this.color](frame); - } + // other objects + type = toString.call(val); - this.frameIndex = ++this.frameIndex % frames.length; + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + if (type === '[object Promise]') { + return 'promise'; + } - return frame + ' ' + this.text; - } - clear() { - if (!this.enabled) { - return this; - } + // buffer + if (isBuffer(val)) { + return 'buffer'; + } - this.stream.clearLine(); - this.stream.cursorTo(0); + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } + + if (type === '[object Map Iterator]') { + return 'mapiterator'; + } + if (type === '[object Set Iterator]') { + return 'setiterator'; + } + if (type === '[object String Iterator]') { + return 'stringiterator'; + } + if (type === '[object Array Iterator]') { + return 'arrayiterator'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } - return this; - } - render() { - this.clear(); - this.stream.write(this.frame()); + // must be a plain object + return 'object'; +}; - return this; - } - start(text) { - if (text) { - this.text = text; - } +/** + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer + */ - if (!this.enabled || this.id) { - return this; - } +function isBuffer(val) { + return val.constructor + && typeof val.constructor.isBuffer === 'function' + && val.constructor.isBuffer(val); +} - cliCursor.hide(this.stream); - this.render(); - this.id = setInterval(this.render.bind(this), this.interval); - return this; - } - stop() { - if (!this.enabled) { - return this; - } +/***/ }), +/* 417 */ +/***/ (function(module, exports, __webpack_require__) { - clearInterval(this.id); - this.id = null; - this.frameIndex = 0; - this.clear(); - cliCursor.show(this.stream); +"use strict"; - return this; - } - succeed(text) { - return this.stopAndPersist({symbol: logSymbols.success, text}); - } - fail(text) { - return this.stopAndPersist({symbol: logSymbols.error, text}); - } - warn(text) { - return this.stopAndPersist({symbol: logSymbols.warning, text}); - } - info(text) { - return this.stopAndPersist({symbol: logSymbols.info, text}); - } - stopAndPersist(options) { - if (!this.enabled) { - return this; - } - // Legacy argument - // TODO: Deprecate sometime in the future - if (typeof options === 'string') { - options = { - symbol: options - }; - } +var posix = __webpack_require__(418); + +module.exports = function(brackets) { + brackets.compiler + + /** + * Escaped characters + */ + + .set('escape', function(node) { + return this.emit('\\' + node.val.replace(/^\\/, ''), node); + }) + + /** + * Text + */ + + .set('text', function(node) { + return this.emit(node.val.replace(/([{}])/g, '\\$1'), node); + }) - options = options || {}; + /** + * POSIX character classes + */ - this.stop(); - this.stream.write(`${options.symbol || ' '} ${options.text || this.text}\n`); + .set('posix', function(node) { + if (node.val === '[::]') { + return this.emit('\\[::\\]', node); + } - return this; - } -} + var val = posix[node.inner]; + if (typeof val === 'undefined') { + val = '[' + node.inner + ']'; + } + return this.emit(val, node); + }) -module.exports = function (opts) { - return new Ora(opts); -}; + /** + * Non-posix brackets + */ -module.exports.promise = (action, options) => { - if (typeof action.then !== 'function') { - throw new TypeError('Parameter `action` must be a Promise'); - } + .set('bracket', function(node) { + return this.mapVisit(node.nodes); + }) + .set('bracket.open', function(node) { + return this.emit(node.val, node); + }) + .set('bracket.inner', function(node) { + var inner = node.val; - const spinner = new Ora(options); - spinner.start(); + if (inner === '[' || inner === ']') { + return this.emit('\\' + node.val, node); + } + if (inner === '^]') { + return this.emit('^\\]', node); + } + if (inner === '^') { + return this.emit('^', node); + } - action.then( - () => { - spinner.succeed(); - }, - () => { - spinner.fail(); - } - ); + if (/-/.test(inner) && !/(\d-\d|\w-\w)/.test(inner)) { + inner = inner.split('-').join('\\-'); + } - return spinner; + var isNegated = inner.charAt(0) === '^'; + // add slashes to negated brackets, per spec + if (isNegated && inner.indexOf('/') === -1) { + inner += '/'; + } + if (isNegated && inner.indexOf('.') === -1) { + inner += '.'; + } + + // don't unescape `0` (octal literal) + inner = inner.replace(/\\([1-9])/g, '$1'); + return this.emit(inner, node); + }) + .set('bracket.close', function(node) { + var val = node.val.replace(/^\\/, ''); + if (node.parent.escaped === true) { + return this.emit('\\' + val, node); + } + return this.emit(val, node); + }); }; /***/ }), -/* 226 */ +/* 418 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const escapeStringRegexp = __webpack_require__(82); -const ansiStyles = __webpack_require__(227); -const stdoutColor = __webpack_require__(228).stdout; -const template = __webpack_require__(229); +/** + * POSIX character classes + */ -const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); +module.exports = { + alnum: 'a-zA-Z0-9', + alpha: 'a-zA-Z', + ascii: '\\x00-\\x7F', + blank: ' \\t', + cntrl: '\\x00-\\x1F\\x7F', + digit: '0-9', + graph: '\\x21-\\x7E', + lower: 'a-z', + print: '\\x20-\\x7E ', + punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', + space: ' \\t\\r\\n\\v\\f', + upper: 'A-Z', + word: 'A-Za-z0-9_', + xdigit: 'A-Fa-f0-9' +}; -// `supportsColor.level` → `ansiStyles.color[name]` mapping -const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; -// `color-convert` models to exclude from the Chalk API due to conflicts and such -const skipModels = new Set(['gray']); +/***/ }), +/* 419 */ +/***/ (function(module, exports, __webpack_require__) { -const styles = Object.create(null); +"use strict"; -function applyOptions(obj, options) { - options = options || {}; - // Detect level if not set manually - const scLevel = stdoutColor ? stdoutColor.level : 0; - obj.level = options.level === undefined ? scLevel : options.level; - obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; -} +var utils = __webpack_require__(420); +var define = __webpack_require__(421); -function Chalk(options) { - // We check for this.template here since calling `chalk.constructor()` - // by itself will have a `this` of a previously constructed chalk object - if (!this || !(this instanceof Chalk) || this.template) { - const chalk = {}; - applyOptions(chalk, options); +/** + * Text regex + */ - chalk.template = function () { - const args = [].slice.call(arguments); - return chalkTag.apply(null, [chalk.template].concat(args)); - }; +var TEXT_REGEX = '(\\[(?=.*\\])|\\])+'; +var not = utils.createRegex(TEXT_REGEX); - Object.setPrototypeOf(chalk, Chalk.prototype); - Object.setPrototypeOf(chalk.template, chalk); +/** + * Brackets parsers + */ - chalk.template.constructor = Chalk; +function parsers(brackets) { + brackets.state = brackets.state || {}; + brackets.parser.sets.bracket = brackets.parser.sets.bracket || []; + brackets.parser - return chalk.template; - } + .capture('escape', function() { + if (this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(/^\\(.)/); + if (!m) return; - applyOptions(this, options); -} + return pos({ + type: 'escape', + val: m[0] + }); + }) -// Use bright blue on Windows as the normal blue color is illegible -if (isSimpleWindowsTerm) { - ansiStyles.blue.open = '\u001B[94m'; -} + /** + * Text parser + */ -for (const key of Object.keys(ansiStyles)) { - ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + .capture('text', function() { + if (this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(not); + if (!m || !m[0]) return; - styles[key] = { - get() { - const codes = ansiStyles[key]; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); - } - }; -} + return pos({ + type: 'text', + val: m[0] + }); + }) -styles.visible = { - get() { - return build.call(this, this._styles || [], true, 'visible'); - } -}; + /** + * POSIX character classes: "[[:alpha:][:digits:]]" + */ -ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); -for (const model of Object.keys(ansiStyles.color.ansi)) { - if (skipModels.has(model)) { - continue; - } + .capture('posix', function() { + var pos = this.position(); + var m = this.match(/^\[:(.*?):\](?=.*\])/); + if (!m) return; - styles[model] = { - get() { - const level = this.level; - return function () { - const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); - const codes = { - open, - close: ansiStyles.color.close, - closeRe: ansiStyles.color.closeRe - }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); - }; - } - }; -} + var inside = this.isInside('bracket'); + if (inside) { + brackets.posix++; + } -ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); -for (const model of Object.keys(ansiStyles.bgColor.ansi)) { - if (skipModels.has(model)) { - continue; - } + return pos({ + type: 'posix', + insideBracket: inside, + inner: m[1], + val: m[0] + }); + }) - const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); - styles[bgModel] = { - get() { - const level = this.level; - return function () { - const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); - const codes = { - open, - close: ansiStyles.bgColor.close, - closeRe: ansiStyles.bgColor.closeRe - }; - return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); - }; - } - }; -} + /** + * Bracket (noop) + */ -const proto = Object.defineProperties(() => {}, styles); + .capture('bracket', function() {}) -function build(_styles, _empty, key) { - const builder = function () { - return applyStyle.apply(builder, arguments); - }; + /** + * Open: '[' + */ - builder._styles = _styles; - builder._empty = _empty; + .capture('bracket.open', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\[(?=.*\])/); + if (!m) return; - const self = this; + var prev = this.prev(); + var last = utils.last(prev.nodes); - Object.defineProperty(builder, 'level', { - enumerable: true, - get() { - return self.level; - }, - set(level) { - self.level = level; - } - }); + if (parsed.slice(-1) === '\\' && !this.isInside('bracket')) { + last.val = last.val.slice(0, last.val.length - 1); + return pos({ + type: 'escape', + val: m[0] + }); + } - Object.defineProperty(builder, 'enabled', { - enumerable: true, - get() { - return self.enabled; - }, - set(enabled) { - self.enabled = enabled; - } - }); + var open = pos({ + type: 'bracket.open', + val: m[0] + }); - // See below for fix regarding invisible grey/dim combination on Windows - builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; + if (last.type === 'bracket.open' || this.isInside('bracket')) { + open.val = '\\' + open.val; + open.type = 'bracket.inner'; + open.escaped = true; + return open; + } - // `__proto__` is used because we must return a function, but there is - // no way to create a function with a different prototype - builder.__proto__ = proto; // eslint-disable-line no-proto + var node = pos({ + type: 'bracket', + nodes: [open] + }); - return builder; -} + define(node, 'parent', prev); + define(open, 'parent', node); + this.push('bracket', node); + prev.nodes.push(node); + }) -function applyStyle() { - // Support varags, but simply cast to string in case there's only one arg - const args = arguments; - const argsLen = args.length; - let str = String(arguments[0]); + /** + * Bracket text + */ - if (argsLen === 0) { - return ''; - } + .capture('bracket.inner', function() { + if (!this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(not); + if (!m || !m[0]) return; - if (argsLen > 1) { - // Don't slice `arguments`, it prevents V8 optimizations - for (let a = 1; a < argsLen; a++) { - str += ' ' + args[a]; - } - } + var next = this.input.charAt(0); + var val = m[0]; - if (!this.enabled || this.level <= 0 || !str) { - return this._empty ? '' : str; - } + var node = pos({ + type: 'bracket.inner', + val: val + }); - // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, - // see https://github.com/chalk/chalk/issues/58 - // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. - const originalDim = ansiStyles.dim.open; - if (isSimpleWindowsTerm && this.hasGrey) { - ansiStyles.dim.open = ''; - } + if (val === '\\\\') { + return node; + } - for (const code of this._styles.slice().reverse()) { - // Replace any instances already present with a re-opening code - // otherwise only the part of the string until said closing code - // will be colored, and the rest will simply be 'plain'. - str = code.open + str.replace(code.closeRe, code.open) + code.close; + var first = val.charAt(0); + var last = val.slice(-1); - // Close the styling before a linebreak and reopen - // after next line to fix a bleed issue on macOS - // https://github.com/chalk/chalk/pull/92 - str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); - } + if (first === '!') { + val = '^' + val.slice(1); + } - // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue - ansiStyles.dim.open = originalDim; + if (last === '\\' || (val === '^' && next === ']')) { + val += this.input[0]; + this.consume(1); + } - return str; -} + node.val = val; + return node; + }) -function chalkTag(chalk, strings) { - if (!Array.isArray(strings)) { - // If chalk() was called by itself or with a string, - // return the string itself as a string. - return [].slice.call(arguments, 1).join(' '); - } + /** + * Close: ']' + */ - const args = [].slice.call(arguments, 2); - const parts = [strings.raw[0]]; + .capture('bracket.close', function() { + var parsed = this.parsed; + var pos = this.position(); + var m = this.match(/^\]/); + if (!m) return; - for (let i = 1; i < strings.length; i++) { - parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); - parts.push(String(strings.raw[i])); - } + var prev = this.prev(); + var last = utils.last(prev.nodes); - return template(chalk, parts.join('')); + if (parsed.slice(-1) === '\\' && !this.isInside('bracket')) { + last.val = last.val.slice(0, last.val.length - 1); + + return pos({ + type: 'escape', + val: m[0] + }); + } + + var node = pos({ + type: 'bracket.close', + rest: this.input, + val: m[0] + }); + + if (last.type === 'bracket.open') { + node.type = 'bracket.inner'; + node.escaped = true; + return node; + } + + var bracket = this.pop('bracket'); + if (!this.isType(bracket, 'bracket')) { + if (this.options.strict) { + throw new Error('missing opening "["'); + } + node.type = 'bracket.inner'; + node.escaped = true; + return node; + } + + bracket.nodes.push(node); + define(node, 'parent', bracket); + }); } -Object.defineProperties(Chalk.prototype, styles); +/** + * Brackets parsers + */ -module.exports = Chalk(); // eslint-disable-line new-cap -module.exports.supportsColor = stdoutColor; -module.exports.default = module.exports; // For TypeScript +module.exports = parsers; + +/** + * Expose text regex + */ + +module.exports.TEXT_REGEX = TEXT_REGEX; /***/ }), -/* 227 */ +/* 420 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* WEBPACK VAR INJECTION */(function(module) { -const colorConvert = __webpack_require__(83); -const wrapAnsi16 = (fn, offset) => function () { - const code = fn.apply(colorConvert, arguments); - return `\u001B[${code + offset}m`; -}; -const wrapAnsi256 = (fn, offset) => function () { - const code = fn.apply(colorConvert, arguments); - return `\u001B[${38 + offset};5;${code}m`; -}; +var toRegex = __webpack_require__(43); +var regexNot = __webpack_require__(64); +var cached; -const wrapAnsi16m = (fn, offset) => function () { - const rgb = fn.apply(colorConvert, arguments); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +/** + * Get the last element from `array` + * @param {Array} `array` + * @return {*} + */ + +exports.last = function(arr) { + return arr[arr.length - 1]; }; -function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39], +/** + * Create and cache regex to use for text nodes + */ - // Bright color - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], +exports.createRegex = function(pattern, include) { + if (cached) return cached; + var opts = {contains: true, strictClose: false}; + var not = regexNot.create(pattern, opts); + var re; - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; + if (typeof include === 'string') { + re = toRegex('^(?:' + include + '|' + not + ')', opts); + } else { + re = toRegex(not, opts); + } - // Fix humans - styles.color.grey = styles.color.gray; + return (cached = re); +}; - for (const groupName of Object.keys(styles)) { - const group = styles[groupName]; - for (const styleName of Object.keys(group)) { - const style = group[styleName]; +/***/ }), +/* 421 */ +/***/ (function(module, exports, __webpack_require__) { - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; +"use strict"; +/*! + * define-property + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ - group[styleName] = styles[styleName]; - codes.set(style[0], style[1]); - } - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); +var isDescriptor = __webpack_require__(422); - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); - } +module.exports = function defineProperty(obj, prop, val) { + if (typeof obj !== 'object' && typeof obj !== 'function') { + throw new TypeError('expected an object or function.'); + } - const ansi2ansi = n => n; - const rgb2rgb = (r, g, b) => [r, g, b]; + if (typeof prop !== 'string') { + throw new TypeError('expected `prop` to be a string.'); + } - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; + if (isDescriptor(val) && ('set' in val || 'get' in val)) { + return Object.defineProperty(obj, prop, val); + } - styles.color.ansi = { - ansi: wrapAnsi16(ansi2ansi, 0) - }; - styles.color.ansi256 = { - ansi256: wrapAnsi256(ansi2ansi, 0) - }; - styles.color.ansi16m = { - rgb: wrapAnsi16m(rgb2rgb, 0) - }; + return Object.defineProperty(obj, prop, { + configurable: true, + enumerable: false, + writable: true, + value: val + }); +}; - styles.bgColor.ansi = { - ansi: wrapAnsi16(ansi2ansi, 10) - }; - styles.bgColor.ansi256 = { - ansi256: wrapAnsi256(ansi2ansi, 10) - }; - styles.bgColor.ansi16m = { - rgb: wrapAnsi16m(rgb2rgb, 10) - }; - for (let key of Object.keys(colorConvert)) { - if (typeof colorConvert[key] !== 'object') { - continue; - } +/***/ }), +/* 422 */ +/***/ (function(module, exports, __webpack_require__) { - const suite = colorConvert[key]; +"use strict"; +/*! + * is-descriptor + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ - if (key === 'ansi16') { - key = 'ansi'; - } - if ('ansi16' in suite) { - styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); - styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); - } - if ('ansi256' in suite) { - styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); - styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); - } +var typeOf = __webpack_require__(423); +var isAccessor = __webpack_require__(424); +var isData = __webpack_require__(426); - if ('rgb' in suite) { - styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); - styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); - } - } +module.exports = function isDescriptor(obj, key) { + if (typeOf(obj) !== 'object') { + return false; + } + if ('get' in obj) { + return isAccessor(obj, key); + } + return isData(obj, key); +}; - return styles; -} -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); +/***/ }), +/* 423 */ +/***/ (function(module, exports) { -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(59)(module))) +var toString = Object.prototype.toString; -/***/ }), -/* 228 */ -/***/ (function(module, exports, __webpack_require__) { +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ -"use strict"; +module.exports = function kindOf(val) { + var type = typeof val; -const os = __webpack_require__(84); -const hasFlag = __webpack_require__(93); + // primitivies + if (type === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (type === 'string' || val instanceof String) { + return 'string'; + } + if (type === 'number' || val instanceof Number) { + return 'number'; + } -const env = process.env; + // functions + if (type === 'function' || val instanceof Function) { + if (typeof val.constructor.name !== 'undefined' && val.constructor.name.slice(0, 9) === 'Generator') { + return 'generatorfunction'; + } + return 'function'; + } -let forceColor; -if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false')) { - forceColor = false; -} else if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - forceColor = true; -} -if ('FORCE_COLOR' in env) { - forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; -} + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } -function translateLevel(level) { - if (level === 0) { - return false; - } + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; -} + // other objects + type = toString.call(val); + + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } + if (type === '[object Promise]') { + return 'promise'; + } + + // buffer + if (isBuffer(val)) { + return 'buffer'; + } + + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } + + if (type === '[object Map Iterator]') { + return 'mapiterator'; + } + if (type === '[object Set Iterator]') { + return 'setiterator'; + } + if (type === '[object String Iterator]') { + return 'stringiterator'; + } + if (type === '[object Array Iterator]') { + return 'arrayiterator'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } -function supportsColor(stream) { - if (forceColor === false) { - return 0; - } + // must be a plain object + return 'object'; +}; - if (hasFlag('color=16m') || - hasFlag('color=full') || - hasFlag('color=truecolor')) { - return 3; - } +/** + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer + */ - if (hasFlag('color=256')) { - return 2; - } +function isBuffer(val) { + return val.constructor + && typeof val.constructor.isBuffer === 'function' + && val.constructor.isBuffer(val); +} - if (stream && !stream.isTTY && forceColor !== true) { - // VS code debugger doesn't have isTTY set - if (env.VSCODE_PID) { - return 1; - } - return 0; - } - const min = forceColor ? 1 : 0; +/***/ }), +/* 424 */ +/***/ (function(module, exports, __webpack_require__) { - if (process.platform === 'win32') { - // Node.js 7.5.0 is the first version of Node.js to include a patch to - // libuv that enables 256 color output on Windows. Anything earlier and it - // won't work. However, here we target Node.js 8 at minimum as it is an LTS - // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows - // release that supports 256 colors. Windows 10 build 14931 is the first release - // that supports 16m/TrueColor. - const osRelease = os.release().split('.'); - if ( - Number(process.versions.node.split('.')[0]) >= 8 && - Number(osRelease[0]) >= 10 && - Number(osRelease[2]) >= 10586 - ) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } +"use strict"; +/*! + * is-accessor-descriptor + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ - return 1; - } - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { - return 1; - } - return min; - } +var typeOf = __webpack_require__(425); - if ('TEAMCITY_VERSION' in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } +// accessor descriptor properties +var accessor = { + get: 'function', + set: 'function', + configurable: 'boolean', + enumerable: 'boolean' +}; - if (env.COLORTERM === 'truecolor') { - return 3; - } +function isAccessorDescriptor(obj, prop) { + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; + } - if ('TERM_PROGRAM' in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + if (typeOf(obj) !== 'object') { + return false; + } - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Apple_Terminal': - return 2; - // No default - } - } + if (has(obj, 'value') || has(obj, 'writable')) { + return false; + } - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } + if (!has(obj, 'get') || typeof obj.get !== 'function') { + return false; + } - if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } + // tldr: it's valid to have "set" be undefined + // "set" might be undefined if `Object.getOwnPropertyDescriptor` + // was used to get the value, and only `get` was defined by the user + if (has(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') { + return false; + } - if ('COLORTERM' in env) { - return 1; - } + for (var key in obj) { + if (!accessor.hasOwnProperty(key)) { + continue; + } - if (env.TERM === 'dumb') { - return min; - } + if (typeOf(obj[key]) === accessor[key]) { + continue; + } - return min; + if (typeof obj[key] !== 'undefined') { + return false; + } + } + return true; } -function getSupportLevel(stream) { - const level = supportsColor(stream); - return translateLevel(level); +function has(obj, key) { + return {}.hasOwnProperty.call(obj, key); } -module.exports = { - supportsColor: getSupportLevel, - stdout: getSupportLevel(process.stdout), - stderr: getSupportLevel(process.stderr) -}; +/** + * Expose `isAccessorDescriptor` + */ + +module.exports = isAccessorDescriptor; /***/ }), -/* 229 */ +/* 425 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +var isBuffer = __webpack_require__(22); +var toString = Object.prototype.toString; -const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; -const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; -const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; -const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ -const ESCAPES = new Map([ - ['n', '\n'], - ['r', '\r'], - ['t', '\t'], - ['b', '\b'], - ['f', '\f'], - ['v', '\v'], - ['0', '\0'], - ['\\', '\\'], - ['e', '\u001B'], - ['a', '\u0007'] -]); +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; + } -function unescape(c) { - if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) { - return String.fromCharCode(parseInt(c.slice(1), 16)); - } + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; + } - return ESCAPES.get(c) || c; -} + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } -function parseArguments(name, args) { - const results = []; - const chunks = args.trim().split(/\s*,\s*/g); - let matches; + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } - for (const chunk of chunks) { - if (!isNaN(chunk)) { - results.push(Number(chunk)); - } else if ((matches = chunk.match(STRING_REGEX))) { - results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr)); - } else { - throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); - } - } + // other objects + var type = toString.call(val); - return results; -} + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } -function parseStyle(style) { - STYLE_REGEX.lastIndex = 0; + // buffer + if (isBuffer(val)) { + return 'buffer'; + } - const results = []; - let matches; + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } - while ((matches = STYLE_REGEX.exec(style)) !== null) { - const name = matches[1]; + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } - if (matches[2]) { - const args = parseArguments(name, matches[2]); - results.push([name].concat(args)); - } else { - results.push([name]); - } - } + // must be a plain object + return 'object'; +}; - return results; -} -function buildStyle(chalk, styles) { - const enabled = {}; +/***/ }), +/* 426 */ +/***/ (function(module, exports, __webpack_require__) { - for (const layer of styles) { - for (const style of layer.styles) { - enabled[style[0]] = layer.inverse ? null : style.slice(1); - } - } +"use strict"; +/*! + * is-data-descriptor + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ - let current = chalk; - for (const styleName of Object.keys(enabled)) { - if (Array.isArray(enabled[styleName])) { - if (!(styleName in current)) { - throw new Error(`Unknown Chalk style: ${styleName}`); - } - if (enabled[styleName].length > 0) { - current = current[styleName].apply(current, enabled[styleName]); - } else { - current = current[styleName]; - } - } - } - return current; -} +var typeOf = __webpack_require__(427); -module.exports = (chalk, tmp) => { - const styles = []; - const chunks = []; - let chunk = []; +// data descriptor properties +var data = { + configurable: 'boolean', + enumerable: 'boolean', + writable: 'boolean' +}; - // eslint-disable-next-line max-params - tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { - if (escapeChar) { - chunk.push(unescape(escapeChar)); - } else if (style) { - const str = chunk.join(''); - chunk = []; - chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); - styles.push({inverse, styles: parseStyle(style)}); - } else if (close) { - if (styles.length === 0) { - throw new Error('Found extraneous } in Chalk template literal'); - } +function isDataDescriptor(obj, prop) { + if (typeOf(obj) !== 'object') { + return false; + } - chunks.push(buildStyle(chalk, styles)(chunk.join(''))); - chunk = []; - styles.pop(); - } else { - chunk.push(chr); - } - }); + if (typeof prop === 'string') { + var val = Object.getOwnPropertyDescriptor(obj, prop); + return typeof val !== 'undefined'; + } - chunks.push(chunk.join('')); + if (!('value' in obj) && !('writable' in obj)) { + return false; + } - if (styles.length > 0) { - const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; - throw new Error(errMsg); - } + for (var key in obj) { + if (key === 'value') continue; - return chunks.join(''); -}; + if (!data.hasOwnProperty(key)) { + continue; + } + + if (typeOf(obj[key]) === data[key]) { + continue; + } + + if (typeof obj[key] !== 'undefined') { + return false; + } + } + return true; +} + +/** + * Expose `isDataDescriptor` + */ + +module.exports = isDataDescriptor; /***/ }), -/* 230 */ +/* 427 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +var isBuffer = __webpack_require__(22); +var toString = Object.prototype.toString; -const restoreCursor = __webpack_require__(231); +/** + * Get the native `typeof` a value. + * + * @param {*} `val` + * @return {*} Native javascript type + */ -let hidden = false; +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; + } + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; + } -exports.show = stream => { - const s = stream || process.stderr; + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; + } - if (!s.isTTY) { - return; - } + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } - hidden = false; - s.write('\u001b[?25h'); -}; + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } -exports.hide = stream => { - const s = stream || process.stderr; + // other objects + var type = toString.call(val); - if (!s.isTTY) { - return; - } + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } - restoreCursor(); - hidden = true; - s.write('\u001b[?25l'); -}; + // buffer + if (isBuffer(val)) { + return 'buffer'; + } -exports.toggle = (force, stream) => { - if (force !== undefined) { - hidden = force; - } + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } - if (hidden) { - exports.show(stream); - } else { - exports.hide(stream); - } + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } + + // must be a plain object + return 'object'; }; /***/ }), -/* 231 */ +/* 428 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const onetime = __webpack_require__(232); -const signalExit = __webpack_require__(89); -module.exports = onetime(() => { - signalExit(() => { - process.stderr.write('\u001b[?25h'); - }, {alwaysLast: true}); -}); +/** + * Module dependencies + */ +var Snapdragon = __webpack_require__(66); +var define = __webpack_require__(44); +var extend = __webpack_require__(20); -/***/ }), -/* 232 */ -/***/ (function(module, exports, __webpack_require__) { +/** + * Local dependencies + */ -"use strict"; +var compilers = __webpack_require__(153); +var parsers = __webpack_require__(155); -const mimicFn = __webpack_require__(233); +/** + * Customize Snapdragon parser and renderer + */ -module.exports = (fn, opts) => { - // TODO: Remove this in v3 - if (opts === true) { - throw new TypeError('The second argument is now an options object'); - } +function Extglob(options) { + this.options = extend({source: 'extglob'}, options); + this.snapdragon = this.options.snapdragon || new Snapdragon(this.options); + this.snapdragon.patterns = this.snapdragon.patterns || {}; + this.compiler = this.snapdragon.compiler; + this.parser = this.snapdragon.parser; - if (typeof fn !== 'function') { - throw new TypeError('Expected a function'); - } + compilers(this.snapdragon); + parsers(this.snapdragon); - opts = opts || {}; + /** + * Override Snapdragon `.parse` method + */ - let ret; - let called = false; - const fnName = fn.displayName || fn.name || ''; + define(this.snapdragon, 'parse', function(str, options) { + var parsed = Snapdragon.prototype.parse.apply(this, arguments); + parsed.input = str; + + // escape unmatched brace/bracket/parens + var last = this.parser.stack.pop(); + if (last && this.options.strict !== true) { + var node = last.nodes[0]; + node.val = '\\' + node.val; + var sibling = node.parent.nodes[1]; + if (sibling.type === 'star') { + sibling.loose = true; + } + } - const onetime = function () { - if (called) { - if (opts.throw === true) { - throw new Error(`Function \`${fnName}\` can only be called once`); - } + // add non-enumerable parser reference + define(parsed, 'parser', this.parser); + return parsed; + }); - return ret; - } + /** + * Decorate `.parse` method + */ - called = true; - ret = fn.apply(this, arguments); - fn = null; + define(this, 'parse', function(ast, options) { + return this.snapdragon.parse.apply(this.snapdragon, arguments); + }); - return ret; - }; + /** + * Decorate `.compile` method + */ - mimicFn(onetime, fn); + define(this, 'compile', function(ast, options) { + return this.snapdragon.compile.apply(this.snapdragon, arguments); + }); - return onetime; -}; +} + +/** + * Expose `Extglob` + */ + +module.exports = Extglob; /***/ }), -/* 233 */ +/* 429 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = (to, from) => { - // TODO: use `Reflect.ownKeys()` when targeting Node.js 6 - for (const prop of Object.getOwnPropertyNames(from).concat(Object.getOwnPropertySymbols(from))) { - Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop)); - } + +var extglob = __webpack_require__(152); +var nanomatch = __webpack_require__(149); +var regexNot = __webpack_require__(64); +var toRegex = __webpack_require__(43); +var not; + +/** + * Characters to use in negation regex (we want to "not" match + * characters that are matched by other parsers) + */ + +var TEXT = '([!@*?+]?\\(|\\)|\\[:?(?=.*?:?\\])|:?\\]|[*+?!^$.\\\\/])+'; +var createNotRegex = function(opts) { + return not || (not = textRegex(TEXT)); }; +/** + * Parsers + */ -/***/ }), -/* 234 */ -/***/ (function(module, exports, __webpack_require__) { +module.exports = function(snapdragon) { + var parsers = snapdragon.parser.parsers; + + // register nanomatch parsers + snapdragon.use(nanomatch.parsers); + + // get references to some specific nanomatch parsers before they + // are overridden by the extglob and/or parsers + var escape = parsers.escape; + var slash = parsers.slash; + var qmark = parsers.qmark; + var plus = parsers.plus; + var star = parsers.star; + var dot = parsers.dot; + + // register extglob parsers + snapdragon.use(extglob.parsers); + + // custom micromatch parsers + snapdragon.parser + .use(function() { + // override "notRegex" created in nanomatch parser + this.notRegex = /^\!+(?!\()/; + }) + // reset the referenced parsers + .capture('escape', escape) + .capture('slash', slash) + .capture('qmark', qmark) + .capture('star', star) + .capture('plus', plus) + .capture('dot', dot) -"use strict"; + /** + * Override `text` parser + */ -module.exports = __webpack_require__(235); + .capture('text', function() { + if (this.isInside('bracket')) return; + var pos = this.position(); + var m = this.match(createNotRegex(this.options)); + if (!m || !m[0]) return; + // escape regex boundary characters and simple brackets + var val = m[0].replace(/([[\]^$])/g, '\\$1'); -/***/ }), -/* 235 */ -/***/ (function(module) { + return pos({ + type: 'text', + val: val + }); + }); +}; + +/** + * Create text regex + */ + +function textRegex(pattern) { + var notStr = regexNot.create(pattern, {contains: true, strictClose: false}); + var prefix = '(?:[\\^]|\\\\|'; + return toRegex(prefix + notStr + ')', {strictClose: false}); +} -module.exports = {"dots":{"interval":80,"frames":["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]},"dots2":{"interval":80,"frames":["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"]},"dots3":{"interval":80,"frames":["⠋","⠙","⠚","⠞","⠖","⠦","⠴","⠲","⠳","⠓"]},"dots4":{"interval":80,"frames":["⠄","⠆","⠇","⠋","⠙","⠸","⠰","⠠","⠰","⠸","⠙","⠋","⠇","⠆"]},"dots5":{"interval":80,"frames":["⠋","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋"]},"dots6":{"interval":80,"frames":["⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠴","⠲","⠒","⠂","⠂","⠒","⠚","⠙","⠉","⠁"]},"dots7":{"interval":80,"frames":["⠈","⠉","⠋","⠓","⠒","⠐","⠐","⠒","⠖","⠦","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈"]},"dots8":{"interval":80,"frames":["⠁","⠁","⠉","⠙","⠚","⠒","⠂","⠂","⠒","⠲","⠴","⠤","⠄","⠄","⠤","⠠","⠠","⠤","⠦","⠖","⠒","⠐","⠐","⠒","⠓","⠋","⠉","⠈","⠈"]},"dots9":{"interval":80,"frames":["⢹","⢺","⢼","⣸","⣇","⡧","⡗","⡏"]},"dots10":{"interval":80,"frames":["⢄","⢂","⢁","⡁","⡈","⡐","⡠"]},"dots11":{"interval":100,"frames":["⠁","⠂","⠄","⡀","⢀","⠠","⠐","⠈"]},"dots12":{"interval":80,"frames":["⢀⠀","⡀⠀","⠄⠀","⢂⠀","⡂⠀","⠅⠀","⢃⠀","⡃⠀","⠍⠀","⢋⠀","⡋⠀","⠍⠁","⢋⠁","⡋⠁","⠍⠉","⠋⠉","⠋⠉","⠉⠙","⠉⠙","⠉⠩","⠈⢙","⠈⡙","⢈⠩","⡀⢙","⠄⡙","⢂⠩","⡂⢘","⠅⡘","⢃⠨","⡃⢐","⠍⡐","⢋⠠","⡋⢀","⠍⡁","⢋⠁","⡋⠁","⠍⠉","⠋⠉","⠋⠉","⠉⠙","⠉⠙","⠉⠩","⠈⢙","⠈⡙","⠈⠩","⠀⢙","⠀⡙","⠀⠩","⠀⢘","⠀⡘","⠀⠨","⠀⢐","⠀⡐","⠀⠠","⠀⢀","⠀⡀"]},"line":{"interval":130,"frames":["-","\\","|","/"]},"line2":{"interval":100,"frames":["⠂","-","–","—","–","-"]},"pipe":{"interval":100,"frames":["┤","┘","┴","└","├","┌","┬","┐"]},"simpleDots":{"interval":400,"frames":[". ",".. ","..."," "]},"simpleDotsScrolling":{"interval":200,"frames":[". ",".. ","..."," .."," ."," "]},"star":{"interval":70,"frames":["✶","✸","✹","✺","✹","✷"]},"star2":{"interval":80,"frames":["+","x","*"]},"flip":{"interval":70,"frames":["_","_","_","-","`","`","'","´","-","_","_","_"]},"hamburger":{"interval":100,"frames":["☱","☲","☴"]},"growVertical":{"interval":120,"frames":["▁","▃","▄","▅","▆","▇","▆","▅","▄","▃"]},"growHorizontal":{"interval":120,"frames":["▏","▎","▍","▌","▋","▊","▉","▊","▋","▌","▍","▎"]},"balloon":{"interval":140,"frames":[" ",".","o","O","@","*"," "]},"balloon2":{"interval":120,"frames":[".","o","O","°","O","o","."]},"noise":{"interval":100,"frames":["▓","▒","░"]},"bounce":{"interval":120,"frames":["⠁","⠂","⠄","⠂"]},"boxBounce":{"interval":120,"frames":["▖","▘","▝","▗"]},"boxBounce2":{"interval":100,"frames":["▌","▀","▐","▄"]},"triangle":{"interval":50,"frames":["◢","◣","◤","◥"]},"arc":{"interval":100,"frames":["◜","◠","◝","◞","◡","◟"]},"circle":{"interval":120,"frames":["◡","⊙","◠"]},"squareCorners":{"interval":180,"frames":["◰","◳","◲","◱"]},"circleQuarters":{"interval":120,"frames":["◴","◷","◶","◵"]},"circleHalves":{"interval":50,"frames":["◐","◓","◑","◒"]},"squish":{"interval":100,"frames":["╫","╪"]},"toggle":{"interval":250,"frames":["⊶","⊷"]},"toggle2":{"interval":80,"frames":["▫","▪"]},"toggle3":{"interval":120,"frames":["□","■"]},"toggle4":{"interval":100,"frames":["■","□","▪","▫"]},"toggle5":{"interval":100,"frames":["▮","▯"]},"toggle6":{"interval":300,"frames":["ဝ","၀"]},"toggle7":{"interval":80,"frames":["⦾","⦿"]},"toggle8":{"interval":100,"frames":["◍","◌"]},"toggle9":{"interval":100,"frames":["◉","◎"]},"toggle10":{"interval":100,"frames":["㊂","㊀","㊁"]},"toggle11":{"interval":50,"frames":["⧇","⧆"]},"toggle12":{"interval":120,"frames":["☗","☖"]},"toggle13":{"interval":80,"frames":["=","*","-"]},"arrow":{"interval":100,"frames":["←","↖","↑","↗","→","↘","↓","↙"]},"arrow2":{"interval":80,"frames":["⬆️ ","↗️ ","➡️ ","↘️ ","⬇️ ","↙️ ","⬅️ ","↖️ "]},"arrow3":{"interval":120,"frames":["▹▹▹▹▹","▸▹▹▹▹","▹▸▹▹▹","▹▹▸▹▹","▹▹▹▸▹","▹▹▹▹▸"]},"bouncingBar":{"interval":80,"frames":["[ ]","[= ]","[== ]","[=== ]","[ ===]","[ ==]","[ =]","[ ]","[ =]","[ ==]","[ ===]","[====]","[=== ]","[== ]","[= ]"]},"bouncingBall":{"interval":80,"frames":["( ● )","( ● )","( ● )","( ● )","( ●)","( ● )","( ● )","( ● )","( ● )","(● )"]},"smiley":{"interval":200,"frames":["😄 ","😝 "]},"monkey":{"interval":300,"frames":["🙈 ","🙈 ","🙉 ","🙊 "]},"hearts":{"interval":100,"frames":["💛 ","💙 ","💜 ","💚 ","❤️ "]},"clock":{"interval":100,"frames":["🕐 ","🕑 ","🕒 ","🕓 ","🕔 ","🕕 ","🕖 ","🕗 ","🕘 ","🕙 ","🕚 "]},"earth":{"interval":180,"frames":["🌍 ","🌎 ","🌏 "]},"moon":{"interval":80,"frames":["🌑 ","🌒 ","🌓 ","🌔 ","🌕 ","🌖 ","🌗 ","🌘 "]},"runner":{"interval":140,"frames":["🚶 ","🏃 "]},"pong":{"interval":80,"frames":["▐⠂ ▌","▐⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂▌","▐ ⠠▌","▐ ⡀▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐ ⠠ ▌","▐ ⠂ ▌","▐ ⠈ ▌","▐ ⠂ ▌","▐ ⠠ ▌","▐ ⡀ ▌","▐⠠ ▌"]},"shark":{"interval":120,"frames":["▐|\\____________▌","▐_|\\___________▌","▐__|\\__________▌","▐___|\\_________▌","▐____|\\________▌","▐_____|\\_______▌","▐______|\\______▌","▐_______|\\_____▌","▐________|\\____▌","▐_________|\\___▌","▐__________|\\__▌","▐___________|\\_▌","▐____________|\\▌","▐____________/|▌","▐___________/|_▌","▐__________/|__▌","▐_________/|___▌","▐________/|____▌","▐_______/|_____▌","▐______/|______▌","▐_____/|_______▌","▐____/|________▌","▐___/|_________▌","▐__/|__________▌","▐_/|___________▌","▐/|____________▌"]},"dqpb":{"interval":100,"frames":["d","q","p","b"]},"weather":{"interval":100,"frames":["☀️ ","☀️ ","☀️ ","🌤 ","⛅️ ","🌥 ","☁️ ","🌧 ","🌨 ","🌧 ","🌨 ","🌧 ","🌨 ","⛈ ","🌨 ","🌧 ","🌨 ","☁️ ","🌥 ","⛅️ ","🌤 ","☀️ ","☀️ "]},"christmas":{"interval":400,"frames":["🌲","🎄"]}}; /***/ }), -/* 236 */ +/* 430 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - +module.exports = new (__webpack_require__(107))(); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.RunCommand = undefined; -var _chalk = __webpack_require__(30); +/***/ }), +/* 431 */ +/***/ (function(module, exports, __webpack_require__) { -var _chalk2 = _interopRequireDefault(_chalk); +"use strict"; -var _log = __webpack_require__(36); -var _parallelize = __webpack_require__(85); +var utils = module.exports; +var path = __webpack_require__(5); -var _projects = __webpack_require__(42); +/** + * Module dependencies + */ -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var Snapdragon = __webpack_require__(66); +utils.define = __webpack_require__(44); +utils.diff = __webpack_require__(150); +utils.extend = __webpack_require__(20); +utils.pick = __webpack_require__(151); +utils.typeOf = __webpack_require__(432); +utils.unique = __webpack_require__(65); -function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ +/** + * Returns true if the platform is windows, or `path.sep` is `\\`. + * This is defined as a function to allow `path.sep` to be set in unit tests, + * or by the user, if there is a reason to do so. + * @return {Boolean} + */ +utils.isWindows = function() { + return path.sep === '\\' || process.platform === 'win32'; +}; -const RunCommand = exports.RunCommand = { - description: 'Run script defined in package.json in each package that contains that script.', - name: 'run', - run(projects, projectGraph, { extraArgs }) { - return _asyncToGenerator(function* () { - const batchedProjects = (0, _projects.topologicallyBatchProjects)(projects, projectGraph); - if (extraArgs.length === 0) { - _log.log.write(_chalk2.default.red.bold('\nNo script specified')); - process.exit(1); - } - const scriptName = extraArgs[0]; - const scriptArgs = extraArgs.slice(1); - _log.log.write(_chalk2.default.bold(`\nRunning script [${_chalk2.default.green(scriptName)}] in batched topological order\n`)); - yield (0, _parallelize.parallelizeBatches)(batchedProjects, (() => { - var _ref = _asyncToGenerator(function* (pkg) { - if (pkg.hasScript(scriptName)) { - yield pkg.runScriptStreaming(scriptName, scriptArgs); - } - }); +/** + * Get the `Snapdragon` instance to use + */ - return function (_x) { - return _ref.apply(this, arguments); - }; - })()); - })(); - } -}; +utils.instantiate = function(ast, options) { + var snapdragon; + // if an instance was created by `.parse`, use that instance + if (utils.typeOf(ast) === 'object' && ast.snapdragon) { + snapdragon = ast.snapdragon; + // if the user supplies an instance on options, use that instance + } else if (utils.typeOf(options) === 'object' && options.snapdragon) { + snapdragon = options.snapdragon; + // create a new instance + } else { + snapdragon = new Snapdragon(options); + } -/***/ }), -/* 237 */ -/***/ (function(module, exports, __webpack_require__) { + utils.define(snapdragon, 'parse', function(str, options) { + var parsed = Snapdragon.prototype.parse.apply(this, arguments); + parsed.input = str; -"use strict"; + // escape unmatched brace/bracket/parens + var last = this.parser.stack.pop(); + if (last && this.options.strictErrors !== true) { + var open = last.nodes[0]; + var inner = last.nodes[1]; + if (last.type === 'bracket') { + if (inner.val.charAt(0) === '[') { + inner.val = '\\' + inner.val; + } + } else { + open.val = '\\' + open.val; + var sibling = open.parent.nodes[1]; + if (sibling.type === 'star') { + sibling.loose = true; + } + } + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.WatchCommand = undefined; + // add non-enumerable parser reference + utils.define(parsed, 'parser', this.parser); + return parsed; + }); -var _chalk = __webpack_require__(30); + return snapdragon; +}; -var _chalk2 = _interopRequireDefault(_chalk); +/** + * Create the key to use for memoization. The key is generated + * by iterating over the options and concatenating key-value pairs + * to the pattern string. + */ -var _log = __webpack_require__(36); +utils.createKey = function(pattern, options) { + if (utils.typeOf(options) !== 'object') { + return pattern; + } + var val = pattern; + var keys = Object.keys(options); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + val += ';' + key + '=' + String(options[key]); + } + return val; +}; -var _parallelize = __webpack_require__(85); +/** + * Cast `val` to an array + * @return {Array} + */ -var _projects = __webpack_require__(42); +utils.arrayify = function(val) { + if (typeof val === 'string') return [val]; + return val ? (Array.isArray(val) ? val : [val]) : []; +}; -var _watch = __webpack_require__(238); +/** + * Return true if `val` is a non-empty string + */ -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +utils.isString = function(val) { + return typeof val === 'string'; +}; -function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ +/** + * Return true if `val` is a non-empty string + */ +utils.isObject = function(val) { + return utils.typeOf(val) === 'object'; +}; /** - * Name of the script in the package/project package.json file to run during `kbn watch`. + * Returns true if the given `str` has special characters */ -const watchScriptName = 'kbn:watch'; + +utils.hasSpecialChars = function(str) { + return /(?:(?:(^|\/)[!.])|[*?+()|\[\]{}]|[+@]\()/.test(str); +}; + /** - * Name of the Kibana project. + * Escape regex characters in the given string */ -const kibanaProjectName = 'kibana'; + +utils.escapeRegex = function(str) { + return str.replace(/[-[\]{}()^$|*+?.\\\/\s]/g, '\\$&'); +}; + /** - * Command that traverses through list of available projects/packages that have `kbn:watch` script in their - * package.json files, groups them into topology aware batches and then processes theses batches one by one - * running `kbn:watch` scripts in parallel within the same batch. + * Normalize slashes in the given filepath. * - * Command internally relies on the fact that most of the build systems that are triggered by `kbn:watch` - * will emit special "marker" once build/watch process is ready that we can use as completion condition for - * the `kbn:watch` script and eventually for the entire batch. Currently we support completion "markers" for - * `webpack` and `tsc` only, for the rest we rely on predefined timeouts. + * @param {String} `filepath` + * @return {String} */ -const WatchCommand = exports.WatchCommand = { - description: 'Runs `kbn:watch` script for every project.', - name: 'watch', - run(projects, projectGraph) { - return _asyncToGenerator(function* () { - const projectsToWatch = new Map(); - for (const project of projects.values()) { - // We can't watch project that doesn't have `kbn:watch` script. - if (project.hasScript(watchScriptName)) { - projectsToWatch.set(project.name, project); - } - } - if (projectsToWatch.size === 0) { - _log.log.write(_chalk2.default.red(`\nThere are no projects to watch found. Make sure that projects define 'kbn:watch' script in 'package.json'.\n`)); - return; - } - const projectNames = Array.from(projectsToWatch.keys()); - _log.log.write(_chalk2.default.bold(_chalk2.default.green(`Running ${watchScriptName} scripts for [${projectNames.join(', ')}].`))); - // Kibana should always be run the last, so we don't rely on automatic - // topological batching and push it to the last one-entry batch manually. - const shouldWatchKibanaProject = projectsToWatch.delete(kibanaProjectName); - const batchedProjects = (0, _projects.topologicallyBatchProjects)(projectsToWatch, projectGraph); - if (shouldWatchKibanaProject) { - batchedProjects.push([projects.get(kibanaProjectName)]); - } - yield (0, _parallelize.parallelizeBatches)(batchedProjects, (() => { - var _ref = _asyncToGenerator(function* (pkg) { - const completionHint = yield (0, _watch.waitUntilWatchIsReady)(pkg.runScriptStreaming(watchScriptName).stdout); - _log.log.write(_chalk2.default.bold(`[${_chalk2.default.green(pkg.name)}] Initial build completed (${completionHint}).`)); - }); - return function (_x) { - return _ref.apply(this, arguments); - }; - })()); - })(); - } +utils.toPosixPath = function(str) { + return str.replace(/\\+/g, '/'); }; -/***/ }), -/* 238 */ -/***/ (function(module, exports, __webpack_require__) { +/** + * Strip backslashes before special characters in a string. + * + * @param {String} `str` + * @return {String} + */ -"use strict"; +utils.unescape = function(str) { + return utils.toPosixPath(str.replace(/\\(?=[*+?!.])/g, '')); +}; +/** + * Strip the prefix from a filepath + * @param {String} `fp` + * @return {String} + */ -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.waitUntilWatchIsReady = waitUntilWatchIsReady; +utils.stripPrefix = function(str) { + if (str.charAt(0) !== '.') { + return str; + } + var ch = str.charAt(1); + if (utils.isSlash(ch)) { + return str.slice(2); + } + return str; +}; + +/** + * Returns true if the given str is an escaped or + * unescaped path character + */ -var _rxjs = __webpack_require__(263); +utils.isSlash = function(str) { + return str === '/' || str === '\\/' || str === '\\' || str === '\\\\'; +}; -var Rx = _interopRequireWildcard(_rxjs); +/** + * Returns a function that returns true if the given + * pattern matches or contains a `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ + +utils.matchPath = function(pattern, options) { + return (options && options.contains) + ? utils.containsPattern(pattern, options) + : utils.equalsPattern(pattern, options); +}; -var _operators = __webpack_require__(262); +/** + * Returns true if the given (original) filepath or unixified path are equal + * to the given pattern. + */ -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +utils._equals = function(filepath, unixPath, pattern) { + return pattern === filepath || pattern === unixPath; +}; /** - * Number of milliseconds we wait before we fall back to the default watch handler. + * Returns true if the given (original) filepath or unixified path contain + * the given pattern. */ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at + +utils._contains = function(filepath, unixPath, pattern) { + return filepath.indexOf(pattern) !== -1 || unixPath.indexOf(pattern) !== -1; +}; + +/** + * Returns a function that returns true if the given + * pattern is the same as a given `filepath` * - * http://www.apache.org/licenses/LICENSE-2.0 + * @param {String} `pattern` + * @return {Function} + */ + +utils.equalsPattern = function(pattern, options) { + var unixify = utils.unixify(options); + options = options || {}; + + return function fn(filepath) { + var equal = utils._equals(filepath, unixify(filepath), pattern); + if (equal === true || options.nocase !== true) { + return equal; + } + var lower = filepath.toLowerCase(); + return utils._equals(lower, unixify(lower), pattern); + }; +}; + +/** + * Returns a function that returns true if the given + * pattern contains a `filepath` * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + * @param {String} `pattern` + * @return {Function} */ -const defaultHandlerDelay = 3000; + +utils.containsPattern = function(pattern, options) { + var unixify = utils.unixify(options); + options = options || {}; + + return function(filepath) { + var contains = utils._contains(filepath, unixify(filepath), pattern); + if (contains === true || options.nocase !== true) { + return contains; + } + var lower = filepath.toLowerCase(); + return utils._contains(lower, unixify(lower), pattern); + }; +}; + /** - * If default watch handler is used, then it's the number of milliseconds we wait for - * any build output before we consider watch task ready. + * Returns a function that returns true if the given + * regex matches the `filename` of a file path. + * + * @param {RegExp} `re` Matching regex + * @return {Function} */ -const defaultHandlerReadinessTimeout = 2000; -function getWatchHandlers(buildOutput$, { handlerDelay = defaultHandlerDelay, handlerReadinessTimeout = defaultHandlerReadinessTimeout }) { - const typescriptHandler = buildOutput$.pipe((0, _operators.first)(data => data.includes('$ tsc')), (0, _operators.map)(() => buildOutput$.pipe((0, _operators.first)(data => data.includes('Compilation complete.')), (0, _operators.mapTo)('tsc')))); - const webpackHandler = buildOutput$.pipe((0, _operators.first)(data => data.includes('$ webpack')), (0, _operators.map)(() => buildOutput$.pipe((0, _operators.first)(data => data.includes('Chunk Names')), (0, _operators.mapTo)('webpack')))); - const defaultHandler = Rx.of(undefined).pipe((0, _operators.delay)(handlerReadinessTimeout), (0, _operators.map)(() => buildOutput$.pipe((0, _operators.timeout)(handlerDelay), (0, _operators.catchError)(() => Rx.of('timeout'))))); - return [typescriptHandler, webpackHandler, defaultHandler]; -} -function waitUntilWatchIsReady(stream, opts = {}) { - const buildOutput$ = new Rx.Subject(); - const onDataListener = data => buildOutput$.next(data.toString('utf-8')); - const onEndListener = () => buildOutput$.complete(); - const onErrorListener = e => buildOutput$.error(e); - stream.once('end', onEndListener); - stream.once('error', onErrorListener); - stream.on('data', onDataListener); - return Rx.race(getWatchHandlers(buildOutput$, opts)).pipe((0, _operators.mergeMap)(whenReady => whenReady), (0, _operators.finalize)(() => { - stream.removeListener('data', onDataListener); - stream.removeListener('end', onEndListener); - stream.removeListener('error', onErrorListener); - buildOutput$.complete(); - })).toPromise(); -} -/***/ }), -/* 239 */ -/***/ (function(module, exports, __webpack_require__) { +utils.matchBasename = function(re) { + return function(filepath) { + return re.test(filepath) || re.test(path.basename(filepath)); + }; +}; -"use strict"; +/** + * Determines the filepath to return based on the provided options. + * @return {any} + */ +utils.value = function(str, unixify, options) { + if (options && options.unixify === false) { + return str; + } + return unixify(str); +}; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.runCommand = undefined; +/** + * Returns a function that normalizes slashes in a string to forward + * slashes, strips `./` from beginning of paths, and optionally unescapes + * special characters. + * @return {Function} + */ -let runCommand = exports.runCommand = (() => { - var _ref = _asyncToGenerator(function* (command, config) { - try { - _log.log.write(_chalk2.default.bold(`Running [${_chalk2.default.green(command.name)}] command from [${_chalk2.default.yellow(config.rootPath)}]:\n`)); - const projectPaths = (0, _config.getProjectPaths)(config.rootPath, config.options); - const projects = yield (0, _projects.getProjects)(config.rootPath, projectPaths, { - exclude: toArray(config.options.exclude), - include: toArray(config.options.include) - }); - if (projects.size === 0) { - _log.log.write(_chalk2.default.red(`There are no projects found. Double check project name(s) in '-i/--include' and '-e/--exclude' filters.\n`)); - return process.exit(1); - } - const projectGraph = (0, _projects.buildProjectGraph)(projects); - _log.log.write(_chalk2.default.bold(`Found [${_chalk2.default.green(projects.size.toString())}] projects:\n`)); - _log.log.write((0, _projects_tree.renderProjectsTree)(config.rootPath, projects)); - yield command.run(projects, projectGraph, config); - } catch (e) { - _log.log.write(_chalk2.default.bold.red(`\n[${command.name}] failed:\n`)); - if (e instanceof _errors.CliError) { - const msg = _chalk2.default.red(`CliError: ${e.message}\n`); - _log.log.write((0, _wrapAnsi2.default)(msg, 80)); - const keys = Object.keys(e.meta); - if (keys.length > 0) { - const metaOutput = keys.map(function (key) { - const value = e.meta[key]; - return `${key}: ${value}`; - }); - _log.log.write('Additional debugging info:\n'); - _log.log.write((0, _indentString2.default)(metaOutput.join('\n'), 3)); - } - } else { - _log.log.write(e.stack); - } - process.exit(1); - } - }); +utils.unixify = function(options) { + options = options || {}; + return function(filepath) { + if (utils.isWindows() || options.unixify === true) { + filepath = utils.toPosixPath(filepath); + } + if (options.stripPrefix !== false) { + filepath = utils.stripPrefix(filepath); + } + if (options.unescape === true) { + filepath = utils.unescape(filepath); + } + return filepath; + }; +}; - return function runCommand(_x, _x2) { - return _ref.apply(this, arguments); - }; -})(); -var _chalk = __webpack_require__(30); +/***/ }), +/* 432 */ +/***/ (function(module, exports) { -var _chalk2 = _interopRequireDefault(_chalk); +var toString = Object.prototype.toString; -var _indentString = __webpack_require__(240); +module.exports = function kindOf(val) { + if (val === void 0) return 'undefined'; + if (val === null) return 'null'; + + var type = typeof val; + if (type === 'boolean') return 'boolean'; + if (type === 'string') return 'string'; + if (type === 'number') return 'number'; + if (type === 'symbol') return 'symbol'; + if (type === 'function') { + return isGeneratorFn(val) ? 'generatorfunction' : 'function'; + } + + if (isArray(val)) return 'array'; + if (isBuffer(val)) return 'buffer'; + if (isArguments(val)) return 'arguments'; + if (isDate(val)) return 'date'; + if (isError(val)) return 'error'; + if (isRegexp(val)) return 'regexp'; + + switch (ctorName(val)) { + case 'Symbol': return 'symbol'; + case 'Promise': return 'promise'; + + // Set, Map, WeakSet, WeakMap + case 'WeakMap': return 'weakmap'; + case 'WeakSet': return 'weakset'; + case 'Map': return 'map'; + case 'Set': return 'set'; + + // 8-bit typed arrays + case 'Int8Array': return 'int8array'; + case 'Uint8Array': return 'uint8array'; + case 'Uint8ClampedArray': return 'uint8clampedarray'; + + // 16-bit typed arrays + case 'Int16Array': return 'int16array'; + case 'Uint16Array': return 'uint16array'; + + // 32-bit typed arrays + case 'Int32Array': return 'int32array'; + case 'Uint32Array': return 'uint32array'; + case 'Float32Array': return 'float32array'; + case 'Float64Array': return 'float64array'; + } + + if (isGeneratorObj(val)) { + return 'generator'; + } + + // Non-plain objects + type = toString.call(val); + switch (type) { + case '[object Object]': return 'object'; + // iterators + case '[object Map Iterator]': return 'mapiterator'; + case '[object Set Iterator]': return 'setiterator'; + case '[object String Iterator]': return 'stringiterator'; + case '[object Array Iterator]': return 'arrayiterator'; + } + + // other + return type.slice(8, -1).toLowerCase().replace(/\s/g, ''); +}; -var _indentString2 = _interopRequireDefault(_indentString); +function ctorName(val) { + return val.constructor ? val.constructor.name : null; +} -var _wrapAnsi = __webpack_require__(241); +function isArray(val) { + if (Array.isArray) return Array.isArray(val); + return val instanceof Array; +} -var _wrapAnsi2 = _interopRequireDefault(_wrapAnsi); +function isError(val) { + return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number'); +} -var _config = __webpack_require__(91); +function isDate(val) { + if (val instanceof Date) return true; + return typeof val.toDateString === 'function' + && typeof val.getDate === 'function' + && typeof val.setDate === 'function'; +} -var _errors = __webpack_require__(88); +function isRegexp(val) { + if (val instanceof RegExp) return true; + return typeof val.flags === 'string' + && typeof val.ignoreCase === 'boolean' + && typeof val.multiline === 'boolean' + && typeof val.global === 'boolean'; +} -var _log = __webpack_require__(36); +function isGeneratorFn(name, val) { + return ctorName(name) === 'GeneratorFunction'; +} -var _projects = __webpack_require__(42); +function isGeneratorObj(val) { + return typeof val.throw === 'function' + && typeof val.return === 'function' + && typeof val.next === 'function'; +} -var _projects_tree = __webpack_require__(248); +function isArguments(val) { + try { + if (typeof val.length === 'number' && typeof val.callee === 'function') { + return true; + } + } catch (err) { + if (err.message.indexOf('callee') !== -1) { + return true; + } + } + return false; +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/** + * If you need to support Safari 5-7 (8-10 yr-old browser), + * take a look at https://github.com/feross/is-buffer + */ -function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ +function isBuffer(val) { + if (val.constructor && typeof val.constructor.isBuffer === 'function') { + return val.constructor.isBuffer(val); + } + return false; +} -function toArray(value) { - if (value == null) { - return []; +/***/ }), +/* 433 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +var readdir = __webpack_require__(108); +var reader_1 = __webpack_require__(111); +var ReaderAsync = /** @class */ (function (_super) { + __extends(ReaderAsync, _super); + function ReaderAsync() { + return _super !== null && _super.apply(this, arguments) || this; } - return Array.isArray(value) ? value : [value]; -} + /** + * Returns founded paths. + */ + ReaderAsync.prototype.api = function (root, options) { + return readdir.readdirStreamStat(root, options); + }; + /** + * Use sync API to read entries for Task. + */ + ReaderAsync.prototype.read = function (task) { + var _this = this; + var root = this.getRootDirectory(task); + var options = this.getReaderOptions(task); + var entries = []; + return new Promise(function (resolve, reject) { + var stream = _this.api(root, options); + stream.on('error', function (err) { + _this.isEnoentCodeError(err) ? resolve([]) : reject(err); + stream.pause(); + }); + stream.on('data', function (entry) { return entries.push(_this.transform(entry)); }); + stream.on('end', function () { return resolve(entries); }); + }); + }; + return ReaderAsync; +}(reader_1.default)); +exports.default = ReaderAsync; + /***/ }), -/* 240 */ +/* 434 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = (str, count, opts) => { - // Support older versions: use the third parameter as options.indent - // TODO: Remove the workaround in the next major version - const options = typeof opts === 'object' ? Object.assign({indent: ' '}, opts) : {indent: opts || ' '}; - count = count === undefined ? 1 : count; - if (typeof str !== 'string') { - throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof str}\``); - } +module.exports = readdirSync; - if (typeof count !== 'number') { - throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof count}\``); - } +const DirectoryReader = __webpack_require__(109); - if (typeof options.indent !== 'string') { - throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\``); - } +let syncFacade = { + fs: __webpack_require__(438), + forEach: __webpack_require__(439), + sync: true +}; - if (count === 0) { - return str; - } +/** + * Returns the buffered output from a synchronous {@link DirectoryReader}. + * + * @param {string} dir + * @param {object} [options] + * @param {object} internalOptions + */ +function readdirSync (dir, options, internalOptions) { + internalOptions.facade = syncFacade; - const regex = options.includeEmptyLines ? /^/mg : /^(?!\s*$)/mg; - return str.replace(regex, options.indent.repeat(count)); + let reader = new DirectoryReader(dir, options, internalOptions); + let stream = reader.stream; + + let results = []; + let data = stream.read(); + while (data !== null) { + results.push(data); + data = stream.read(); + } + + return results; } -; /***/ }), -/* 241 */ +/* 435 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const stringWidth = __webpack_require__(242); -const stripAnsi = __webpack_require__(246); - -const ESCAPES = new Set([ - '\u001B', - '\u009B' -]); -const END_CODE = 39; +const path = __webpack_require__(5); +const globToRegExp = __webpack_require__(436); -const ESCAPE_CODES = new Map([ - [0, 0], - [1, 22], - [2, 22], - [3, 23], - [4, 24], - [7, 27], - [8, 28], - [9, 29], - [30, 39], - [31, 39], - [32, 39], - [33, 39], - [34, 39], - [35, 39], - [36, 39], - [37, 39], - [90, 39], - [40, 49], - [41, 49], - [42, 49], - [43, 49], - [44, 49], - [45, 49], - [46, 49], - [47, 49] -]); +module.exports = normalizeOptions; -const wrapAnsi = code => `${ESCAPES.values().next().value}[${code}m`; +let isWindows = /^win/.test(process.platform); -// Calculate the length of words split on ' ', ignoring -// the extra characters added by ansi escape codes -const wordLengths = str => str.split(' ').map(s => stringWidth(s)); +/** + * @typedef {Object} FSFacade + * @property {fs.readdir} readdir + * @property {fs.stat} stat + * @property {fs.lstat} lstat + */ -// Wrap a long word across multiple rows -// Ansi escape codes do not count towards length -const wrapWord = (rows, word, cols) => { - const arr = Array.from(word); +/** + * Validates and normalizes the options argument + * + * @param {object} [options] - User-specified options, if any + * @param {object} internalOptions - Internal options that aren't part of the public API + * + * @param {number|boolean|function} [options.deep] + * The number of directories to recursively traverse. Any falsy value or negative number will + * default to zero, so only the top-level contents will be returned. Set to `true` or `Infinity` + * to traverse all subdirectories. Or provide a function that accepts a {@link fs.Stats} object + * and returns a truthy value if the directory's contents should be crawled. + * + * @param {function|string|RegExp} [options.filter] + * A function that accepts a {@link fs.Stats} object and returns a truthy value if the data should + * be returned. Or a RegExp or glob string pattern, to filter by file name. + * + * @param {string} [options.sep] + * The path separator to use. By default, the OS-specific separator will be used, but this can be + * set to a specific value to ensure consistency across platforms. + * + * @param {string} [options.basePath] + * The base path to prepend to each result. If empty, then all results will be relative to `dir`. + * + * @param {FSFacade} [options.fs] + * Synchronous or asynchronous facades for Node.js File System module + * + * @param {object} [internalOptions.facade] + * Synchronous or asynchronous facades for various methods, including for the Node.js File System module + * + * @param {boolean} [internalOptions.emit] + * Indicates whether the reader should emit "file", "directory", and "symlink" events + * + * @param {boolean} [internalOptions.stats] + * Indicates whether the reader should emit {@link fs.Stats} objects instead of path strings + * + * @returns {object} + */ +function normalizeOptions (options, internalOptions) { + if (options === null || options === undefined) { + options = {}; + } + else if (typeof options !== 'object') { + throw new TypeError('options must be an object'); + } - let insideEscape = false; - let visible = stringWidth(stripAnsi(rows[rows.length - 1])); + let recurseDepth, recurseFn, recurseRegExp, recurseGlob, deep = options.deep; + if (deep === null || deep === undefined) { + recurseDepth = 0; + } + else if (typeof deep === 'boolean') { + recurseDepth = deep ? Infinity : 0; + } + else if (typeof deep === 'number') { + if (deep < 0 || isNaN(deep)) { + throw new Error('options.deep must be a positive number'); + } + else if (Math.floor(deep) !== deep) { + throw new Error('options.deep must be an integer'); + } + else { + recurseDepth = deep; + } + } + else if (typeof deep === 'function') { + recurseDepth = Infinity; + recurseFn = deep; + } + else if (deep instanceof RegExp) { + recurseDepth = Infinity; + recurseRegExp = deep; + } + else if (typeof deep === 'string' && deep.length > 0) { + recurseDepth = Infinity; + recurseGlob = globToRegExp(deep, { extended: true, globstar: true }); + } + else { + throw new TypeError('options.deep must be a boolean, number, function, regular expression, or glob pattern'); + } - for (const item of arr.entries()) { - const i = item[0]; - const char = item[1]; - const charLength = stringWidth(char); + let filterFn, filterRegExp, filterGlob, filter = options.filter; + if (filter !== null && filter !== undefined) { + if (typeof filter === 'function') { + filterFn = filter; + } + else if (filter instanceof RegExp) { + filterRegExp = filter; + } + else if (typeof filter === 'string' && filter.length > 0) { + filterGlob = globToRegExp(filter, { extended: true, globstar: true }); + } + else { + throw new TypeError('options.filter must be a function, regular expression, or glob pattern'); + } + } - if (visible + charLength <= cols) { - rows[rows.length - 1] += char; - } else { - rows.push(char); - visible = 0; - } + let sep = options.sep; + if (sep === null || sep === undefined) { + sep = path.sep; + } + else if (typeof sep !== 'string') { + throw new TypeError('options.sep must be a string'); + } - if (ESCAPES.has(char)) { - insideEscape = true; - } else if (insideEscape && char === 'm') { - insideEscape = false; - continue; - } + let basePath = options.basePath; + if (basePath === null || basePath === undefined) { + basePath = ''; + } + else if (typeof basePath === 'string') { + // Append a path separator to the basePath, if necessary + if (basePath && basePath.substr(-1) !== sep) { + basePath += sep; + } + } + else { + throw new TypeError('options.basePath must be a string'); + } - if (insideEscape) { - continue; - } + // Convert the basePath to POSIX (forward slashes) + // so that glob pattern matching works consistently, even on Windows + let posixBasePath = basePath; + if (posixBasePath && sep !== '/') { + posixBasePath = posixBasePath.replace(new RegExp('\\' + sep, 'g'), '/'); - visible += charLength; + /* istanbul ignore if */ + if (isWindows) { + // Convert Windows root paths (C:\) and UNCs (\\) to POSIX root paths + posixBasePath = posixBasePath.replace(/^([a-zA-Z]\:\/|\/\/)/, '/'); + } + } - if (visible === cols && i < arr.length - 1) { - rows.push(''); - visible = 0; - } - } + // Determine which facade methods to use + let facade; + if (options.fs === null || options.fs === undefined) { + // The user didn't provide their own facades, so use our internal ones + facade = internalOptions.facade; + } + else if (typeof options.fs === 'object') { + // Merge the internal facade methods with the user-provided `fs` facades + facade = Object.assign({}, internalOptions.facade); + facade.fs = Object.assign({}, internalOptions.facade.fs, options.fs); + } + else { + throw new TypeError('options.fs must be an object'); + } - // It's possible that the last row we copy over is only - // ansi escape characters, handle this edge-case - if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) { - rows[rows.length - 2] += rows.pop(); - } -}; + return { + recurseDepth, + recurseFn, + recurseRegExp, + recurseGlob, + filterFn, + filterRegExp, + filterGlob, + sep, + basePath, + posixBasePath, + facade, + emit: !!internalOptions.emit, + stats: !!internalOptions.stats, + }; +} -// The wrap-ansi module can be invoked -// in either 'hard' or 'soft' wrap mode -// -// 'hard' will never allow a string to take up more -// than cols characters -// -// 'soft' allows long words to expand past the column length -const exec = (str, cols, opts) => { - const options = opts || {}; - if (str.trim() === '') { - return options.trim === false ? str : str.trim(); - } +/***/ }), +/* 436 */ +/***/ (function(module, exports) { - let pre = ''; - let ret = ''; - let escapeCode; +module.exports = function (glob, opts) { + if (typeof glob !== 'string') { + throw new TypeError('Expected a string'); + } - const lengths = wordLengths(str); - const words = str.split(' '); - const rows = ['']; + var str = String(glob); - for (const item of Array.from(words).entries()) { - const i = item[0]; - const word = item[1]; + // The regexp we are building, as a string. + var reStr = ""; - rows[rows.length - 1] = options.trim === false ? rows[rows.length - 1] : rows[rows.length - 1].trim(); - let rowLength = stringWidth(rows[rows.length - 1]); + // Whether we are matching so called "extended" globs (like bash) and should + // support single character matching, matching ranges of characters, group + // matching, etc. + var extended = opts ? !!opts.extended : false; - if (rowLength || word === '') { - if (rowLength === cols && options.wordWrap === false) { - // If we start with a new word but the current row length equals the length of the columns, add a new row - rows.push(''); - rowLength = 0; - } + // When globstar is _false_ (default), '/foo/*' is translated a regexp like + // '^\/foo\/.*$' which will match any string beginning with '/foo/' + // When globstar is _true_, '/foo/*' is translated to regexp like + // '^\/foo\/[^/]*$' which will match any string beginning with '/foo/' BUT + // which does not have a '/' to the right of it. + // E.g. with '/foo/*' these will match: '/foo/bar', '/foo/bar.txt' but + // these will not '/foo/bar/baz', '/foo/bar/baz.txt' + // Lastely, when globstar is _true_, '/foo/**' is equivelant to '/foo/*' when + // globstar is _false_ + var globstar = opts ? !!opts.globstar : false; - rows[rows.length - 1] += ' '; - rowLength++; - } + // If we are doing extended matching, this boolean is true when we are inside + // a group (eg {*.html,*.js}), and false otherwise. + var inGroup = false; - // In 'hard' wrap mode, the length of a line is - // never allowed to extend past 'cols' - if (lengths[i] > cols && options.hard) { - if (rowLength) { - rows.push(''); - } - wrapWord(rows, word, cols); - continue; - } + // RegExp flags (eg "i" ) to pass in to RegExp constructor. + var flags = opts && typeof( opts.flags ) === "string" ? opts.flags : ""; - if (rowLength + lengths[i] > cols && rowLength > 0) { - if (options.wordWrap === false && rowLength < cols) { - wrapWord(rows, word, cols); - continue; - } + var c; + for (var i = 0, len = str.length; i < len; i++) { + c = str[i]; - rows.push(''); - } + switch (c) { + case "\\": + case "/": + case "$": + case "^": + case "+": + case ".": + case "(": + case ")": + case "=": + case "!": + case "|": + reStr += "\\" + c; + break; - if (rowLength + lengths[i] > cols && options.wordWrap === false) { - wrapWord(rows, word, cols); - continue; - } + case "?": + if (extended) { + reStr += "."; + break; + } - rows[rows.length - 1] += word; - } + case "[": + case "]": + if (extended) { + reStr += c; + break; + } - pre = rows.map(r => options.trim === false ? r : r.trim()).join('\n'); + case "{": + if (extended) { + inGroup = true; + reStr += "("; + break; + } - for (const item of Array.from(pre).entries()) { - const i = item[0]; - const char = item[1]; + case "}": + if (extended) { + inGroup = false; + reStr += ")"; + break; + } - ret += char; + case ",": + if (inGroup) { + reStr += "|"; + break; + } + reStr += "\\" + c; + break; - if (ESCAPES.has(char)) { - const code = parseFloat(/\d[^m]*/.exec(pre.slice(i, i + 4))); - escapeCode = code === END_CODE ? null : code; - } + case "*": + // Move over all consecutive "*"'s. + // Also store the previous and next characters + var prevChar = str[i - 1]; + var starCount = 1; + while(str[i + 1] === "*") { + starCount++; + i++; + } + var nextChar = str[i + 1]; - const code = ESCAPE_CODES.get(Number(escapeCode)); + if (!globstar) { + // globstar is disabled, so treat any number of "*" as one + reStr += ".*"; + } else { + // globstar is enabled, so determine if this is a globstar segment + var isGlobstar = starCount > 1 // multiple "*"'s + && (prevChar === "/" || prevChar === undefined) // from the start of the segment + && (nextChar === "/" || nextChar === undefined) // to the end of the segment + + if (isGlobstar) { + // it's a globstar, so match zero or more path segments + reStr += "(?:[^/]*(?:\/|$))*"; + i++; // move over the "/" + } else { + // it's not a globstar, so only match one path segment + reStr += "[^/]*"; + } + } + break; - if (escapeCode && code) { - if (pre[i + 1] === '\n') { - ret += wrapAnsi(code); - } else if (char === '\n') { - ret += wrapAnsi(escapeCode); - } - } - } + default: + reStr += c; + } + } - return ret; -}; + // When regexp 'g' flag is specified don't + // constrain the regular expression with ^ & $ + if (!flags || !~flags.indexOf('g')) { + reStr = "^" + reStr + "$"; + } -// For each newline, invoke the method separately -module.exports = (str, cols, opts) => { - return String(str) - .normalize() - .split('\n') - .map(line => exec(line, cols, opts)) - .join('\n'); + return new RegExp(reStr, flags); }; /***/ }), -/* 242 */ +/* 437 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const stripAnsi = __webpack_require__(243); -const isFullwidthCodePoint = __webpack_require__(245); -module.exports = str => { - if (typeof str !== 'string' || str.length === 0) { - return 0; - } +const call = __webpack_require__(110); - str = stripAnsi(str); +module.exports = stat; - let width = 0; +/** + * Retrieves the {@link fs.Stats} for the given path. If the path is a symbolic link, + * then the Stats of the symlink's target are returned instead. If the symlink is broken, + * then the Stats of the symlink itself are returned. + * + * @param {object} fs - Synchronous or Asynchronouse facade for the "fs" module + * @param {string} path - The path to return stats for + * @param {function} callback + */ +function stat (fs, path, callback) { + let isSymLink = false; - for (let i = 0; i < str.length; i++) { - const code = str.codePointAt(i); + call.safe(fs.lstat, path, (err, lstats) => { + if (err) { + // fs.lstat threw an eror + return callback(err); + } - // Ignore control characters - if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { - continue; - } + try { + isSymLink = lstats.isSymbolicLink(); + } + catch (err2) { + // lstats.isSymbolicLink() threw an error + // (probably because fs.lstat returned an invalid result) + return callback(err2); + } - // Ignore combining characters - if (code >= 0x300 && code <= 0x36F) { - continue; - } + if (isSymLink) { + // Try to resolve the symlink + symlinkStat(fs, path, lstats, callback); + } + else { + // It's not a symlink, so return the stats as-is + callback(null, lstats); + } + }); +} - // Surrogates - if (code > 0xFFFF) { - i++; - } +/** + * Retrieves the {@link fs.Stats} for the target of the given symlink. + * If the symlink is broken, then the Stats of the symlink itself are returned. + * + * @param {object} fs - Synchronous or Asynchronouse facade for the "fs" module + * @param {string} path - The path of the symlink to return stats for + * @param {object} lstats - The stats of the symlink + * @param {function} callback + */ +function symlinkStat (fs, path, lstats, callback) { + call.safe(fs.stat, path, (err, stats) => { + if (err) { + // The symlink is broken, so return the stats for the link itself + return callback(null, lstats); + } - width += isFullwidthCodePoint(code) ? 2 : 1; - } + try { + // Return the stats for the resolved symlink target, + // and override the `isSymbolicLink` method to indicate that it's a symlink + stats.isSymbolicLink = () => true; + } + catch (err2) { + // Setting stats.isSymbolicLink threw an error + // (probably because fs.stat returned an invalid result) + return callback(err2); + } - return width; -}; + callback(null, stats); + }); +} /***/ }), -/* 243 */ +/* 438 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const ansiRegex = __webpack_require__(244); -module.exports = input => typeof input === 'string' ? input.replace(ansiRegex(), '') : input; +const fs = __webpack_require__(13); +const call = __webpack_require__(110); +/** + * A facade around {@link fs.readdirSync} that allows it to be called + * the same way as {@link fs.readdir}. + * + * @param {string} dir + * @param {function} callback + */ +exports.readdir = function (dir, callback) { + // Make sure the callback is only called once + callback = call.once(callback); -/***/ }), -/* 244 */ -/***/ (function(module, exports, __webpack_require__) { + try { + let items = fs.readdirSync(dir); + callback(null, items); + } + catch (err) { + callback(err); + } +}; -"use strict"; +/** + * A facade around {@link fs.statSync} that allows it to be called + * the same way as {@link fs.stat}. + * + * @param {string} path + * @param {function} callback + */ +exports.stat = function (path, callback) { + // Make sure the callback is only called once + callback = call.once(callback); + try { + let stats = fs.statSync(path); + callback(null, stats); + } + catch (err) { + callback(err); + } +}; -module.exports = () => { - const pattern = [ - '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\\u0007)', - '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))' - ].join('|'); +/** + * A facade around {@link fs.lstatSync} that allows it to be called + * the same way as {@link fs.lstat}. + * + * @param {string} path + * @param {function} callback + */ +exports.lstat = function (path, callback) { + // Make sure the callback is only called once + callback = call.once(callback); - return new RegExp(pattern, 'g'); + try { + let stats = fs.lstatSync(path); + callback(null, stats); + } + catch (err) { + callback(err); + } }; /***/ }), -/* 245 */ +/* 439 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* eslint-disable yoda */ -module.exports = x => { - if (Number.isNaN(x)) { - return false; - } - // code points are derived from: - // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt - if ( - x >= 0x1100 && ( - x <= 0x115f || // Hangul Jamo - x === 0x2329 || // LEFT-POINTING ANGLE BRACKET - x === 0x232a || // RIGHT-POINTING ANGLE BRACKET - // CJK Radicals Supplement .. Enclosed CJK Letters and Months - (0x2e80 <= x && x <= 0x3247 && x !== 0x303f) || - // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A - (0x3250 <= x && x <= 0x4dbf) || - // CJK Unified Ideographs .. Yi Radicals - (0x4e00 <= x && x <= 0xa4c6) || - // Hangul Jamo Extended-A - (0xa960 <= x && x <= 0xa97c) || - // Hangul Syllables - (0xac00 <= x && x <= 0xd7a3) || - // CJK Compatibility Ideographs - (0xf900 <= x && x <= 0xfaff) || - // Vertical Forms - (0xfe10 <= x && x <= 0xfe19) || - // CJK Compatibility Forms .. Small Form Variants - (0xfe30 <= x && x <= 0xfe6b) || - // Halfwidth and Fullwidth Forms - (0xff01 <= x && x <= 0xff60) || - (0xffe0 <= x && x <= 0xffe6) || - // Kana Supplement - (0x1b000 <= x && x <= 0x1b001) || - // Enclosed Ideographic Supplement - (0x1f200 <= x && x <= 0x1f251) || - // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane - (0x20000 <= x && x <= 0x3fffd) - ) - ) { - return true; - } +module.exports = syncForEach; - return false; -}; +/** + * A facade that allows {@link Array.forEach} to be called as though it were asynchronous. + * + * @param {array} array - The array to iterate over + * @param {function} iterator - The function to call for each item in the array + * @param {function} done - The function to call when all iterators have completed + */ +function syncForEach (array, iterator, done) { + array.forEach(item => { + iterator(item, () => { + // Note: No error-handling here because this is currently only ever called + // by DirectoryReader, which never passes an `error` parameter to the callback. + // Instead, DirectoryReader emits an "error" event if an error occurs. + }); + }); + + done(); +} /***/ }), -/* 246 */ +/* 440 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const ansiRegex = __webpack_require__(247); -module.exports = input => typeof input === 'string' ? input.replace(ansiRegex(), '') : input; +module.exports = readdirAsync; +const maybe = __webpack_require__(441); +const DirectoryReader = __webpack_require__(109); -/***/ }), -/* 247 */ -/***/ (function(module, exports, __webpack_require__) { +let asyncFacade = { + fs: __webpack_require__(13), + forEach: __webpack_require__(157), + async: true +}; -"use strict"; +/** + * Returns the buffered output from an asynchronous {@link DirectoryReader}, + * via an error-first callback or a {@link Promise}. + * + * @param {string} dir + * @param {object} [options] + * @param {function} [callback] + * @param {object} internalOptions + */ +function readdirAsync (dir, options, callback, internalOptions) { + if (typeof options === 'function') { + callback = options; + options = undefined; + } + return maybe(callback, new Promise(((resolve, reject) => { + let results = []; -module.exports = () => { - const pattern = [ - '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\\u0007)', - '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))' - ].join('|'); + internalOptions.facade = asyncFacade; - return new RegExp(pattern, 'g'); -}; + let reader = new DirectoryReader(dir, options, internalOptions); + let stream = reader.stream; + + stream.on('error', err => { + reject(err); + stream.pause(); + }); + stream.on('data', result => { + results.push(result); + }); + stream.on('end', () => { + resolve(results); + }); + }))); +} /***/ }), -/* 248 */ +/* 441 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.renderProjectsTree = renderProjectsTree; +var next = (global.process && process.nextTick) || global.setImmediate || function (f) { + setTimeout(f, 0) +} -var _chalk = __webpack_require__(30); +module.exports = function maybe (cb, promise) { + if (cb) { + promise + .then(function (result) { + next(function () { cb(null, result) }) + }, function (err) { + next(function () { cb(err) }) + }) + return undefined + } + else { + return promise + } +} -var _chalk2 = _interopRequireDefault(_chalk); -var _path = __webpack_require__(7); +/***/ }), +/* 442 */ +/***/ (function(module, exports, __webpack_require__) { -var _path2 = _interopRequireDefault(_path); +"use strict"; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 +module.exports = readdirStream; + +const DirectoryReader = __webpack_require__(109); + +let streamFacade = { + fs: __webpack_require__(13), + forEach: __webpack_require__(157), + async: true +}; + +/** + * Returns the {@link stream.Readable} of an asynchronous {@link DirectoryReader}. * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. + * @param {string} dir + * @param {object} [options] + * @param {object} internalOptions */ -const projectKey = Symbol('__project'); -function renderProjectsTree(rootPath, projects) { - const projectsTree = buildProjectsTree(rootPath, projects); - return treeToString(createTreeStructure(projectsTree)); -} -function treeToString(tree) { - return [tree.name].concat(childrenToStrings(tree.children, '')).join('\n'); +function readdirStream (dir, options, internalOptions) { + internalOptions.facade = streamFacade; + + let reader = new DirectoryReader(dir, options, internalOptions); + return reader.stream; } -function childrenToStrings(tree, treePrefix) { - if (tree === undefined) { - return []; + + +/***/ }), +/* 443 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +var arrayUtils = __webpack_require__(158); +var pathUtils = __webpack_require__(444); +var patternUtils = __webpack_require__(105); +var DeepFilter = /** @class */ (function () { + function DeepFilter(options, micromatchOptions) { + this.options = options; + this.micromatchOptions = micromatchOptions; } - let strings = []; - tree.forEach((node, index) => { - const isLastNode = tree.length - 1 === index; - const nodePrefix = isLastNode ? '└── ' : '├── '; - const childPrefix = isLastNode ? ' ' : '│ '; - const childrenPrefix = treePrefix + childPrefix; - strings.push(`${treePrefix}${nodePrefix}${node.name}`); - strings = strings.concat(childrenToStrings(node.children, childrenPrefix)); - }); - return strings; -} -function createTreeStructure(tree) { - let name; - const children = []; - for (const [dir, project] of tree.entries()) { - // This is a leaf node (aka a project) - if (typeof project === 'string') { - name = _chalk2.default.green(project); - continue; - } - // If there's only one project and the key indicates it's a leaf node, we - // know that we're at a package folder that contains a package.json, so we - // "inline it" so we don't get unnecessary levels, i.e. we'll just see - // `foo` instead of `foo -> foo`. - if (project.size === 1 && project.has(projectKey)) { - const projectName = project.get(projectKey); - children.push({ - children: [], - name: dirOrProjectName(dir, projectName) - }); - continue; - } - const subtree = createTreeStructure(project); - // If the name is specified, we know there's a package at the "root" of the - // subtree itself. - if (subtree.name !== undefined) { - const projectName = subtree.name; - children.push({ - children: subtree.children, - name: dirOrProjectName(dir, projectName) - }); - continue; + /** + * Returns filter for directories. + */ + DeepFilter.prototype.getFilter = function (positive, negative) { + var _this = this; + var depth = this.getMaxDeth(positive); + var negativeRe = patternUtils.convertPatternsToRe(negative, this.micromatchOptions); + return function (entry) { return _this.filter(entry, negativeRe, depth); }; + }; + /** + * Returns true if directory must be read. + */ + DeepFilter.prototype.filter = function (entry, negativeRe, depth) { + // Skip reading, depending on the nesting level + if (!this.options.deep || this.skipByDeepOption(entry) || this.skipByPatternDepth(entry, depth)) { + return false; } - // Special-case whenever we have one child, so we don't get unnecessary - // folders in the output. E.g. instead of `foo -> bar -> baz` we get - // `foo/bar/baz` instead. - if (subtree.children && subtree.children.length === 1) { - const child = subtree.children[0]; - const newName = _chalk2.default.dim(_path2.default.join(dir.toString(), child.name)); - children.push({ - children: child.children, - name: newName - }); - continue; + // Skip reading if the directory is symlink and we don't want expand symlinks + if (this.isFollowedSymlink(entry)) { + return false; } - children.push({ - children: subtree.children, - name: _chalk2.default.dim(dir.toString()) - }); - } - return { name, children }; -} -function dirOrProjectName(dir, projectName) { - return dir === projectName ? _chalk2.default.green(dir) : _chalk2.default`{dim ${dir.toString()} ({reset.green ${projectName}})}`; -} -function buildProjectsTree(rootPath, projects) { - const tree = new Map(); - for (const project of projects.values()) { - if (rootPath === project.path) { - tree.set(projectKey, project.name); - } else { - const relativeProjectPath = _path2.default.relative(rootPath, project.path); - addProjectToTree(tree, relativeProjectPath.split(_path2.default.sep), project); + // Skip reading if the directory name starting with a period and is not expected + if (this.isFollowedDotDirectory(entry)) { + return false; } - } - return tree; -} -function addProjectToTree(tree, pathParts, project) { - if (pathParts.length === 0) { - tree.set(projectKey, project.name); - } else { - const [currentDir, ...rest] = pathParts; - if (!tree.has(currentDir)) { - tree.set(currentDir, new Map()); + // Skip by negative patterns + if (patternUtils.matchAny(entry.path, negativeRe)) { + return false; } - const subtree = tree.get(currentDir); - addProjectToTree(subtree, rest, project); - } -} + return true; + }; + /** + * Returns max depth for reading. + */ + DeepFilter.prototype.getMaxDeth = function (positive) { + var globstar = positive.some(patternUtils.hasGlobStar); + var patternDepths = positive.map(patternUtils.getDepth); + return globstar ? Infinity : arrayUtils.max(patternDepths); + }; + /** + * Returns true for dot directories if the «dot» option is enabled. + */ + DeepFilter.prototype.isFollowedDotDirectory = function (entry) { + return !this.options.dot && pathUtils.isDotDirectory(entry.path); + }; + /** + * Returns true for symlinked directories if the «followSymlinks» option is enabled. + */ + DeepFilter.prototype.isFollowedSymlink = function (entry) { + return !this.options.followSymlinkedDirectories && entry.isSymbolicLink(); + }; + /** + * Returns true when the «deep» options is number and entry depth greater that the option value. + */ + DeepFilter.prototype.skipByDeepOption = function (entry) { + return typeof this.options.deep === 'number' && entry.depth > this.options.deep; + }; + /** + * Return true when depth parameter is not an Infinity and entry depth greater that the parameter value. + */ + DeepFilter.prototype.skipByPatternDepth = function (entry, depth) { + return depth !== Infinity && entry.depth > depth; + }; + return DeepFilter; +}()); +exports.default = DeepFilter; + /***/ }), -/* 249 */ +/* 444 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Returns true if the last partial of the path starting with a period. + */ +function isDotDirectory(path) { + var pathPartials = path.split('/'); + var lastPathPartial = pathPartials[pathPartials.length - 1]; + return lastPathPartial.startsWith('.'); +} +exports.isDotDirectory = isDotDirectory; -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _build_production_projects = __webpack_require__(250); - -Object.defineProperty(exports, 'buildProductionProjects', { - enumerable: true, - get: function () { - return _build_production_projects.buildProductionProjects; - } -}); - -var _prepare_project_dependencies = __webpack_require__(261); - -Object.defineProperty(exports, 'prepareExternalProjectDependencies', { - enumerable: true, - get: function () { - return _prepare_project_dependencies.prepareExternalProjectDependencies; - } -}); /***/ }), -/* 250 */ +/* 445 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.buildProductionProjects = undefined; - -let buildProductionProjects = exports.buildProductionProjects = (() => { - var _ref = _asyncToGenerator(function* ({ kibanaRoot, buildRoots }) { - const projects = yield getProductionProjects(kibanaRoot); - const projectGraph = (0, _projects.buildProjectGraph)(projects); - const batchedProjects = (0, _projects.topologicallyBatchProjects)(projects, projectGraph); - const projectNames = [...projects.values()].map(function (project) { - return project.name; - }); - _log.log.write(`Preparing production build for [${projectNames.join(', ')}]`); - for (const batch of batchedProjects) { - for (const project of batch) { - yield deleteTarget(project); - yield buildProject(project); - for (const buildRoot of buildRoots) { - yield copyToBuild(project, kibanaRoot, buildRoot); - } +Object.defineProperty(exports, "__esModule", { value: true }); +var patternUtils = __webpack_require__(105); +var DeepFilter = /** @class */ (function () { + function DeepFilter(options, micromatchOptions) { + this.options = options; + this.micromatchOptions = micromatchOptions; + this.index = new Map(); + } + /** + * Returns filter for directories. + */ + DeepFilter.prototype.getFilter = function (positive, negative) { + var _this = this; + var positiveRe = patternUtils.convertPatternsToRe(positive, this.micromatchOptions); + var negativeRe = patternUtils.convertPatternsToRe(negative, this.micromatchOptions); + return function (entry) { return _this.filter(entry, positiveRe, negativeRe); }; + }; + /** + * Returns true if entry must be added to result. + */ + DeepFilter.prototype.filter = function (entry, positiveRe, negativeRe) { + var entryPath = entry.path; + // Exclude duplicate results + if (this.options.unique) { + if (this.isDuplicateEntry(entry)) { + return false; } + this.createIndexRecord(entry); } - }); - - return function buildProductionProjects(_x) { - return _ref.apply(this, arguments); + // Mark directory by the final slash. Need to micromatch to support «directory/**» patterns + if (entry.isDirectory()) { + entryPath += '/'; + } + // Filter directories that will be excluded by deep filter + if (entry.isDirectory() && patternUtils.matchAny(entryPath, negativeRe)) { + return false; + } + // Filter files and directories by options + if (this.onlyFileFilter(entry) || this.onlyDirectoryFilter(entry)) { + return false; + } + return patternUtils.match(entryPath, positiveRe, negativeRe); }; -})(); -/** - * Returns the subset of projects that should be built into the production - * bundle. As we copy these into Kibana's `node_modules` during the build step, - * and let Kibana's build process be responsible for installing dependencies, - * we only include Kibana's transitive _production_ dependencies. - */ - - -let getProductionProjects = (() => { - var _ref2 = _asyncToGenerator(function* (rootPath) { - const projectPaths = (0, _config.getProjectPaths)(rootPath, {}); - const projects = yield (0, _projects.getProjects)(rootPath, projectPaths); - const productionProjects = (0, _projects.includeTransitiveProjects)([projects.get('kibana')], projects, { - onlyProductionDependencies: true - }); - // We remove Kibana, as we're already building Kibana - productionProjects.delete('kibana'); - return productionProjects; - }); - - return function getProductionProjects(_x2) { - return _ref2.apply(this, arguments); + /** + * Return true if the entry already has in the cross reader index. + */ + DeepFilter.prototype.isDuplicateEntry = function (entry) { + return this.index.has(entry.path); }; -})(); + /** + * Create record in the cross reader index. + */ + DeepFilter.prototype.createIndexRecord = function (entry) { + this.index.set(entry.path, undefined); + }; + /** + * Returns true for non-files if the «onlyFiles» option is enabled. + */ + DeepFilter.prototype.onlyFileFilter = function (entry) { + return this.options.onlyFiles && !entry.isFile(); + }; + /** + * Returns true for non-directories if the «onlyDirectories» option is enabled. + */ + DeepFilter.prototype.onlyDirectoryFilter = function (entry) { + return this.options.onlyDirectories && !entry.isDirectory(); + }; + return DeepFilter; +}()); +exports.default = DeepFilter; -let deleteTarget = (() => { - var _ref3 = _asyncToGenerator(function* (project) { - const targetDir = project.targetLocation; - if (yield (0, _fs.isDirectory)(targetDir)) { - yield (0, _del2.default)(targetDir, { force: true }); - } - }); - return function deleteTarget(_x3) { - return _ref3.apply(this, arguments); +/***/ }), +/* 446 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); +Object.defineProperty(exports, "__esModule", { value: true }); +var stream = __webpack_require__(39); +var readdir = __webpack_require__(108); +var reader_1 = __webpack_require__(111); +var TransformStream = /** @class */ (function (_super) { + __extends(TransformStream, _super); + function TransformStream(reader) { + var _this = _super.call(this, { objectMode: true }) || this; + _this.reader = reader; + return _this; + } + TransformStream.prototype._transform = function (entry, _encoding, callback) { + callback(null, this.reader.transform(entry)); + }; + return TransformStream; +}(stream.Transform)); +var ReaderStream = /** @class */ (function (_super) { + __extends(ReaderStream, _super); + function ReaderStream() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** + * Returns founded paths. + */ + ReaderStream.prototype.api = function (root, options) { + return readdir.readdirStreamStat(root, options); + }; + /** + * Use stream API to read entries for Task. + */ + ReaderStream.prototype.read = function (task) { + var _this = this; + var root = this.getRootDirectory(task); + var options = this.getReaderOptions(task); + var transform = new TransformStream(this); + var readable = this.api(root, options); + return readable + .once('error', function (err) { return _this.isEnoentCodeError(err) ? null : transform.emit('error', err); }) + .pipe(transform); + }; + return ReaderStream; +}(reader_1.default)); +exports.default = ReaderStream; -let buildProject = (() => { - var _ref4 = _asyncToGenerator(function* (project) { - if (project.hasScript('build')) { - yield project.runScript('build'); - } - }); - return function buildProject(_x4) { - return _ref4.apply(this, arguments); +/***/ }), +/* 447 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); -/** - * Copy all the project's files from its "intermediate build directory" and - * into the build. The intermediate directory can either be the root of the - * project or some other location defined in the project's `package.json`. - * - * When copying all the files into the build, we exclude `node_modules` because - * we want the Kibana build to be responsible for actually installing all - * dependencies. The primary reason for allowing the Kibana build process to - * manage dependencies is that it will "dedupe" them, so we don't include - * unnecessary copies of dependencies. - */ +Object.defineProperty(exports, "__esModule", { value: true }); +var readdir = __webpack_require__(108); +var reader_1 = __webpack_require__(111); +var ReaderSync = /** @class */ (function (_super) { + __extends(ReaderSync, _super); + function ReaderSync() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** + * Returns founded paths. + */ + ReaderSync.prototype.api = function (root, options) { + return readdir.readdirSyncStat(root, options); + }; + /** + * Use sync API to read entries for Task. + */ + ReaderSync.prototype.read = function (task) { + var root = this.getRootDirectory(task); + var options = this.getReaderOptions(task); + try { + var entries = this.api(root, options); + return entries.map(this.transform, this); + } + catch (err) { + if (this.isEnoentCodeError(err)) { + return []; + } + throw err; + } + }; + return ReaderSync; +}(reader_1.default)); +exports.default = ReaderSync; -let copyToBuild = (() => { - var _ref5 = _asyncToGenerator(function* (project, kibanaRoot, buildRoot) { - // We want the package to have the same relative location within the build - const relativeProjectPath = (0, _path.relative)(kibanaRoot, project.path); - const buildProjectPath = (0, _path.resolve)(buildRoot, relativeProjectPath); - yield (0, _cpy2.default)(['**/*', '!node_modules/**'], buildProjectPath, { - cwd: project.getIntermediateBuildDirectory(), - dot: true, - nodir: true, - parents: true - }); - // If a project is using an intermediate build directory, we special-case our - // handling of `package.json`, as the project build process might have copied - // (a potentially modified) `package.json` into the intermediate build - // directory already. If so, we want to use that `package.json` as the basis - // for creating the production-ready `package.json`. If it's not present in - // the intermediate build, we fall back to using the project's already defined - // `package.json`. - const packageJson = (yield (0, _fs.isFile)((0, _path.join)(buildProjectPath, 'package.json'))) ? yield (0, _package_json.readPackageJson)(buildProjectPath) : project.json; - yield (0, _package_json.writePackageJson)(buildProjectPath, packageJson); - }); +/***/ }), +/* 448 */ +/***/ (function(module, exports, __webpack_require__) { - return function copyToBuild(_x5, _x6, _x7) { - return _ref5.apply(this, arguments); - }; -})(); +"use strict"; -var _cpy = __webpack_require__(251); +const path = __webpack_require__(5); +const arrify = __webpack_require__(133); +const pathType = __webpack_require__(122); -var _cpy2 = _interopRequireDefault(_cpy); +const getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0]; +const getPath = filepath => filepath[0] === '!' ? filepath.slice(1) : filepath; -var _del = __webpack_require__(113); +const addExtensions = (file, extensions) => { + if (path.extname(file)) { + return `**/${file}`; + } -var _del2 = _interopRequireDefault(_del); + return `**/${file}.${getExtensions(extensions)}`; +}; -var _path = __webpack_require__(7); +const getGlob = (dir, opts) => { + opts = Object.assign({}, opts); -var _config = __webpack_require__(91); + if (opts.files && !Array.isArray(opts.files)) { + throw new TypeError(`\`options.files\` must be an \`Array\`, not \`${typeof opts.files}\``); + } -var _fs = __webpack_require__(60); + if (opts.extensions && !Array.isArray(opts.extensions)) { + throw new TypeError(`\`options.extensions\` must be an \`Array\`, not \`${typeof opts.extensions}\``); + } -var _log = __webpack_require__(36); + if (opts.files && opts.extensions) { + return opts.files.map(x => path.join(dir, addExtensions(x, opts.extensions))); + } else if (opts.files) { + return opts.files.map(x => path.join(dir, `**/${x}`)); + } else if (opts.extensions) { + return [path.join(dir, `**/*.${getExtensions(opts.extensions)}`)]; + } -var _package_json = __webpack_require__(62); + return [path.join(dir, '**')]; +}; -var _projects = __webpack_require__(42); +module.exports = (input, opts) => { + return Promise.all(arrify(input).map(x => pathType.dir(getPath(x)) + .then(isDir => isDir ? getGlob(x, opts) : x))) + .then(globs => [].concat.apply([], globs)); +}; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +module.exports.sync = (input, opts) => { + const globs = arrify(input).map(x => pathType.dirSync(getPath(x)) ? getGlob(x, opts) : x); + return [].concat.apply([], globs); +}; -function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ /***/ }), -/* 251 */ +/* 449 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const EventEmitter = __webpack_require__(61); -const path = __webpack_require__(7); -const arrify = __webpack_require__(252); -const globby = __webpack_require__(253); -const cpFile = __webpack_require__(255); -const CpyError = __webpack_require__(260); - -const preprocessSrcPath = (srcPath, opts) => opts.cwd ? path.resolve(opts.cwd, srcPath) : srcPath; - -const preprocessDestPath = (srcPath, dest, opts) => { - let basename = path.basename(srcPath); - const dirname = path.dirname(srcPath); - - if (typeof opts.rename === 'string') { - basename = opts.rename; - } else if (typeof opts.rename === 'function') { - basename = opts.rename(basename); - } +const fs = __webpack_require__(13); +const path = __webpack_require__(5); +const fastGlob = __webpack_require__(134); +const gitIgnore = __webpack_require__(450); +const pify = __webpack_require__(451); +const slash = __webpack_require__(452); + +const DEFAULT_IGNORE = [ + '**/node_modules/**', + '**/bower_components/**', + '**/flow-typed/**', + '**/coverage/**', + '**/.git' +]; - if (opts.cwd) { - dest = path.resolve(opts.cwd, dest); - } +const readFileP = pify(fs.readFile); - if (opts.parents) { - return path.join(dest, dirname, basename); +const mapGitIgnorePatternTo = base => ignore => { + if (ignore.startsWith('!')) { + return '!' + path.posix.join(base, ignore.substr(1)); } - return path.join(dest, basename); + return path.posix.join(base, ignore); }; -module.exports = (src, dest, opts) => { - src = arrify(src); - opts = opts || {}; +const parseGitIgnore = (content, opts) => { + const base = slash(path.relative(opts.cwd, path.dirname(opts.fileName))); - if (src.length === 0 || !dest) { - return Promise.reject(new CpyError('`files` and `destination` required')); - } + return content + .split(/\r?\n/) + .filter(Boolean) + .filter(l => l.charAt(0) !== '#') + .map(mapGitIgnorePatternTo(base)); +}; - const progressEmitter = new EventEmitter(); - const copyStatus = new Map(); - let completedFiles = 0; - let completedSize = 0; +const reduceIgnore = files => { + return files.reduce((ignores, file) => { + ignores.add(parseGitIgnore(file.content, { + cwd: file.cwd, + fileName: file.filePath + })); + return ignores; + }, gitIgnore()); +}; - const promise = globby(src, opts) - .catch(err => { - throw new CpyError(`Cannot glob \`${src}\`: ${err.message}`, err); - }) - .then(files => { - if (files.length === 0) { - progressEmitter.emit('progress', { - totalFiles: 0, - percent: 1, - completedFiles: 0, - completedSize: 0 - }); - } +const getIsIgnoredPredecate = (ignores, cwd) => { + return p => ignores.ignores(slash(path.relative(cwd, p))); +}; - return Promise.all(files.map(srcPath => { - const from = preprocessSrcPath(srcPath, opts); - const to = preprocessDestPath(srcPath, dest, opts); +const getFile = (file, cwd) => { + const filePath = path.join(cwd, file); + return readFileP(filePath, 'utf8') + .then(content => ({ + content, + cwd, + filePath + })); +}; - return cpFile(from, to, opts) - .on('progress', event => { - const fileStatus = copyStatus.get(event.src) || {written: 0, percent: 0}; +const getFileSync = (file, cwd) => { + const filePath = path.join(cwd, file); + const content = fs.readFileSync(filePath, 'utf8'); - if (fileStatus.written !== event.written || fileStatus.percent !== event.percent) { - completedSize -= fileStatus.written; - completedSize += event.written; + return { + content, + cwd, + filePath + }; +}; - if (event.percent === 1 && fileStatus.percent !== 1) { - completedFiles++; - } +const normalizeOpts = opts => { + opts = opts || {}; + const ignore = opts.ignore || []; + const cwd = opts.cwd || process.cwd(); + return {ignore, cwd}; +}; - copyStatus.set(event.src, {written: event.written, percent: event.percent}); +module.exports = o => { + const opts = normalizeOpts(o); - progressEmitter.emit('progress', { - totalFiles: files.length, - percent: completedFiles / files.length, - completedFiles, - completedSize - }); - } - }) - .catch(err => { - throw new CpyError(`Cannot copy from \`${from}\` to \`${to}\`: ${err.message}`, err); - }); - })); - }); + return fastGlob('**/.gitignore', {ignore: DEFAULT_IGNORE.concat(opts.ignore), cwd: opts.cwd}) + .then(paths => Promise.all(paths.map(file => getFile(file, opts.cwd)))) + .then(files => reduceIgnore(files)) + .then(ignores => getIsIgnoredPredecate(ignores, opts.cwd)); +}; - promise.on = function () { - progressEmitter.on.apply(progressEmitter, arguments); - return promise; - }; +module.exports.sync = o => { + const opts = normalizeOpts(o); - return promise; + const paths = fastGlob.sync('**/.gitignore', {ignore: DEFAULT_IGNORE.concat(opts.ignore), cwd: opts.cwd}); + const files = paths.map(file => getFileSync(file, opts.cwd)); + const ignores = reduceIgnore(files); + return getIsIgnoredPredecate(ignores, opts.cwd); }; /***/ }), -/* 252 */ +/* 450 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = function (val) { - if (val === null || val === undefined) { - return []; - } - return Array.isArray(val) ? val : [val]; +var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +module.exports = function () { + return new IgnoreBase(); }; +// A simple implementation of make-array +function make_array(subject) { + return Array.isArray(subject) ? subject : [subject]; +} -/***/ }), -/* 253 */ -/***/ (function(module, exports, __webpack_require__) { +var REGEX_BLANK_LINE = /^\s+$/; +var REGEX_LEADING_EXCAPED_EXCLAMATION = /^\\\!/; +var REGEX_LEADING_EXCAPED_HASH = /^\\#/; +var SLASH = '/'; +var KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('node-ignore') +/* istanbul ignore next */ +: 'node-ignore'; -"use strict"; +var IgnoreBase = function () { + function IgnoreBase() { + _classCallCheck(this, IgnoreBase); -var Promise = __webpack_require__(114); -var arrayUnion = __webpack_require__(115); -var objectAssign = __webpack_require__(116); -var glob = __webpack_require__(43); -var pify = __webpack_require__(254); + this._rules = []; + this[KEY_IGNORE] = true; + this._initCache(); + } -var globP = pify(glob, Promise).bind(glob); + _createClass(IgnoreBase, [{ + key: '_initCache', + value: function _initCache() { + this._cache = {}; + } -function isNegative(pattern) { - return pattern[0] === '!'; -} + // @param {Array.|string|Ignore} pattern -function isString(value) { - return typeof value === 'string'; -} + }, { + key: 'add', + value: function add(pattern) { + this._added = false; -function assertPatternsInput(patterns) { - if (!patterns.every(isString)) { - throw new TypeError('patterns must be a string or an array of strings'); - } -} + if (typeof pattern === 'string') { + pattern = pattern.split(/\r?\n/g); + } -function generateGlobTasks(patterns, opts) { - patterns = [].concat(patterns); - assertPatternsInput(patterns); + make_array(pattern).forEach(this._addPattern, this); - var globTasks = []; + // Some rules have just added to the ignore, + // making the behavior changed. + if (this._added) { + this._initCache(); + } - opts = objectAssign({ - cache: Object.create(null), - statCache: Object.create(null), - realpathCache: Object.create(null), - symlinks: Object.create(null), - ignore: [] - }, opts); + return this; + } - patterns.forEach(function (pattern, i) { - if (isNegative(pattern)) { - return; - } + // legacy - var ignore = patterns.slice(i).filter(isNegative).map(function (pattern) { - return pattern.slice(1); - }); + }, { + key: 'addPattern', + value: function addPattern(pattern) { + return this.add(pattern); + } + }, { + key: '_addPattern', + value: function _addPattern(pattern) { + // #32 + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules); + this._added = true; + return; + } - globTasks.push({ - pattern: pattern, - opts: objectAssign({}, opts, { - ignore: opts.ignore.concat(ignore) - }) - }); - }); + if (this._checkPattern(pattern)) { + var rule = this._createRule(pattern); + this._added = true; + this._rules.push(rule); + } + } + }, { + key: '_checkPattern', + value: function _checkPattern(pattern) { + // > A blank line matches no files, so it can serve as a separator for readability. + return pattern && typeof pattern === 'string' && !REGEX_BLANK_LINE.test(pattern) - return globTasks; -} + // > A line starting with # serves as a comment. + && pattern.indexOf('#') !== 0; + } + }, { + key: 'filter', + value: function filter(paths) { + var _this = this; -module.exports = function (patterns, opts) { - var globTasks; + return make_array(paths).filter(function (path) { + return _this._filter(path); + }); + } + }, { + key: 'createFilter', + value: function createFilter() { + var _this2 = this; - try { - globTasks = generateGlobTasks(patterns, opts); - } catch (err) { - return Promise.reject(err); - } + return function (path) { + return _this2._filter(path); + }; + } + }, { + key: 'ignores', + value: function ignores(path) { + return !this._filter(path); + } + }, { + key: '_createRule', + value: function _createRule(pattern) { + var origin = pattern; + var negative = false; + + // > An optional prefix "!" which negates the pattern; + if (pattern.indexOf('!') === 0) { + negative = true; + pattern = pattern.substr(1); + } - return Promise.all(globTasks.map(function (task) { - return globP(task.pattern, task.opts); - })).then(function (paths) { - return arrayUnion.apply(null, paths); - }); -}; + pattern = pattern + // > Put a backslash ("\") in front of the first "!" for patterns that begin with a literal "!", for example, `"\!important!.txt"`. + .replace(REGEX_LEADING_EXCAPED_EXCLAMATION, '!') + // > Put a backslash ("\") in front of the first hash for patterns that begin with a hash. + .replace(REGEX_LEADING_EXCAPED_HASH, '#'); -module.exports.sync = function (patterns, opts) { - var globTasks = generateGlobTasks(patterns, opts); + var regex = make_regex(pattern, negative); - return globTasks.reduce(function (matches, task) { - return arrayUnion(matches, glob.sync(task.pattern, task.opts)); - }, []); -}; + return { + origin: origin, + pattern: pattern, + negative: negative, + regex: regex + }; + } -module.exports.generateGlobTasks = generateGlobTasks; + // @returns `Boolean` true if the `path` is NOT ignored -module.exports.hasMagic = function (patterns, opts) { - return [].concat(patterns).some(function (pattern) { - return glob.hasMagic(pattern, opts); - }); -}; + }, { + key: '_filter', + value: function _filter(path, slices) { + if (!path) { + return false; + } + + if (path in this._cache) { + return this._cache[path]; + } + + if (!slices) { + // path/to/a.js + // ['path', 'to', 'a.js'] + slices = path.split(SLASH); + } + + slices.pop(); + + return this._cache[path] = slices.length + // > It is not possible to re-include a file if a parent directory of that file is excluded. + // If the path contains a parent directory, check the parent first + ? this._filter(slices.join(SLASH) + SLASH, slices) && this._test(path) + + // Or only test the path + : this._test(path); + } + + // @returns {Boolean} true if a file is NOT ignored + + }, { + key: '_test', + value: function _test(path) { + // Explicitly define variable type by setting matched to `0` + var matched = 0; + + this._rules.forEach(function (rule) { + // if matched = true, then we only test negative rules + // if matched = false, then we test non-negative rules + if (!(matched ^ rule.negative)) { + matched = rule.negative ^ rule.regex.test(path); + } + }); + + return !matched; + } + }]); + + return IgnoreBase; +}(); + +// > If the pattern ends with a slash, +// > it is removed for the purpose of the following description, +// > but it would only find a match with a directory. +// > In other words, foo/ will match a directory foo and paths underneath it, +// > but will not match a regular file or a symbolic link foo +// > (this is consistent with the way how pathspec works in general in Git). +// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' +// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call +// you could use option `mark: true` with `glob` + +// '`foo/`' should not continue with the '`..`' + + +var DEFAULT_REPLACER_PREFIX = [ + +// > Trailing spaces are ignored unless they are quoted with backslash ("\") +[ +// (a\ ) -> (a ) +// (a ) -> (a) +// (a \ ) -> (a ) +/\\?\s+$/, function (match) { + return match.indexOf('\\') === 0 ? ' ' : ''; +}], + +// replace (\ ) with ' ' +[/\\\s/g, function () { + return ' '; +}], + +// Escape metacharacters +// which is written down by users but means special for regular expressions. + +// > There are 12 characters with special meanings: +// > - the backslash \, +// > - the caret ^, +// > - the dollar sign $, +// > - the period or dot ., +// > - the vertical bar or pipe symbol |, +// > - the question mark ?, +// > - the asterisk or star *, +// > - the plus sign +, +// > - the opening parenthesis (, +// > - the closing parenthesis ), +// > - and the opening square bracket [, +// > - the opening curly brace {, +// > These special characters are often called "metacharacters". +[/[\\\^$.|?*+()\[{]/g, function (match) { + return '\\' + match; +}], + +// leading slash +[ + +// > A leading slash matches the beginning of the pathname. +// > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". +// A leading slash matches the beginning of the pathname +/^\//, function () { + return '^'; +}], + +// replace special metacharacter slash after the leading slash +[/\//g, function () { + return '\\/'; +}], [ +// > A leading "**" followed by a slash means match in all directories. +// > For example, "**/foo" matches file or directory "foo" anywhere, +// > the same as pattern "foo". +// > "**/foo/bar" matches file or directory "bar" anywhere that is directly under directory "foo". +// Notice that the '*'s have been replaced as '\\*' +/^\^*\\\*\\\*\\\//, + +// '**/foo' <-> 'foo' +function () { + return '^(?:.*\\/)?'; +}]]; + +var DEFAULT_REPLACER_SUFFIX = [ +// starting +[ +// there will be no leading '/' (which has been replaced by section "leading slash") +// If starts with '**', adding a '^' to the regular expression also works +/^(?=[^\^])/, function () { + return !/\/(?!$)/.test(this) + // > If the pattern does not contain a slash /, Git treats it as a shell glob pattern + // Actually, if there is only a trailing slash, git also treats it as a shell glob pattern + ? '(?:^|\\/)' + + // > Otherwise, Git treats the pattern as a shell glob suitable for consumption by fnmatch(3) + : '^'; +}], + +// two globstars +[ +// Use lookahead assertions so that we could match more than one `'/**'` +/\\\/\\\*\\\*(?=\\\/|$)/g, + +// Zero, one or several directories +// should not use '*', or it will be replaced by the next replacer + +// Check if it is not the last `'/**'` +function (match, index, str) { + return index + 6 < str.length + + // case: /**/ + // > A slash followed by two consecutive asterisks then a slash matches zero or more directories. + // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. + // '/**/' + ? '(?:\\/[^\\/]+)*' + + // case: /** + // > A trailing `"/**"` matches everything inside. + + // #21: everything inside but it should not include the current folder + : '\\/.+'; +}], + +// intermediate wildcards +[ +// Never replace escaped '*' +// ignore rule '\*' will match the path '*' + +// 'abc.*/' -> go +// 'abc.*' -> skip this rule +/(^|[^\\]+)\\\*(?=.+)/g, + +// '*.js' matches '.js' +// '*.js' doesn't match 'abc' +function (match, p1) { + return p1 + '[^\\/]*'; +}], + +// trailing wildcard +[/(\^|\\\/)?\\\*$/, function (match, p1) { + return (p1 + // '\^': + // '/*' does not match '' + // '/*' does not match everything + + // '\\\/': + // 'abc/*' does not match 'abc/' + ? p1 + '[^/]+' + + // 'a*' matches 'a' + // 'a*' matches 'aa' + : '[^/]*') + '(?=$|\\/$)'; +}], [ +// unescape +/\\\\\\/g, function () { + return '\\'; +}]]; + +var POSITIVE_REPLACERS = [].concat(DEFAULT_REPLACER_PREFIX, [ + +// 'f' +// matches +// - /f(end) +// - /f/ +// - (start)f(end) +// - (start)f/ +// doesn't match +// - oof +// - foo +// pseudo: +// -> (^|/)f(/|$) + +// ending +[ +// 'js' will not match 'js.' +// 'ab' will not match 'abc' +/(?:[^*\/])$/, + +// 'js*' will not match 'a.js' +// 'js/' will not match 'a.js' +// 'js' will match 'a.js' and 'a.js/' +function (match) { + return match + '(?=$|\\/)'; +}]], DEFAULT_REPLACER_SUFFIX); + +var NEGATIVE_REPLACERS = [].concat(DEFAULT_REPLACER_PREFIX, [ + +// #24, #38 +// The MISSING rule of [gitignore docs](https://git-scm.com/docs/gitignore) +// A negative pattern without a trailing wildcard should not +// re-include the things inside that directory. + +// eg: +// ['node_modules/*', '!node_modules'] +// should ignore `node_modules/a.js` +[/(?:[^*])$/, function (match) { + return match + '(?=$|\\/$)'; +}]], DEFAULT_REPLACER_SUFFIX); + +// A simple cache, because an ignore rule only has only one certain meaning +var cache = {}; + +// @param {pattern} +function make_regex(pattern, negative) { + var r = cache[pattern]; + if (r) { + return r; + } + + var replacers = negative ? NEGATIVE_REPLACERS : POSITIVE_REPLACERS; + + var source = replacers.reduce(function (prev, current) { + return prev.replace(current[0], current[1].bind(pattern)); + }, pattern); + + return cache[pattern] = new RegExp(source, 'i'); +} + +// Windows +// -------------------------------------------------------------- +/* istanbul ignore if */ +if ( +// Detect `process` so that it can run in browsers. +typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) { + + var filter = IgnoreBase.prototype._filter; + var make_posix = function make_posix(str) { + return (/^\\\\\?\\/.test(str) || /[^\x00-\x80]+/.test(str) ? str : str.replace(/\\/g, '/') + ); + }; + + IgnoreBase.prototype._filter = function (path, slices) { + path = make_posix(path); + return filter.call(this, path, slices); + }; +} /***/ }), -/* 254 */ +/* 451 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var processFn = function (fn, P, opts) { - return function () { - var that = this; - var args = new Array(arguments.length); +const processFn = (fn, opts) => function () { + const P = opts.promiseModule; + const args = new Array(arguments.length); - for (var i = 0; i < arguments.length; i++) { - args[i] = arguments[i]; - } + for (let i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } - return new P(function (resolve, reject) { + return new P((resolve, reject) => { + if (opts.errorFirst) { args.push(function (err, result) { - if (err) { - reject(err); - } else if (opts.multiArgs) { - var results = new Array(arguments.length - 1); + if (opts.multiArgs) { + const results = new Array(arguments.length - 1); - for (var i = 1; i < arguments.length; i++) { + for (let i = 1; i < arguments.length; i++) { results[i - 1] = arguments[i]; } + if (err) { + results.unshift(err); + reject(results); + } else { + resolve(results); + } + } else if (err) { + reject(err); + } else { + resolve(result); + } + }); + } else { + args.push(function (result) { + if (opts.multiArgs) { + const results = new Array(arguments.length - 1); + + for (let i = 0; i < arguments.length; i++) { + results[i] = arguments[i]; + } + resolve(results); } else { resolve(result); } }); + } - fn.apply(that, args); - }); - }; + fn.apply(this, args); + }); }; -var pify = module.exports = function (obj, P, opts) { - if (typeof P !== 'function') { - opts = P; - P = Promise; - } +module.exports = (obj, opts) => { + opts = Object.assign({ + exclude: [/.+(Sync|Stream)$/], + errorFirst: true, + promiseModule: Promise + }, opts); - opts = opts || {}; - opts.exclude = opts.exclude || [/.+Sync$/]; + const filter = key => { + const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key); + return opts.include ? opts.include.some(match) : !opts.exclude.some(match); + }; - var filter = function (key) { - var match = function (pattern) { - return typeof pattern === 'string' ? key === pattern : pattern.test(key); + let ret; + if (typeof obj === 'function') { + ret = function () { + if (opts.excludeMain) { + return obj.apply(this, arguments); + } + + return processFn(obj, opts).apply(this, arguments); }; + } else { + ret = Object.create(Object.getPrototypeOf(obj)); + } - return opts.include ? opts.include.some(match) : !opts.exclude.some(match); - }; + for (const key in obj) { // eslint-disable-line guard-for-in + const x = obj[key]; + ret[key] = typeof x === 'function' && filter(key) ? processFn(x, opts) : x; + } - var ret = typeof obj === 'function' ? function () { - if (opts.excludeMain) { - return obj.apply(this, arguments); - } + return ret; +}; - return processFn(obj, P, opts).apply(this, arguments); - } : {}; - return Object.keys(obj).reduce(function (ret, key) { - var x = obj[key]; +/***/ }), +/* 452 */ +/***/ (function(module, exports, __webpack_require__) { - ret[key] = typeof x === 'function' && filter(key) ? processFn(x, P, opts) : x; +"use strict"; - return ret; - }, ret); -}; +module.exports = function (str) { + var isExtendedLengthPath = /^\\\\\?\\/.test(str); + var hasNonAscii = /[^\x00-\x80]+/.test(str); -pify.all = pify; + if (isExtendedLengthPath || hasNonAscii) { + return str; + } + + return str.replace(/\\/g, '/'); +}; /***/ }), -/* 255 */ +/* 453 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const path = __webpack_require__(7); -const fsConstants = __webpack_require__(16).constants; -const Buffer = __webpack_require__(256).Buffer; -const CpFileError = __webpack_require__(117); -const fs = __webpack_require__(258); -const ProgressEmitter = __webpack_require__(259); +const path = __webpack_require__(5); +const fsConstants = __webpack_require__(13).constants; +const {Buffer} = __webpack_require__(454); +const CpFileError = __webpack_require__(159); +const fs = __webpack_require__(456); +const ProgressEmitter = __webpack_require__(458); module.exports = (src, dest, opts) => { if (!src || !dest) { @@ -25804,8 +51187,8 @@ module.exports = (src, dest, opts) => { } }); - promise.on = function () { - progressEmitter.on.apply(progressEmitter, arguments); + promise.on = (...args) => { + progressEmitter.on(...args); return promise; }; @@ -25903,11 +51286,11 @@ module.exports.sync = (src, dest, opts) => { /***/ }), -/* 256 */ +/* 454 */ /***/ (function(module, exports, __webpack_require__) { /* eslint-disable node/no-deprecated-api */ -var buffer = __webpack_require__(257) +var buffer = __webpack_require__(455) var Buffer = buffer.Buffer // alternative to using Object.keys for old browsers @@ -25971,21 +51354,21 @@ SafeBuffer.allocUnsafeSlow = function (size) { /***/ }), -/* 257 */ +/* 455 */ /***/ (function(module, exports) { module.exports = require("buffer"); /***/ }), -/* 258 */ +/* 456 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const fs = __webpack_require__(56); -const makeDir = __webpack_require__(106); -const pify = __webpack_require__(44); -const CpFileError = __webpack_require__(117); +const fs = __webpack_require__(61); +const makeDir = __webpack_require__(126); +const pify = __webpack_require__(457); +const CpFileError = __webpack_require__(159); const fsP = pify(fs); @@ -25995,15 +51378,15 @@ exports.createWriteStream = fs.createWriteStream.bind(fs); exports.createReadStream = (path, options) => new Promise((resolve, reject) => { const read = fs.createReadStream(path, options); - read.on('error', err => { + read.once('error', err => { reject(new CpFileError(`Cannot read from \`${path}\`: ${err.message}`, err)); }); - read.on('readable', () => { + read.once('readable', () => { resolve(read); }); - read.on('end', () => { + read.once('end', () => { resolve(read); }); }); @@ -26130,12 +51513,103 @@ if (fs.copyFileSync) { /***/ }), -/* 259 */ +/* 457 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const processFn = (fn, opts) => function () { + const P = opts.promiseModule; + const args = new Array(arguments.length); + + for (let i = 0; i < arguments.length; i++) { + args[i] = arguments[i]; + } + + return new P((resolve, reject) => { + if (opts.errorFirst) { + args.push(function (err, result) { + if (opts.multiArgs) { + const results = new Array(arguments.length - 1); + + for (let i = 1; i < arguments.length; i++) { + results[i - 1] = arguments[i]; + } + + if (err) { + results.unshift(err); + reject(results); + } else { + resolve(results); + } + } else if (err) { + reject(err); + } else { + resolve(result); + } + }); + } else { + args.push(function (result) { + if (opts.multiArgs) { + const results = new Array(arguments.length - 1); + + for (let i = 0; i < arguments.length; i++) { + results[i] = arguments[i]; + } + + resolve(results); + } else { + resolve(result); + } + }); + } + + fn.apply(this, args); + }); +}; + +module.exports = (obj, opts) => { + opts = Object.assign({ + exclude: [/.+(Sync|Stream)$/], + errorFirst: true, + promiseModule: Promise + }, opts); + + const filter = key => { + const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key); + return opts.include ? opts.include.some(match) : !opts.exclude.some(match); + }; + + let ret; + if (typeof obj === 'function') { + ret = function () { + if (opts.excludeMain) { + return obj.apply(this, arguments); + } + + return processFn(obj, opts).apply(this, arguments); + }; + } else { + ret = Object.create(Object.getPrototypeOf(obj)); + } + + for (const key in obj) { // eslint-disable-line guard-for-in + const x = obj[key]; + ret[key] = typeof x === 'function' && filter(key) ? processFn(x, opts) : x; + } + + return ret; +}; + + +/***/ }), +/* 458 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const EventEmitter = __webpack_require__(61); +const EventEmitter = __webpack_require__(63); const written = new WeakMap(); @@ -26156,8 +51630,7 @@ class ProgressEmitter extends EventEmitter { } emitProgress() { - const size = this.size; - const written = this.written; + const {size, written} = this; this.emit('progress', { src: this.src, dest: this.dest, @@ -26172,12 +51645,12 @@ module.exports = ProgressEmitter; /***/ }), -/* 260 */ +/* 459 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const NestedError = __webpack_require__(118); +const NestedError = __webpack_require__(160); class CpyError extends NestedError { constructor(message, nested) { @@ -26191,7 +51664,7 @@ module.exports = CpyError; /***/ }), -/* 261 */ +/* 460 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -26231,9 +51704,9 @@ let prepareExternalProjectDependencies = exports.prepareExternalProjectDependenc }; })(); -var _package_json = __webpack_require__(62); +var _package_json = __webpack_require__(72); -var _project = __webpack_require__(101); +var _project = __webpack_require__(121); function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /* * Licensed to Elasticsearch B.V. under one or more contributor @@ -26262,20 +51735,20 @@ function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, a const isKibanaDep = depVersion => depVersion.includes('../../kibana/'); /***/ }), -/* 262 */ +/* 461 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); -// EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/node_modules/tslib/tslib.es6.js +// EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/tslib/tslib.es6.js var tslib_es6 = __webpack_require__(0); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/tryCatch.js -var tryCatch = __webpack_require__(14); +var tryCatch = __webpack_require__(16); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/errorObject.js -var errorObject = __webpack_require__(6); +var errorObject = __webpack_require__(7); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/OuterSubscriber.js var OuterSubscriber = __webpack_require__(4); @@ -26358,7 +51831,7 @@ var audit_AuditSubscriber = /*@__PURE__*/ (function (_super) { var scheduler_async = __webpack_require__(10); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/timer.js -var timer = __webpack_require__(71); +var timer = __webpack_require__(87); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/auditTime.js /** PURE_IMPORTS_START _scheduler_async,_audit,_observable_timer PURE_IMPORTS_END */ @@ -26661,7 +52134,7 @@ function dispatchBufferClose(arg) { //# sourceMappingURL=bufferTime.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/Subscription.js -var Subscription = __webpack_require__(5); +var Subscription = __webpack_require__(6); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/bufferToggle.js /** PURE_IMPORTS_START tslib,_Subscription,_util_subscribeToResult,_OuterSubscriber PURE_IMPORTS_END */ @@ -26904,7 +52377,7 @@ var catchError_CatchSubscriber = /*@__PURE__*/ (function (_super) { //# sourceMappingURL=catchError.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/combineLatest.js -var combineLatest = __webpack_require__(49); +var combineLatest = __webpack_require__(54); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/combineAll.js /** PURE_IMPORTS_START _observable_combineLatest PURE_IMPORTS_END */ @@ -26918,7 +52391,7 @@ function combineAll(project) { var isArray = __webpack_require__(11); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/from.js + 5 modules -var from = __webpack_require__(15); +var from = __webpack_require__(17); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/combineLatest.js /** PURE_IMPORTS_START _util_isArray,_observable_combineLatest,_observable_from PURE_IMPORTS_END */ @@ -26943,7 +52416,7 @@ function combineLatest_combineLatest() { //# sourceMappingURL=combineLatest.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/concat.js -var concat = __webpack_require__(26); +var concat = __webpack_require__(29); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/concat.js /** PURE_IMPORTS_START _observable_concat PURE_IMPORTS_END */ @@ -26958,10 +52431,10 @@ function concat_concat() { //# sourceMappingURL=concat.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/concatAll.js -var concatAll = __webpack_require__(68); +var concatAll = __webpack_require__(84); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/mergeMap.js -var mergeMap = __webpack_require__(27); +var mergeMap = __webpack_require__(31); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/concatMap.js /** PURE_IMPORTS_START _mergeMap PURE_IMPORTS_END */ @@ -27228,7 +52701,7 @@ function isDate(value) { //# sourceMappingURL=isDate.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/Notification.js -var Notification = __webpack_require__(22); +var Notification = __webpack_require__(24); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/delay.js /** PURE_IMPORTS_START tslib,_scheduler_async,_util_isDate,_Subscriber,_Notification PURE_IMPORTS_END */ @@ -27620,7 +53093,7 @@ function distinctUntilKeyChanged(key, compare) { //# sourceMappingURL=distinctUntilKeyChanged.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/ArgumentOutOfRangeError.js -var ArgumentOutOfRangeError = __webpack_require__(28); +var ArgumentOutOfRangeError = __webpack_require__(32); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/filter.js /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ @@ -27668,10 +53141,10 @@ var filter_FilterSubscriber = /*@__PURE__*/ (function (_super) { //# sourceMappingURL=filter.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/noop.js -var noop = __webpack_require__(20); +var noop = __webpack_require__(21); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/isFunction.js -var isFunction = __webpack_require__(29); +var isFunction = __webpack_require__(33); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/tap.js /** PURE_IMPORTS_START tslib,_Subscriber,_util_noop,_util_isFunction PURE_IMPORTS_END */ @@ -27751,7 +53224,7 @@ var tap_TapSubscriber = /*@__PURE__*/ (function (_super) { //# sourceMappingURL=tap.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/EmptyError.js -var EmptyError = __webpack_require__(31); +var EmptyError = __webpack_require__(34); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/throwIfEmpty.js /** PURE_IMPORTS_START _tap,_util_EmptyError PURE_IMPORTS_END */ @@ -27851,10 +53324,10 @@ function elementAt(index, defaultValue) { //# sourceMappingURL=elementAt.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/fromArray.js -var fromArray = __webpack_require__(17); +var fromArray = __webpack_require__(18); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/scalar.js -var scalar = __webpack_require__(53); +var scalar = __webpack_require__(58); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/endWith.js /** PURE_IMPORTS_START _observable_fromArray,_observable_scalar,_observable_empty,_observable_concat,_util_isScheduler PURE_IMPORTS_END */ @@ -27991,7 +53464,7 @@ var exhaust_SwitchFirstSubscriber = /*@__PURE__*/ (function (_super) { //# sourceMappingURL=exhaust.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/map.js -var map = __webpack_require__(13); +var map = __webpack_require__(15); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/exhaustMap.js /** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult,_map,_observable_from PURE_IMPORTS_END */ @@ -28266,7 +53739,7 @@ function findIndex(predicate, thisArg) { //# sourceMappingURL=findIndex.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/identity.js -var identity = __webpack_require__(21); +var identity = __webpack_require__(23); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/first.js /** PURE_IMPORTS_START _util_EmptyError,_filter,_take,_defaultIfEmpty,_throwIfEmpty,_util_identity PURE_IMPORTS_END */ @@ -28283,7 +53756,7 @@ function first(predicate, defaultValue) { //# sourceMappingURL=first.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/groupBy.js -var groupBy = __webpack_require__(63); +var groupBy = __webpack_require__(73); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/ignoreElements.js /** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ @@ -28572,7 +54045,7 @@ var scan_ScanSubscriber = /*@__PURE__*/ (function (_super) { //# sourceMappingURL=scan.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/pipe.js -var pipe = __webpack_require__(39); +var pipe = __webpack_require__(45); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/reduce.js /** PURE_IMPORTS_START _scan,_takeLast,_defaultIfEmpty,_util_pipe PURE_IMPORTS_END */ @@ -28606,7 +54079,7 @@ function max_max(comparer) { //# sourceMappingURL=max.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/merge.js -var merge = __webpack_require__(69); +var merge = __webpack_require__(85); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/merge.js /** PURE_IMPORTS_START _observable_merge PURE_IMPORTS_END */ @@ -28621,7 +54094,7 @@ function merge_merge() { //# sourceMappingURL=merge.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/mergeAll.js -var mergeAll = __webpack_require__(50); +var mergeAll = __webpack_require__(55); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/mergeMapTo.js /** PURE_IMPORTS_START _mergeMap PURE_IMPORTS_END */ @@ -28745,7 +54218,7 @@ function min_min(comparer) { //# sourceMappingURL=min.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/ConnectableObservable.js -var ConnectableObservable = __webpack_require__(64); +var ConnectableObservable = __webpack_require__(80); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/multicast.js /** PURE_IMPORTS_START _observable_ConnectableObservable PURE_IMPORTS_END */ @@ -28788,7 +54261,7 @@ var MulticastOperator = /*@__PURE__*/ (function () { //# sourceMappingURL=multicast.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/observeOn.js -var observeOn = __webpack_require__(66); +var observeOn = __webpack_require__(82); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/onErrorResumeNext.js /** PURE_IMPORTS_START tslib,_observable_from,_util_isArray,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ @@ -28969,7 +54442,7 @@ function publish(selector) { //# sourceMappingURL=publish.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/BehaviorSubject.js -var BehaviorSubject = __webpack_require__(65); +var BehaviorSubject = __webpack_require__(81); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/publishBehavior.js /** PURE_IMPORTS_START _BehaviorSubject,_multicast PURE_IMPORTS_END */ @@ -28981,7 +54454,7 @@ function publishBehavior(value) { //# sourceMappingURL=publishBehavior.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/AsyncSubject.js -var AsyncSubject = __webpack_require__(33); +var AsyncSubject = __webpack_require__(36); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/publishLast.js /** PURE_IMPORTS_START _AsyncSubject,_multicast PURE_IMPORTS_END */ @@ -28993,7 +54466,7 @@ function publishLast() { //# sourceMappingURL=publishLast.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/ReplaySubject.js -var ReplaySubject = __webpack_require__(46); +var ReplaySubject = __webpack_require__(51); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/publishReplay.js /** PURE_IMPORTS_START _ReplaySubject,_multicast PURE_IMPORTS_END */ @@ -29010,7 +54483,7 @@ function publishReplay(bufferSize, windowTime, selectorOrScheduler, scheduler) { //# sourceMappingURL=publishReplay.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/race.js -var race = __webpack_require__(70); +var race = __webpack_require__(86); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/race.js /** PURE_IMPORTS_START _util_isArray,_observable_race PURE_IMPORTS_END */ @@ -29289,7 +54762,7 @@ var retryWhen_RetryWhenSubscriber = /*@__PURE__*/ (function (_super) { //# sourceMappingURL=retryWhen.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/refCount.js -var operators_refCount = __webpack_require__(45); +var operators_refCount = __webpack_require__(50); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/sample.js /** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ @@ -29827,10 +55300,10 @@ function startWith() { //# sourceMappingURL=startWith.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/scheduler/asap.js + 3 modules -var asap = __webpack_require__(54); +var asap = __webpack_require__(59); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/isNumeric.js -var isNumeric = __webpack_require__(35); +var isNumeric = __webpack_require__(38); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/SubscribeOnObservable.js /** PURE_IMPORTS_START tslib,_Observable,_scheduler_asap,_util_isNumeric PURE_IMPORTS_END */ @@ -30260,7 +55733,7 @@ function throttleTime_dispatchNext(arg) { //# sourceMappingURL=throttleTime.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/defer.js -var defer = __webpack_require__(51); +var defer = __webpack_require__(56); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/timeInterval.js /** PURE_IMPORTS_START _scheduler_async,_scan,_observable_defer,_map PURE_IMPORTS_END */ @@ -30295,7 +55768,7 @@ var TimeInterval = /*@__PURE__*/ (function () { //# sourceMappingURL=timeInterval.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/TimeoutError.js -var TimeoutError = __webpack_require__(67); +var TimeoutError = __webpack_require__(83); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/timeoutWith.js /** PURE_IMPORTS_START tslib,_scheduler_async,_util_isDate,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ @@ -30368,7 +55841,7 @@ var timeoutWith_TimeoutWithSubscriber = /*@__PURE__*/ (function (_super) { //# sourceMappingURL=timeoutWith.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/throwError.js -var throwError = __webpack_require__(48); +var throwError = __webpack_require__(53); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/timeout.js /** PURE_IMPORTS_START _scheduler_async,_util_TimeoutError,_timeoutWith,_observable_throwError PURE_IMPORTS_END */ @@ -31029,7 +56502,7 @@ var withLatestFrom_WithLatestFromSubscriber = /*@__PURE__*/ (function (_super) { //# sourceMappingURL=withLatestFrom.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/zip.js -var zip = __webpack_require__(52); +var zip = __webpack_require__(57); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/zip.js /** PURE_IMPORTS_START _observable_zip PURE_IMPORTS_END */ @@ -31267,7 +56740,7 @@ function zipAll(project) { /***/ }), -/* 263 */ +/* 462 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; @@ -31277,40 +56750,40 @@ __webpack_require__.r(__webpack_exports__); var Observable = __webpack_require__(2); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/ConnectableObservable.js -var ConnectableObservable = __webpack_require__(64); +var ConnectableObservable = __webpack_require__(80); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/groupBy.js -var groupBy = __webpack_require__(63); +var groupBy = __webpack_require__(73); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/symbol/observable.js -var observable = __webpack_require__(24); +var observable = __webpack_require__(27); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/Subject.js var Subject = __webpack_require__(8); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/BehaviorSubject.js -var BehaviorSubject = __webpack_require__(65); +var BehaviorSubject = __webpack_require__(81); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/ReplaySubject.js -var ReplaySubject = __webpack_require__(46); +var ReplaySubject = __webpack_require__(51); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/AsyncSubject.js -var AsyncSubject = __webpack_require__(33); +var AsyncSubject = __webpack_require__(36); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/scheduler/asap.js + 3 modules -var asap = __webpack_require__(54); +var asap = __webpack_require__(59); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/scheduler/async.js var scheduler_async = __webpack_require__(10); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/scheduler/queue.js + 2 modules -var queue = __webpack_require__(72); +var queue = __webpack_require__(88); -// EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/node_modules/tslib/tslib.es6.js +// EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/tslib/tslib.es6.js var tslib_es6 = __webpack_require__(0); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/scheduler/AsyncAction.js + 1 modules -var AsyncAction = __webpack_require__(34); +var AsyncAction = __webpack_require__(37); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/scheduler/AnimationFrameAction.js /** PURE_IMPORTS_START tslib,_AsyncAction PURE_IMPORTS_END */ @@ -31353,7 +56826,7 @@ var AnimationFrameAction_AnimationFrameAction = /*@__PURE__*/ (function (_super) //# sourceMappingURL=AnimationFrameAction.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/scheduler/AsyncScheduler.js -var AsyncScheduler = __webpack_require__(32); +var AsyncScheduler = __webpack_require__(35); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/scheduler/AnimationFrameScheduler.js /** PURE_IMPORTS_START tslib,_AsyncScheduler PURE_IMPORTS_END */ @@ -31508,25 +56981,25 @@ var VirtualTimeScheduler_VirtualAction = /*@__PURE__*/ (function (_super) { //# sourceMappingURL=VirtualTimeScheduler.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/Scheduler.js -var Scheduler = __webpack_require__(58); +var Scheduler = __webpack_require__(69); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/Subscription.js -var Subscription = __webpack_require__(5); +var Subscription = __webpack_require__(6); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/Subscriber.js var Subscriber = __webpack_require__(1); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/Notification.js -var Notification = __webpack_require__(22); +var Notification = __webpack_require__(24); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/pipe.js -var pipe = __webpack_require__(39); +var pipe = __webpack_require__(45); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/noop.js -var noop = __webpack_require__(20); +var noop = __webpack_require__(21); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/identity.js -var identity = __webpack_require__(21); +var identity = __webpack_require__(23); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/isObservable.js /** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */ @@ -31537,22 +57010,22 @@ function isObservable(obj) { //# sourceMappingURL=isObservable.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/ArgumentOutOfRangeError.js -var ArgumentOutOfRangeError = __webpack_require__(28); +var ArgumentOutOfRangeError = __webpack_require__(32); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/EmptyError.js -var EmptyError = __webpack_require__(31); +var EmptyError = __webpack_require__(34); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/ObjectUnsubscribedError.js -var ObjectUnsubscribedError = __webpack_require__(25); +var ObjectUnsubscribedError = __webpack_require__(28); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/UnsubscriptionError.js -var UnsubscriptionError = __webpack_require__(40); +var UnsubscriptionError = __webpack_require__(46); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/TimeoutError.js -var TimeoutError = __webpack_require__(67); +var TimeoutError = __webpack_require__(83); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/operators/map.js -var map = __webpack_require__(13); +var map = __webpack_require__(15); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/isArray.js var isArray = __webpack_require__(11); @@ -31771,13 +57244,13 @@ function bindNodeCallback_dispatchError(arg) { //# sourceMappingURL=bindNodeCallback.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/combineLatest.js -var combineLatest = __webpack_require__(49); +var combineLatest = __webpack_require__(54); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/concat.js -var concat = __webpack_require__(26); +var concat = __webpack_require__(29); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/defer.js -var defer = __webpack_require__(51); +var defer = __webpack_require__(56); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/empty.js var empty = __webpack_require__(9); @@ -31865,10 +57338,10 @@ var forkJoin_ForkJoinSubscriber = /*@__PURE__*/ (function (_super) { //# sourceMappingURL=forkJoin.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/from.js + 5 modules -var from = __webpack_require__(15); +var from = __webpack_require__(17); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/isFunction.js -var isFunction = __webpack_require__(29); +var isFunction = __webpack_require__(33); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/fromEvent.js /** PURE_IMPORTS_START _Observable,_util_isArray,_util_isFunction,_operators_map PURE_IMPORTS_END */ @@ -32112,7 +57585,7 @@ function iif(condition, trueResult, falseResult) { //# sourceMappingURL=iif.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/util/isNumeric.js -var isNumeric = __webpack_require__(35); +var isNumeric = __webpack_require__(38); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/interval.js /** PURE_IMPORTS_START _Observable,_scheduler_async,_util_isNumeric PURE_IMPORTS_END */ @@ -32145,7 +57618,7 @@ function interval_dispatch(state) { //# sourceMappingURL=interval.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/merge.js -var merge = __webpack_require__(69); +var merge = __webpack_require__(85); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/never.js /** PURE_IMPORTS_START _Observable,_util_noop PURE_IMPORTS_END */ @@ -32158,7 +57631,7 @@ function never() { //# sourceMappingURL=never.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/of.js -var of = __webpack_require__(47); +var of = __webpack_require__(52); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/onErrorResumeNext.js /** PURE_IMPORTS_START _Observable,_from,_util_isArray,_empty PURE_IMPORTS_END */ @@ -32231,7 +57704,7 @@ function pairs_dispatch(state) { //# sourceMappingURL=pairs.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/race.js -var race = __webpack_require__(70); +var race = __webpack_require__(86); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/range.js /** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */ @@ -32283,10 +57756,10 @@ function range_dispatch(state) { //# sourceMappingURL=range.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/throwError.js -var throwError = __webpack_require__(48); +var throwError = __webpack_require__(53); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/timer.js -var timer = __webpack_require__(71); +var timer = __webpack_require__(87); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/using.js /** PURE_IMPORTS_START _Observable,_from,_empty PURE_IMPORTS_END */ @@ -32324,10 +57797,10 @@ function using(resourceFactory, observableFactory) { //# sourceMappingURL=using.js.map // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/observable/zip.js -var zip = __webpack_require__(52); +var zip = __webpack_require__(57); // EXTERNAL MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/internal/config.js -var config = __webpack_require__(18); +var config = __webpack_require__(19); // CONCATENATED MODULE: /Users/tiagocosta/elastic/kibana/node_modules/rxjs/_esm5/index.js /* concated harmony reexport Observable */__webpack_require__.d(__webpack_exports__, "Observable", function() { return Observable["a" /* Observable */]; }); diff --git a/packages/kbn-pm/package.json b/packages/kbn-pm/package.json index 2a415914fb93a..759122237ae39 100644 --- a/packages/kbn-pm/package.json +++ b/packages/kbn-pm/package.json @@ -14,7 +14,7 @@ "@types/cpy": "^5.1.0", "@types/dedent": "^0.7.0", "@types/del": "^3.0.0", - "@types/execa": "^0.8.1", + "@types/execa": "^0.9.0", "@types/getopts": "^2.0.0", "@types/glob": "^5.0.35", "@types/globby": "^6.1.0", @@ -25,7 +25,7 @@ "@types/log-symbols": "^2.0.0", "@types/mkdirp": "^0.5.2", "@types/ncp": "^2.0.1", - "@types/node": "^8.10.38", + "@types/node": "^10.12.12", "@types/ora": "^1.3.2", "@types/read-pkg": "^3.0.0", "@types/strip-ansi": "^3.0.0", @@ -39,10 +39,10 @@ "babel-preset-stage-3": "^6.24.1", "chalk": "^2.4.1", "cmd-shim": "^2.0.2", - "cpy": "^6.0.0", + "cpy": "^7.0.1", "dedent": "^0.7.0", "del": "^3.0.0", - "execa": "^0.9.0", + "execa": "^1.0.0", "getopts": "^2.0.0", "glob": "^7.1.2", "globby": "^8.0.1", @@ -63,6 +63,7 @@ "tempy": "^0.2.1", "ts-loader": "^5.2.2", "typescript": "^3.0.3", + "unlazy-loader": "^0.1.3", "webpack": "^4.23.1", "webpack-cli": "^3.1.2", "wrap-ansi": "^3.0.1", diff --git a/packages/kbn-pm/webpack.config.js b/packages/kbn-pm/webpack.config.js index dd103d09a7d1a..b1c8a1bf1d8f7 100644 --- a/packages/kbn-pm/webpack.config.js +++ b/packages/kbn-pm/webpack.config.js @@ -72,6 +72,21 @@ module.exports = { }, }, }, + // In order to make it work with Node 10 we had the need to upgrade + // the package cpy to a version >= 7.0.0. In this version cpy is + // using the new globby that relies in the fast-glob which relies + // in the new micromatch. The micromatch (use and class-utils) dependencies having a require + // that uses the lazy-cache which cannot be correctly extracted by webpack. + // According to the documentation we should use the unlazy-loader to solve + // this situation: https://github.com/jonschlinkert/lazy-cache#heads-up + // We can also found some issues arround this who also used unlazy-loader + // to solve this: https://github.com/micromatch/micromatch/issues/55 + { + test: /node_modules\/(use|class-utils)\/utils\.js$/, + use: { + loader: 'unlazy-loader', + }, + }, ], }, diff --git a/packages/kbn-ui-framework/package.json b/packages/kbn-ui-framework/package.json index 8d560e831699a..731550a015c0e 100644 --- a/packages/kbn-ui-framework/package.json +++ b/packages/kbn-ui-framework/package.json @@ -70,6 +70,6 @@ "webpack": "^4.23.1", "webpack-dev-server": "^3.1.10", "yeoman-generator": "1.1.1", - "yo": "2.0.3" + "yo": "2.0.5" } } diff --git a/src/cli/cluster/__mocks__/cluster.js b/src/cli/cluster/__mocks__/cluster.js index 14efc4b6f0150..1f542b775c765 100644 --- a/src/cli/cluster/__mocks__/cluster.js +++ b/src/cli/cluster/__mocks__/cluster.js @@ -50,7 +50,7 @@ class MockClusterFork extends EventEmitter { }); jest.spyOn(this, 'on'); - jest.spyOn(this, 'removeListener'); + jest.spyOn(this, 'off'); jest.spyOn(this, 'emit'); (async () => { diff --git a/src/cli/cluster/cluster_manager.test.js b/src/cli/cluster/cluster_manager.test.js index ab42c4a369bb8..0d00b41066b2d 100644 --- a/src/cli/cluster/cluster_manager.test.js +++ b/src/cli/cluster/cluster_manager.test.js @@ -41,8 +41,8 @@ describe('CLI cluster manager', () => { kill: jest.fn(), }, isDead: jest.fn().mockReturnValue(false), - removeListener: jest.fn(), - addListener: jest.fn(), + off: jest.fn(), + on: jest.fn(), send: jest.fn() }; }); @@ -105,8 +105,8 @@ describe('CLI cluster manager', () => { clusterManager = ClusterManager.create({}, {}, basePathProxyMock); - jest.spyOn(clusterManager.server, 'addListener'); - jest.spyOn(clusterManager.server, 'removeListener'); + jest.spyOn(clusterManager.server, 'on'); + jest.spyOn(clusterManager.server, 'off'); [[{ blockUntil, shouldRedirectFromOldBasePath }]] = basePathProxyMock.start.mock.calls; }); @@ -128,58 +128,58 @@ describe('CLI cluster manager', () => { clusterManager.server.crashed = true; await expect(blockUntil()).resolves.not.toBeDefined(); - expect(clusterManager.server.addListener).not.toHaveBeenCalled(); - expect(clusterManager.server.removeListener).not.toHaveBeenCalled(); + expect(clusterManager.server.on).not.toHaveBeenCalled(); + expect(clusterManager.server.off).not.toHaveBeenCalled(); }); test('`blockUntil()` resolves immediately if worker is already listening.', async () => { clusterManager.server.listening = true; await expect(blockUntil()).resolves.not.toBeDefined(); - expect(clusterManager.server.addListener).not.toHaveBeenCalled(); - expect(clusterManager.server.removeListener).not.toHaveBeenCalled(); + expect(clusterManager.server.on).not.toHaveBeenCalled(); + expect(clusterManager.server.off).not.toHaveBeenCalled(); }); test('`blockUntil()` resolves when worker crashes.', async () => { const blockUntilPromise = blockUntil(); - expect(clusterManager.server.addListener).toHaveBeenCalledTimes(2); - expect(clusterManager.server.addListener).toHaveBeenCalledWith( + expect(clusterManager.server.on).toHaveBeenCalledTimes(2); + expect(clusterManager.server.on).toHaveBeenCalledWith( 'crashed', expect.any(Function) ); - const [, [eventName, onCrashed]] = clusterManager.server.addListener.mock.calls; + const [, [eventName, onCrashed]] = clusterManager.server.on.mock.calls; // Check event name to make sure we call the right callback, // in Jest 23 we could use `toHaveBeenNthCalledWith` instead. expect(eventName).toBe('crashed'); - expect(clusterManager.server.removeListener).not.toHaveBeenCalled(); + expect(clusterManager.server.off).not.toHaveBeenCalled(); onCrashed(); await expect(blockUntilPromise).resolves.not.toBeDefined(); - expect(clusterManager.server.removeListener).toHaveBeenCalledTimes(2); + expect(clusterManager.server.off).toHaveBeenCalledTimes(2); }); test('`blockUntil()` resolves when worker starts listening.', async () => { const blockUntilPromise = blockUntil(); - expect(clusterManager.server.addListener).toHaveBeenCalledTimes(2); - expect(clusterManager.server.addListener).toHaveBeenCalledWith( + expect(clusterManager.server.on).toHaveBeenCalledTimes(2); + expect(clusterManager.server.on).toHaveBeenCalledWith( 'listening', expect.any(Function) ); - const [[eventName, onListening]] = clusterManager.server.addListener.mock.calls; + const [[eventName, onListening]] = clusterManager.server.on.mock.calls; // Check event name to make sure we call the right callback, // in Jest 23 we could use `toHaveBeenNthCalledWith` instead. expect(eventName).toBe('listening'); - expect(clusterManager.server.removeListener).not.toHaveBeenCalled(); + expect(clusterManager.server.off).not.toHaveBeenCalled(); onListening(); await expect(blockUntilPromise).resolves.not.toBeDefined(); - expect(clusterManager.server.removeListener).toHaveBeenCalledTimes(2); + expect(clusterManager.server.off).toHaveBeenCalledTimes(2); }); }); }); diff --git a/src/cli/cluster/worker.test.js b/src/cli/cluster/worker.test.js index 24687d640438a..9854c4cf764be 100644 --- a/src/cli/cluster/worker.test.js +++ b/src/cli/cluster/worker.test.js @@ -35,7 +35,8 @@ function assertListenerRemoved(emitter, event) { const [, onEventListener] = emitter.on.mock.calls.find(([eventName]) => { return eventName === event; }); - expect(emitter.removeListener).toHaveBeenCalledWith(event, onEventListener); + + expect(emitter.off).toHaveBeenCalledWith(event, onEventListener); } function setup(opts = {}) { @@ -98,7 +99,7 @@ describe('CLI cluster manager', () => { assertListenerAdded(fork, 'message'); assertListenerAdded(fork, 'online'); assertListenerAdded(fork, 'disconnect'); - worker.shutdown(); + await worker.shutdown(); expect(fork.process.kill).toHaveBeenCalledTimes(1); assertListenerRemoved(fork, 'message'); assertListenerRemoved(fork, 'online'); diff --git a/src/cli_keystore/add.test.js b/src/cli_keystore/add.test.js index fdf6708cfd94d..71d8379b26438 100644 --- a/src/cli_keystore/add.test.js +++ b/src/cli_keystore/add.test.js @@ -17,8 +17,25 @@ * under the License. */ +const mockKeystoreData = '1:IxR0geiUTMJp8ueHDkqeUJ0I9eEw4NJPXIJi22UDyfGfJSy4mH' + + 'BBuGPkkAix/x/YFfIxo4tiKGdJ2oVTtU8LgKDkVoGdL+z7ylY4n3myatt6osqhI4lzJ9M' + + 'Ry21UcAJki2qFUTj4TYuvhta3LId+RM5UX/dJ2468hQ=='; + +jest.mock('fs', () => ({ + readFileSync: jest.fn().mockImplementation((path) => { + if (!path.includes('nonexistent')) { + return JSON.stringify(mockKeystoreData); + } + + throw { code: 'ENOENT' }; + }), + existsSync: jest.fn().mockImplementation((path) => { + return !path.includes('nonexistent'); + }), + writeFileSync: jest.fn() +})); + import sinon from 'sinon'; -import mockFs from 'mock-fs'; import { PassThrough } from 'stream'; import { Keystore } from '../server/keystore'; @@ -30,17 +47,7 @@ describe('Kibana keystore', () => { describe('add', () => { const sandbox = sinon.createSandbox(); - const keystoreData = '1:IxR0geiUTMJp8ueHDkqeUJ0I9eEw4NJPXIJi22UDyfGfJSy4mH' - + 'BBuGPkkAix/x/YFfIxo4tiKGdJ2oVTtU8LgKDkVoGdL+z7ylY4n3myatt6osqhI4lzJ9M' - + 'Ry21UcAJki2qFUTj4TYuvhta3LId+RM5UX/dJ2468hQ=='; - beforeEach(() => { - mockFs({ - '/data': { - 'test.keystore': JSON.stringify(keystoreData), - } - }); - sandbox.stub(prompt, 'confirm'); sandbox.stub(prompt, 'question'); @@ -49,7 +56,6 @@ describe('Kibana keystore', () => { }); afterEach(() => { - mockFs.restore(); sandbox.restore(); }); @@ -149,4 +155,8 @@ describe('Kibana keystore', () => { expect(keystore.data.foo).toEqual('kibana'); }); }); + + afterAll(() => { + jest.restoreAllMocks(); + }); }); diff --git a/src/cli_keystore/create.test.js b/src/cli_keystore/create.test.js index 234212b93a1ba..d0650640d2435 100644 --- a/src/cli_keystore/create.test.js +++ b/src/cli_keystore/create.test.js @@ -17,8 +17,25 @@ * under the License. */ +const mockKeystoreData = '1:IxR0geiUTMJp8ueHDkqeUJ0I9eEw4NJPXIJi22UDyfGfJSy4mH' + + 'BBuGPkkAix/x/YFfIxo4tiKGdJ2oVTtU8LgKDkVoGdL+z7ylY4n3myatt6osqhI4lzJ9M' + + 'Ry21UcAJki2qFUTj4TYuvhta3LId+RM5UX/dJ2468hQ=='; + +jest.mock('fs', () => ({ + readFileSync: jest.fn().mockImplementation((path) => { + if (!path.includes('foo')) { + return JSON.stringify(mockKeystoreData); + } + + throw { code: 'ENOENT' }; + }), + existsSync: jest.fn().mockImplementation((path) => { + return !path.includes('foo'); + }), + writeFileSync: jest.fn() +})); + import sinon from 'sinon'; -import mockFs from 'mock-fs'; import { Keystore } from '../server/keystore'; import { create } from './create'; @@ -29,23 +46,12 @@ describe('Kibana keystore', () => { describe('create', () => { const sandbox = sinon.createSandbox(); - const keystoreData = '1:IxR0geiUTMJp8ueHDkqeUJ0I9eEw4NJPXIJi22UDyfGfJSy4mH' - + 'BBuGPkkAix/x/YFfIxo4tiKGdJ2oVTtU8LgKDkVoGdL+z7ylY4n3myatt6osqhI4lzJ9M' - + 'Ry21UcAJki2qFUTj4TYuvhta3LId+RM5UX/dJ2468hQ=='; - beforeEach(() => { - mockFs({ - '/data': { - 'test.keystore': JSON.stringify(keystoreData), - } - }); - sandbox.stub(Logger.prototype, 'log'); sandbox.stub(Logger.prototype, 'error'); }); afterEach(() => { - mockFs.restore(); sandbox.restore(); }); @@ -94,4 +100,8 @@ describe('Kibana keystore', () => { sinon.assert.notCalled(keystore.save); }); }); + + afterAll(() => { + jest.restoreAllMocks(); + }); }); diff --git a/src/cli_keystore/list.test.js b/src/cli_keystore/list.test.js index 8e43a08fc9ff2..46dd56e5149c8 100644 --- a/src/cli_keystore/list.test.js +++ b/src/cli_keystore/list.test.js @@ -17,9 +17,24 @@ * under the License. */ -import sinon from 'sinon'; -import mockFs from 'mock-fs'; +const mockKeystoreData = '1:IxR0geiUTMJp8ueHDkqeUJ0I9eEw4NJPXIJi22UDyfGfJSy4mH' + + 'BBuGPkkAix/x/YFfIxo4tiKGdJ2oVTtU8LgKDkVoGdL+z7ylY4n3myatt6osqhI4lzJ9M' + + 'Ry21UcAJki2qFUTj4TYuvhta3LId+RM5UX/dJ2468hQ=='; + +jest.mock('fs', () => ({ + readFileSync: jest.fn().mockImplementation((path) => { + if (!path.includes('nonexistent')) { + return JSON.stringify(mockKeystoreData); + } + throw { code: 'ENOENT' }; + }), + existsSync: jest.fn().mockImplementation((path) => { + return !path.includes('nonexistent'); + }) +})); + +import sinon from 'sinon'; import { Keystore } from '../server/keystore'; import { list } from './list'; import Logger from '../cli_plugin/lib/logger'; @@ -28,23 +43,12 @@ describe('Kibana keystore', () => { describe('list', () => { const sandbox = sinon.createSandbox(); - const keystoreData = '1:IxR0geiUTMJp8ueHDkqeUJ0I9eEw4NJPXIJi22UDyfGfJSy4mH' - + 'BBuGPkkAix/x/YFfIxo4tiKGdJ2oVTtU8LgKDkVoGdL+z7ylY4n3myatt6osqhI4lzJ9M' - + 'Ry21UcAJki2qFUTj4TYuvhta3LId+RM5UX/dJ2468hQ=='; - beforeEach(() => { - mockFs({ - '/data': { - 'test.keystore': JSON.stringify(keystoreData), - } - }); - sandbox.stub(Logger.prototype, 'log'); sandbox.stub(Logger.prototype, 'error'); }); afterEach(() => { - mockFs.restore(); sandbox.restore(); }); @@ -64,4 +68,8 @@ describe('Kibana keystore', () => { sinon.assert.calledWith(Logger.prototype.error, 'ERROR: Kibana keystore not found. Use \'create\' command to create one.'); }); }); + + afterAll(() => { + jest.restoreAllMocks(); + }); }); diff --git a/src/cli_keystore/remove.test.js b/src/cli_keystore/remove.test.js index 9be73b128af21..03116b6e42796 100644 --- a/src/cli_keystore/remove.test.js +++ b/src/cli_keystore/remove.test.js @@ -17,8 +17,17 @@ * under the License. */ +const mockKeystoreData = '1:IxR0geiUTMJp8ueHDkqeUJ0I9eEw4NJPXIJi22UDyfGfJSy4mH' + + 'BBuGPkkAix/x/YFfIxo4tiKGdJ2oVTtU8LgKDkVoGdL+z7ylY4n3myatt6osqhI4lzJ9M' + + 'Ry21UcAJki2qFUTj4TYuvhta3LId+RM5UX/dJ2468hQ=='; + +jest.mock('fs', () => ({ + readFileSync: jest.fn().mockImplementation(() => JSON.stringify(mockKeystoreData)), + existsSync: jest.fn().mockImplementation(() => true), + writeFileSync: jest.fn() +})); + import sinon from 'sinon'; -import mockFs from 'mock-fs'; import { Keystore } from '../server/keystore'; import { remove } from './remove'; @@ -27,20 +36,7 @@ describe('Kibana keystore', () => { describe('remove', () => { const sandbox = sinon.createSandbox(); - const keystoreData = '1:IxR0geiUTMJp8ueHDkqeUJ0I9eEw4NJPXIJi22UDyfGfJSy4mH' - + 'BBuGPkkAix/x/YFfIxo4tiKGdJ2oVTtU8LgKDkVoGdL+z7ylY4n3myatt6osqhI4lzJ9M' - + 'Ry21UcAJki2qFUTj4TYuvhta3LId+RM5UX/dJ2468hQ=='; - - beforeEach(() => { - mockFs({ - '/data': { - 'test.keystore': JSON.stringify(keystoreData), - } - }); - }); - afterEach(() => { - mockFs.restore(); sandbox.restore(); }); @@ -61,4 +57,8 @@ describe('Kibana keystore', () => { sinon.assert.calledOnce(keystore.save); }); }); + + afterAll(() => { + jest.restoreAllMocks(); + }); }); diff --git a/src/cli_plugin/install/kibana.test.js b/src/cli_plugin/install/kibana.test.js index e77d82258e209..4a4ca6ebe3034 100644 --- a/src/cli_plugin/install/kibana.test.js +++ b/src/cli_plugin/install/kibana.test.js @@ -17,12 +17,18 @@ * under the License. */ +jest.mock('fs', () => ({ + statSync: jest.fn().mockImplementation(() => require('fs').statSync), + unlinkSync: jest.fn().mockImplementation(() => require('fs').unlinkSync), + mkdirSync: jest.fn().mockImplementation(() => require('fs').mkdirSync), +})); + import sinon from 'sinon'; -import mockFs from 'mock-fs'; import Logger from '../lib/logger'; import { join } from 'path'; import rimraf from 'rimraf'; import mkdirp from 'mkdirp'; +import fs from 'fs'; import { existingInstall, assertVersion } from './kibana'; describe('kibana cli', function () { @@ -119,20 +125,24 @@ describe('kibana cli', function () { }); it('should throw an error if the plugin already exists.', function () { - mockFs({ [`${pluginDir}/foo`]: {} }); - + fs.statSync = jest.fn().mockImplementationOnce(() => true); existingInstall(settings, logger); expect(logger.error.firstCall.args[0]).toMatch(/already exists/); expect(process.exit.called).toBe(true); - - mockFs.restore(); }); it('should not throw an error if the plugin does not exist.', function () { + fs.statSync = jest.fn().mockImplementationOnce(() => { + throw { code: 'ENOENT' }; + }); existingInstall(settings, logger); expect(logger.error.called).toBe(false); }); }); }); }); + + afterAll(() => { + jest.restoreAllMocks(); + }); }); diff --git a/src/core/public/injected_metadata/deep_freeze.ts b/src/core/public/injected_metadata/deep_freeze.ts index 97eca921b4a62..f172c5de6a9aa 100644 --- a/src/core/public/injected_metadata/deep_freeze.ts +++ b/src/core/public/injected_metadata/deep_freeze.ts @@ -24,7 +24,9 @@ interface RecursiveReadonlyArray extends Array> {} type RecursiveReadonly = T extends any[] ? RecursiveReadonlyArray - : T extends object ? Readonly<{ [K in keyof T]: RecursiveReadonly }> : T; + : T extends object + ? Readonly<{ [K in keyof T]: RecursiveReadonly }> + : T; export function deepFreeze(object: T) { // for any properties that reference an object, makes sure that object is diff --git a/src/core/server/config/config_service.ts b/src/core/server/config/config_service.ts index 5c80beee885e4..14a7ac04263b1 100644 --- a/src/core/server/config/config_service.ts +++ b/src/core/server/config/config_service.ts @@ -79,8 +79,8 @@ export class ConfigService { ConfigClass: ConfigWithSchema ) { return this.getDistinctConfig(path).pipe( - map( - config => (config === undefined ? undefined : this.createConfig(path, config, ConfigClass)) + map(config => + config === undefined ? undefined : this.createConfig(path, config, ConfigClass) ) ); } diff --git a/src/core/server/http/http_tools.ts b/src/core/server/http/http_tools.ts index faf7ba4e94542..30b7631bde564 100644 --- a/src/core/server/http/http_tools.ts +++ b/src/core/server/http/http_tools.ts @@ -85,7 +85,7 @@ export function createServer(options: ServerOptions) { server.listener.keepAliveTimeout = 120e3; server.listener.on('clientError', (err, socket) => { if (socket.writable) { - socket.end(new Buffer('HTTP/1.1 400 Bad Request\r\n\r\n', 'ascii')); + socket.end(Buffer.from('HTTP/1.1 400 Bad Request\r\n\r\n', 'ascii')); } else { socket.destroy(err); } diff --git a/src/core/server/plugins/discovery/plugins_discovery.ts b/src/core/server/plugins/discovery/plugins_discovery.ts index fa92a1ba2ffef..e7ec311c5823f 100644 --- a/src/core/server/plugins/discovery/plugins_discovery.ts +++ b/src/core/server/plugins/discovery/plugins_discovery.ts @@ -76,7 +76,7 @@ function processPluginSearchPaths$(pluginDirs: ReadonlyArray, log: Logge log.debug(`Scanning "${dir}" for plugin sub-directories...`); return fsReadDir$(dir).pipe( - mergeMap(subDirs => subDirs.map(subDir => resolve(dir, subDir))), + mergeMap((subDirs: string[]) => subDirs.map(subDir => resolve(dir, subDir))), mergeMap(path => fsStat$(path).pipe( // Filter out non-directory entries from target directories, it's expected that diff --git a/src/dev/build/lib/scan_delete.ts b/src/dev/build/lib/scan_delete.ts index 854e82ed169a8..c1e9a7cd84065 100644 --- a/src/dev/build/lib/scan_delete.ts +++ b/src/dev/build/lib/scan_delete.ts @@ -53,7 +53,7 @@ export async function scanDelete(options: Options) { const getChildPath$ = (path: string) => getReadDir$(path).pipe( mergeAll(), - map(name => join(path, name)) + map((name: string) => join(path, name)) ); // get an observable of all paths to be deleted, by starting with the arg diff --git a/src/legacy/core_plugins/inspector_views/public/data/__snapshots__/data_view.test.js.snap b/src/legacy/core_plugins/inspector_views/public/data/__snapshots__/data_view.test.js.snap index 1ccc5f9adf2dc..e54d62db412f3 100644 --- a/src/legacy/core_plugins/inspector_views/public/data/__snapshots__/data_view.test.js.snap +++ b/src/legacy/core_plugins/inspector_views/public/data/__snapshots__/data_view.test.js.snap @@ -10,7 +10,6 @@ exports[`Inspector Data View component should render empty state 1`] = ` }, "_eventsCount": 1, "_maxListeners": undefined, - "domain": null, "tabular": [Function], "tabularOptions": Object {}, }, @@ -101,7 +100,6 @@ exports[`Inspector Data View component should render loading state 1`] = ` }, "_eventsCount": 1, "_maxListeners": undefined, - "domain": null, }, } } diff --git a/src/legacy/core_plugins/kibana/public/dashboard/actions/embeddables.ts b/src/legacy/core_plugins/kibana/public/dashboard/actions/embeddables.ts index f2b570ec25a08..04c73b5f2aa8f 100644 --- a/src/legacy/core_plugins/kibana/public/dashboard/actions/embeddables.ts +++ b/src/legacy/core_plugins/kibana/public/dashboard/actions/embeddables.ts @@ -44,9 +44,9 @@ export interface EmbeddableIsInitializedActionPayload { export interface EmbeddableIsInitializedAction extends KibanaAction< - EmbeddableActionTypeKeys.EMBEDDABLE_IS_INITIALIZED, - EmbeddableIsInitializedActionPayload - > {} + EmbeddableActionTypeKeys.EMBEDDABLE_IS_INITIALIZED, + EmbeddableIsInitializedActionPayload + > {} export interface SetStagedFilterActionPayload { panelId: PanelId; diff --git a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/field.test.js b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/field.test.js index e29fa051b155f..91267758310e3 100644 --- a/src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/field.test.js +++ b/src/legacy/core_plugins/kibana/public/management/sections/settings/components/field/field.test.js @@ -243,10 +243,14 @@ describe('Field', () => { ...component.instance().props.setting, value: userValue, } }); + + await component.instance().cancelChangeImage(); component.update(); }); it('should be able to change value from existing value and save', async () => { + findTestSubject(component, `advancedSetting-changeImage-${setting.name}`).simulate('click'); + const newUserValue = `${userValue}=`; await component.instance().onImageChange([newUserValue]); component.update(); diff --git a/src/legacy/core_plugins/kibana/public/visualize/wizard/type_selection/vis_type_icon.tsx b/src/legacy/core_plugins/kibana/public/visualize/wizard/type_selection/vis_type_icon.tsx index 44c4f4835d5aa..2468069c77bb9 100644 --- a/src/legacy/core_plugins/kibana/public/visualize/wizard/type_selection/vis_type_icon.tsx +++ b/src/legacy/core_plugins/kibana/public/visualize/wizard/type_selection/vis_type_icon.tsx @@ -45,10 +45,9 @@ export const VisTypeIcon = ({ visType }: VisTypeIconProps) => { )} {!visType.image && visType.legacyIcon && } - {!visType.image && - !visType.legacyIcon && ( -