Merge remote-tracking branch 'upstream/master' into enh/geojsonUpload

# Conflicts:
#	x-pack/plugins/maps/public/shared/layers/sources/source.js
This commit is contained in:
Aaron Caldwell 2019-04-01 08:21:01 -06:00
commit 265a0e3d61
1939 changed files with 20892 additions and 14819 deletions

View file

@ -14,18 +14,27 @@ node scripts/es snapshot --license=oss --download-only;
# download reporting browsers
(cd "x-pack" && yarn gulp prepare);
# cache the chromedriver bin
# cache the chromedriver archive
chromedriverDistVersion="$(node -e "console.log(require('chromedriver').version)")"
chromedriverPkgVersion="$(node -e "console.log(require('./package.json').devDependencies.chromedriver)")"
if [ -z "$chromedriverDistVersion" ] || [ -z "$chromedriverPkgVersion" ]; then
echo "UNABLE TO DETERMINE CHROMEDRIVER VERSIONS"
exit 1
fi
mkdir ".chromedriver"
mkdir -p .chromedriver
curl "https://chromedriver.storage.googleapis.com/$chromedriverDistVersion/chromedriver_linux64.zip" > .chromedriver/chromedriver.zip
echo "$chromedriverPkgVersion" > .chromedriver/pkgVersion
# cache the geckodriver archive
geckodriverPkgVersion="$(node -e "console.log(require('./package.json').devDependencies.geckodriver)")"
if [ -z "$geckodriverPkgVersion" ]; then
echo "UNABLE TO DETERMINE geckodriver VERSIONS"
exit 1
fi
mkdir -p ".geckodriver"
cp "node_modules/geckodriver/geckodriver.tar.gz" .geckodriver/geckodriver.tar.gz
echo "$geckodriverPkgVersion" > .geckodriver/pkgVersion
# archive cacheable directories
mkdir -p "$HOME/.kibana/bootstrap_cache"
tar -cf "$HOME/.kibana/bootstrap_cache/$branch.tar" \
@ -36,7 +45,8 @@ tar -cf "$HOME/.kibana/bootstrap_cache/$branch.tar" \
x-pack/plugins/reporting/.chromium \
test/plugin_functional/plugins/*/node_modules \
.es \
.chromedriver;
.chromedriver \
.geckodriver;
echo "created $HOME/.kibana/bootstrap_cache/$branch.tar"

View file

@ -47,6 +47,47 @@ module.exports = {
rules: {
'no-restricted-imports': [2, restrictedModules],
'no-restricted-modules': [2, restrictedModules],
'@kbn/eslint/no-restricted-paths': [
'error',
{
basePath: __dirname,
zones: [
{
target: [
'src/legacy/**/*',
'x-pack/**/*',
'!x-pack/**/*.test.*',
'src/plugins/**/(public|server)/**/*',
'src/core/(public|server)/**/*',
],
from: [
'src/core/public/**/*',
'!src/core/public/index*',
'!src/core/public/utils/**/*',
'src/core/server/**/*',
'!src/core/server/index*',
'src/plugins/**/public/**/*',
'!src/plugins/**/public/index*',
'src/plugins/**/server/**/*',
'!src/plugins/**/server/index*',
],
allowSameFolder: true,
},
],
},
],
'@kbn/eslint/module_migration': [
'error',
[
{
from: 'expect.js',
to: '@kbn/expect',
},
],
],
},
overrides: [

View file

@ -111,7 +111,7 @@ If yarn doesn't find the module it may not have types. For example, our `rison_
1. Contribute types into the DefinitelyTyped repo itself, or
2. Create a top level `types` folder and point to that in the tsconfig. For example, Infra team already handled this for `rison_node` and added: `x-pack/plugins/infra/types/rison_node.d.ts`. Other code uses it too so we will need to pull it up. Or,
3. Add a `// @ts-ignore` line above the import. This should be used minimally, the above options are better. However, sometimes you have to resort to this method. For example, the `expect.js` module will require this line. We don't have type definitions installed for this library. Installing these types would conflict with the jest typedefs for expect, and since they aren't API compatible with each other, it's not possible to make both test frameworks happy. Since we are moving from mocha => jest, we don't see this is a big issue.
3. Add a `// @ts-ignore` line above the import. This should be used minimally, the above options are better. However, sometimes you have to resort to this method.
### TypeScripting react files

View file

@ -1,8 +1,5 @@
[[release-notes]]
= {kib} Release Notes
++++
<titleabbrev>Release Notes</titleabbrev>
++++
= Release Notes
[partintro]
--

View file

@ -5,6 +5,7 @@
* <<development-dependencies>>
* <<development-modules>>
* <<development-elasticsearch>>
* <<development-unit-tests>>
* <<development-functional-tests>>
include::core/development-basepath.asciidoc[]
@ -15,4 +16,6 @@ include::core/development-modules.asciidoc[]
include::core/development-elasticsearch.asciidoc[]
include::core/development-unit-tests.asciidoc[]
include::core/development-functional-tests.asciidoc[]

View file

@ -82,7 +82,7 @@ Use the `--help` flag for more options.
[float]
===== Environment
The tests are written in https://mochajs.org[mocha] using https://github.com/Automattic/expect.js[expect] for assertions.
The tests are written in https://mochajs.org[mocha] using https://github.com/elastic/kibana/tree/master/packages/kbn-expect[@kbn/expect] for assertions.
We use https://sites.google.com/a/chromium.org/chromedriver/[chromedriver], https://theintern.github.io/leadfoot[leadfoot], and https://github.com/theintern/digdug[digdug] for automating Chrome. When the `FunctionalTestRunner` launches, digdug opens a `Tunnel` which starts chromedriver and a stripped-down instance of Chrome. It also creates an instance of https://theintern.github.io/leadfoot/module-leadfoot_Command.html[Leadfoot's `Command`] class, which is available via the `remote` service. The `remote` communicates to Chrome through the digdug `Tunnel`. See the https://theintern.github.io/leadfoot/module-leadfoot_Command.html[leadfoot/Command API] docs for all the commands you can use with `remote`.
@ -122,11 +122,11 @@ A test suite is a collection of tests defined by calling `describe()`, and then
[float]
===== Anatomy of a test file
The annotated example file below shows the basic structure every test suite uses. It starts by importing https://github.com/Automattic/expect.js[`expect.js`] and defining its default export: an anonymous Test Provider. The test provider then destructures the Provider API for the `getService()` and `getPageObjects()` functions. It uses these functions to collect the dependencies of this suite. The rest of the test file will look pretty normal to mocha.js users. `describe()`, `it()`, `before()` and the lot are used to define suites that happen to automate a browser via services and objects of type `PageObject`.
The annotated example file below shows the basic structure every test suite uses. It starts by importing https://github.com/elastic/kibana/tree/master/packages/kbn-expect[`@kbn/expect`] and defining its default export: an anonymous Test Provider. The test provider then destructures the Provider API for the `getService()` and `getPageObjects()` functions. It uses these functions to collect the dependencies of this suite. The rest of the test file will look pretty normal to mocha.js users. `describe()`, `it()`, `before()` and the lot are used to define suites that happen to automate a browser via services and objects of type `PageObject`.
["source","js"]
----
import expect from 'expect.js';
import expect from '@kbn/expect';
// test files must `export default` a function that defines a test suite
export default function ({ getService, getPageObject }) {

View file

@ -0,0 +1,83 @@
[[development-unit-tests]]
=== Unit Testing
We use unit tests to make sure that individual software units of {kib} perform as they were designed to.
[float]
=== Current Frameworks
{kib} is migrating unit testing from `Mocha` to `Jest`. Legacy unit tests still exist in `Mocha` but all new unit tests should be written in `Jest`.
[float]
==== Mocha (legacy)
Mocha tests are contained in `__tests__` directories.
*Running Mocha Unit Tests*
["source","shell"]
-----------
yarn test:mocha
-----------
[float]
==== Jest
Jest tests are stored in the same directory as source code files with the `.test.{js,ts,tsx}` suffix.
*Running Jest Unit Tests*
["source","shell"]
-----------
yarn test:jest
-----------
[float]
===== Writing Jest Unit Tests
In order to write those tests there are two main things you need to be aware of.
The first one is the different between `jest.mock` and `jest.doMock`
and the second one our `jest mocks file pattern`. As we are running `js` and `ts`
test files with `babel-jest` both techniques are needed
specially for the tests implemented on Typescript in order to benefit from the
auto-inference types feature.
[float]
===== Jest.mock vs Jest.doMock
Both methods are essentially the same on their roots however the `jest.mock`
calls will get hoisted to the top of the file and can only reference variables
prefixed with `mock`. On the other hand, `jest.doMock` won't be hoisted and can
reference pretty much any variable we want, however we have to assure those referenced
variables are instantiated at the time we need them which lead us to the next
section where we'll talk about our jest mock files pattern.
[float]
===== Jest Mock Files Pattern
Specially on typescript it is pretty common to have in unit tests
`jest.doMock` calls which reference for example imported types. Any error
will thrown from doing that however the test will fail. The reason behind that
is because despite the `jest.doMock` isn't being hoisted by `babel-jest` the
import with the types we are referencing will be hoisted to the top and at the
time we'll call the function that variable would not be defined.
In order to prevent that we develop a protocol that should be followed:
- Each module could provide a standard mock in `mymodule.mock.ts` in case
there are other tests that could benefit from using definitions here.
This file would not have any `jest.mock` calls, just dummy objects.
- Each test defines its mocks in `mymodule.test.mocks.ts`. This file
could import relevant mocks from the generalised module's mocks
file `(*.mock.ts)` and call `jest.mock` for each of them. If there is
any relevant dummy mock objects to generalise (and to be used by
other tests), the dummy objects could be defined directly on this file.
- Each test would import its mocks from the test mocks
file mymodule.test.mocks.ts. `mymodule.test.ts` has an import
like: `import * as Mocks from './mymodule.test.mocks'`,
`import { mockX } from './mymodule.test.mocks'`
or just `import './mymodule.test.mocks'` if there isn't anything
exported to be used.

View file

@ -3,12 +3,16 @@
This tutorial requires three data sets:
* The complete works of William Shakespeare, suitably parsed into fields. Download
https://download.elastic.co/demos/kibana/gettingstarted/shakespeare_6.0.json[`shakespeare.json`].
* A set of fictitious accounts with randomly generated data. Download
https://download.elastic.co/demos/kibana/gettingstarted/accounts.zip[`accounts.zip`].
* A set of randomly generated log files. Download
https://download.elastic.co/demos/kibana/gettingstarted/logs.jsonl.gz[`logs.jsonl.gz`].
* The complete works of William Shakespeare, suitably parsed into fields
* A set of fictitious accounts with randomly generated data
* A set of randomly generated log files
Create a new working directory where you want to download the files. From that directory, run the following commands:
[source,shell]
curl -O https://download.elastic.co/demos/kibana/gettingstarted/8.x/shakespeare.json
curl -O https://download.elastic.co/demos/kibana/gettingstarted/8.x/accounts.zip
curl -O https://download.elastic.co/demos/kibana/gettingstarted/8.x/logs.jsonl.gz
Two of the data sets are compressed. To extract the files, use these commands:
@ -73,16 +77,14 @@ In Kibana *Dev Tools > Console*, set up a mapping for the Shakespeare data set:
[source,js]
PUT /shakespeare
{
"mappings": {
"doc": {
"properties": {
"mappings": {
"properties": {
"speaker": {"type": "keyword"},
"play_name": {"type": "keyword"},
"line_id": {"type": "integer"},
"speech_number": {"type": "integer"}
}
}
}
}
}
//CONSOLE
@ -100,13 +102,11 @@ as geographic locations by applying the `geo_point` type.
PUT /logstash-2015.05.18
{
"mappings": {
"log": {
"properties": {
"geo": {
"properties": {
"coordinates": {
"type": "geo_point"
}
"properties": {
"geo": {
"properties": {
"coordinates": {
"type": "geo_point"
}
}
}
@ -120,13 +120,11 @@ PUT /logstash-2015.05.18
PUT /logstash-2015.05.19
{
"mappings": {
"log": {
"properties": {
"geo": {
"properties": {
"coordinates": {
"type": "geo_point"
}
"properties": {
"geo": {
"properties": {
"coordinates": {
"type": "geo_point"
}
}
}
@ -140,13 +138,11 @@ PUT /logstash-2015.05.19
PUT /logstash-2015.05.20
{
"mappings": {
"log": {
"properties": {
"geo": {
"properties": {
"coordinates": {
"type": "geo_point"
}
"properties": {
"geo": {
"properties": {
"coordinates": {
"type": "geo_point"
}
}
}
@ -165,13 +161,13 @@ API to load the data sets:
[source,shell]
curl -H 'Content-Type: application/x-ndjson' -XPOST 'localhost:9200/bank/account/_bulk?pretty' --data-binary @accounts.json
curl -H 'Content-Type: application/x-ndjson' -XPOST 'localhost:9200/shakespeare/doc/_bulk?pretty' --data-binary @shakespeare_6.0.json
curl -H 'Content-Type: application/x-ndjson' -XPOST 'localhost:9200/shakespeare/_bulk?pretty' --data-binary @shakespeare.json
curl -H 'Content-Type: application/x-ndjson' -XPOST 'localhost:9200/_bulk?pretty' --data-binary @logs.jsonl
Or for Windows users, in Powershell:
[source,shell]
Invoke-RestMethod "http://localhost:9200/bank/account/_bulk?pretty" -Method Post -ContentType 'application/x-ndjson' -InFile "accounts.json"
Invoke-RestMethod "http://localhost:9200/shakespeare/doc/_bulk?pretty" -Method Post -ContentType 'application/x-ndjson' -InFile "shakespeare_6.0.json"
Invoke-RestMethod "http://localhost:9200/shakespeare/_bulk?pretty" -Method Post -ContentType 'application/x-ndjson' -InFile "shakespeare.json"
Invoke-RestMethod "http://localhost:9200/_bulk?pretty" -Method Post -ContentType 'application/x-ndjson' -InFile "logs.jsonl"
These commands might take some time to execute, depending on the available computing resources.
@ -187,8 +183,8 @@ Your output should look similar to this:
[source,shell]
health status index pri rep docs.count docs.deleted store.size pri.store.size
yellow open bank 5 1 1000 0 418.2kb 418.2kb
yellow open shakespeare 5 1 111396 0 17.6mb 17.6mb
yellow open logstash-2015.05.18 5 1 4631 0 15.6mb 15.6mb
yellow open logstash-2015.05.19 5 1 4624 0 15.7mb 15.7mb
yellow open logstash-2015.05.20 5 1 4750 0 16.4mb 16.4mb
yellow open bank 1 1 1000 0 418.2kb 418.2kb
yellow open shakespeare 1 1 111396 0 17.6mb 17.6mb
yellow open logstash-2015.05.18 1 1 4631 0 15.6mb 15.6mb
yellow open logstash-2015.05.19 1 1 4624 0 15.7mb 15.7mb
yellow open logstash-2015.05.20 1 1 4750 0 16.4mb 16.4mb

View file

@ -1,9 +1,6 @@
[role="xpack"]
[[xpack-graph]]
= Graphing Connections in Your Data
++++
<titleabbrev>Graph</titleabbrev>
++++
[partintro]
--
@ -66,6 +63,7 @@ multi-node clusters and scales with your Elasticsearch deployment.
Advanced options let you control how your data is sampled and summarized.
You can also set timeouts to prevent graph queries from adversely
affecting the cluster.
--
include::getting-started.asciidoc[]

View file

@ -41,9 +41,6 @@ working on big documents. Set this property to `false` to disable highlighting.
`doc_table:hideTimeColumn`:: Hide the 'Time' column in Discover and in all Saved Searches on Dashboards.
`search:includeFrozen`:: Will include {ref}/frozen-indices.html[frozen indices] in results if enabled. Searching through frozen indices
might increase the search time.
`courier:maxSegmentCount`:: Kibana splits requests in the Discover app into segments to limit the size of requests sent to
the Elasticsearch cluster. This setting constrains the length of the segment list. Long segment lists can significantly
increase request processing time.
`courier:ignoreFilterIfFieldNotInIndex`:: Set this property to `true` to skip filters that apply to fields that don't exist in a visualization's index. Useful when dashboards consist of visualizations from multiple index patterns.
`courier:maxConcurrentShardRequests`:: Controls the {ref}/search-multi-search.html[max_concurrent_shard_requests] setting used for _msearch requests sent by Kibana. Set to 0 to disable this config and use the Elasticsearch default.
`fields:popularLimit`:: This setting governs how many of the top most popular fields are shown.

View file

@ -18,4 +18,10 @@ The following section is re-used in the Installation and Upgrade Guide
////
// tag::notable-breaking-changes[]
[float]
=== Default logging timezone is now the system's timezone
*Details:* In prior releases the timezone used in logs defaulted to UTC. We now use the host machine's timezone by default.
*Impact:* To restore the previous behavior, in kibana.yml set `logging.timezone: UTC`.
// end::notable-breaking-changes[]

View file

@ -1,8 +1,5 @@
[[release-highlights]]
= {kib} Release Highlights
++++
<titleabbrev>Release Highlights</titleabbrev>
++++
= Release Highlights
[partintro]
--

View file

@ -1,11 +1,11 @@
[role="xpack"]
[[automating-report-generation]]
== Automating Report Generation
You can automatically generate reports with a watch, or by submitting
You can automatically generate reports with {watcher}, or by submitting
HTTP POST requests from a script.
To automatically generate reports with a watch, you need to configure
{watcher} to trust the Kibana servers certificate. For more information,
{watcher} to trust the {kib} servers certificate. For more information,
see <<securing-reporting, Securing Reporting>>.
include::report-intervals.asciidoc[]
@ -13,27 +13,28 @@ include::report-intervals.asciidoc[]
To get the URL for triggering a report generation during a given time period:
. Load the saved object.
. Use the time-picker to specify a relative or absolute time period.
. Click *Reporting* in the Kibana toolbar.
. Copy the displayed **Generation URL**.
. Use the timepicker to specify a relative or absolute time period.
. Click *Share* in the Kibana toolbar.
. Select *PDF Reports*.
. Click **Copy POST URL**.
NOTE: The response from this request with be JSON, and will contain a `path` property
with a URL to use to download the generated report. When requesting that path,
you will get a 503 response if it's not completed yet. In this case, retry after the
number of seconds in the `Retry-After` header in the response until you get the PDF.
number of seconds in the `Retry-After` header in the response until the PDF is returned.
To configure a watch to email reports, you use the `reporting` attachment type
in an `email` action. For more information, see
{xpack-ref}/actions-email.html#configuring-email[Configuring Email Accounts].
{stack-ov}/actions-email.html#configuring-email[Configuring Email Accounts].
include::watch-example.asciidoc[]
For more information about configuring watches, see
{xpack-ref}/how-watcher-works.html[How Watcher Works].
{stack-ov}/how-watcher-works.html[How Watcher Works].
== Deprecated Report URLs
The following is deprecated in 6.0, and you should now use Kibana to get the URL for a
The following is deprecated in 6.0, and you should now use {kib} to get the URL for a
particular report.
You may request PDF reports optimized for printing through three {reporting} endpoints:

View file

@ -49,5 +49,4 @@ image:reporting/images/share-button.png["Reporting Button",link="share-button.pn
=== Generating a Report Automatically
If you want to automatically generate reports from a script or with
{watcher}, use the displayed Generation URL. For more information, see
<<automating-report-generation, Automating Report Generation>>
{watcher}, see <<automating-report-generation, Automating Report Generation>>

View file

@ -73,8 +73,7 @@ xpack.security.sessionTimeout: 600000
. Restart {kib}.
[[kibana-roles]]
. Choose an authentication mechanism and grant users the privileges they need to
. [[kibana-roles]]Choose an authentication mechanism and grant users the privileges they need to
use {kib}.
+
--

View file

@ -96,7 +96,7 @@ Some example translations are shown here:
`KIBANA_DEFAULTAPPID`:: `kibana.defaultAppId`
`XPACK_MONITORING_ENABLED`:: `xpack.monitoring.enabled`
In general, any setting listed in <<settings>> or <<settings-xpack-kb>> can be
In general, any setting listed in <<settings>> can be
configured with this technique.
These variables can be set with +docker-compose+ like this:

View file

@ -80,7 +80,7 @@ requests to check Elasticsearch for an updated list of nodes.
`elasticsearch.sniffOnStart:`:: *Default: false* Attempt to find other
Elasticsearch nodes on startup.
`elasticsearch.sniffOnConectionFault:`:: *Default: false* Update the list of
`elasticsearch.sniffOnConnectionFault:`:: *Default: false* Update the list of
Elasticsearch nodes immediately following a connection fault.
`elasticsearch.ssl.alwaysPresentCertificate:`:: *Default: false* Controls
@ -118,6 +118,9 @@ password that the Kibana server uses to perform maintenance on the Kibana index
at startup. Your Kibana users still need to authenticate with Elasticsearch,
which is proxied through the Kibana server.
`interpreter.enableInVisualize`:: *Default: true* Enables use of interpreter in
Visualize.
`kibana.defaultAppId:`:: *Default: "discover"* The default application to load.
`kibana.index:`:: *Default: ".kibana"* Kibana uses an index in Elasticsearch to
@ -300,4 +303,4 @@ include::{docdir}/settings/monitoring-settings.asciidoc[]
include::{docdir}/settings/reporting-settings.asciidoc[]
include::secure-settings.asciidoc[]
include::{docdir}/settings/security-settings.asciidoc[]
include::{docdir}/settings/spaces-settings.asciidoc[]
include::{docdir}/settings/spaces-settings.asciidoc[]

View file

@ -90,13 +90,15 @@
"**/@types/*/**",
"**/grunt-*",
"**/grunt-*/**",
"x-pack/typescript",
"kbn_tp_*/**"
"x-pack/typescript"
]
},
"dependencies": {
"@babel/core": "^7.3.4",
"@babel/polyfill": "^7.2.5",
"@babel/register": "^7.0.0",
"@elastic/datemath": "5.0.2",
"@elastic/eui": "9.5.0",
"@elastic/eui": "9.7.1",
"@elastic/filesaver": "1.1.2",
"@elastic/good": "8.1.1-kibana2",
"@elastic/numeral": "2.3.2",
@ -124,10 +126,7 @@
"angular-sanitize": "1.6.5",
"angular-sortable-view": "0.0.15",
"autoprefixer": "^9.1.0",
"babel-core": "6.26.3",
"babel-loader": "7.1.5",
"babel-polyfill": "6.26.0",
"babel-register": "6.26.0",
"babel-loader": "8.0.5",
"bluebird": "3.5.3",
"boom": "^7.2.0",
"brace": "0.11.1",
@ -174,7 +173,7 @@
"leaflet-responsive-popup": "0.2.0",
"leaflet-vega": "^0.8.6",
"leaflet.heat": "0.2.0",
"less": "2.7.1",
"less": "^2.7.3",
"less-loader": "4.1.0",
"lodash": "npm:@elastic/lodash@3.10.1-kibana1",
"lodash.clonedeep": "^4.5.0",
@ -258,12 +257,13 @@
"@kbn/es": "1.0.0",
"@kbn/eslint-import-resolver-kibana": "2.0.0",
"@kbn/eslint-plugin-eslint": "1.0.0",
"@kbn/expect": "1.0.0",
"@kbn/plugin-generator": "1.0.0",
"@kbn/test": "1.0.0",
"@octokit/rest": "^15.10.0",
"@types/angular": "1.6.50",
"@types/angular-mocks": "^1.7.0",
"@types/babel-core": "^6.25.5",
"@types/babel__core": "^7.1.0",
"@types/bluebird": "^3.1.1",
"@types/boom": "^7.2.0",
"@types/chance": "^1.0.0",
@ -275,7 +275,7 @@
"@types/delete-empty": "^2.0.0",
"@types/elasticsearch": "^5.0.30",
"@types/enzyme": "^3.1.12",
"@types/eslint": "^4.16.2",
"@types/eslint": "^4.16.6",
"@types/execa": "^0.9.0",
"@types/fetch-mock": "7.2.1",
"@types/getopts": "^2.0.0",
@ -293,6 +293,7 @@
"@types/json5": "^0.0.30",
"@types/listr": "^0.13.0",
"@types/lodash": "^3.10.1",
"@types/lru-cache": "^5.1.0",
"@types/minimatch": "^2.0.29",
"@types/mocha": "^5.2.6",
"@types/moment-timezone": "^0.5.8",
@ -320,8 +321,8 @@
"@types/zen-observable": "^0.8.0",
"angular-mocks": "1.4.7",
"archiver": "^3.0.0",
"babel-eslint": "^9.0.0",
"babel-jest": "^23.6.0",
"babel-eslint": "^10.0.1",
"babel-jest": "^24.1.0",
"backport": "4.4.1",
"chai": "3.5.0",
"chance": "1.0.10",
@ -335,21 +336,21 @@
"enzyme-adapter-react-16": "^1.9.0",
"enzyme-adapter-utils": "^1.10.0",
"enzyme-to-json": "^3.3.4",
"eslint": "^5.6.0",
"eslint-config-prettier": "^3.1.0",
"eslint-plugin-babel": "^5.2.0",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-jest": "^21.26.2",
"eslint-plugin-jsx-a11y": "^6.1.2",
"eslint-plugin-mocha": "^5.2.0",
"eslint": "^5.15.1",
"eslint-config-prettier": "^4.1.0",
"eslint-plugin-babel": "^5.3.0",
"eslint-plugin-import": "^2.16.0",
"eslint-plugin-jest": "^22.3.0",
"eslint-plugin-jsx-a11y": "^6.2.1",
"eslint-plugin-mocha": "^5.3.0",
"eslint-plugin-no-unsanitized": "^3.0.2",
"eslint-plugin-prefer-object-spread": "^1.2.1",
"eslint-plugin-prettier": "^2.6.2",
"eslint-plugin-react": "^7.11.1",
"expect.js": "0.3.1",
"eslint-plugin-prettier": "^3.0.1",
"eslint-plugin-react": "^7.12.4",
"eslint-plugin-react-hooks": "^1.6.0",
"faker": "1.1.0",
"fetch-mock": "7.3.0",
"geckodriver": "1.12.2",
"geckodriver": "^1.16.1",
"getopts": "2.0.0",
"grunt": "1.0.3",
"grunt-cli": "^1.2.0",
@ -357,7 +358,7 @@
"grunt-karma": "2.0.0",
"grunt-peg": "^2.0.1",
"grunt-run": "0.7.0",
"gulp-babel": "^7.0.1",
"gulp-babel": "^8.0.0",
"gulp-sourcemaps": "2.6.4",
"has-ansi": "^3.0.0",
"image-diff": "1.6.0",
@ -403,9 +404,6 @@
"supertest": "^3.1.0",
"supertest-as-promised": "^4.0.2",
"tree-kill": "^1.1.0",
"ts-jest": "^23.1.4",
"ts-loader": "^5.2.2",
"ts-node": "^7.0.1",
"tslint": "^5.11.0",
"tslint-config-prettier": "^1.15.0",
"tslint-microsoft-contrib": "^6.0.0",

View file

@ -1,13 +1,16 @@
{
"presets": [["env", {
"targets": {
"node": "current",
"browsers": [
"last 2 versions",
"> 5%",
"Safari 7",
]
"presets": [
["@babel/preset-env", {
"targets": {
"node": "current",
"browsers": [
"last 2 versions",
"> 5%",
"Safari 7"
]
}
}
}]],
]
],
"plugins": ["add-module-exports"]
}
}

View file

@ -11,9 +11,9 @@
"kbn:watch": "yarn build --watch"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-plugin-add-module-exports": "^0.2.1",
"babel-preset-env": "^1.7.0",
"@babel/cli": "^7.2.3",
"@babel/preset-env": "^7.3.4",
"babel-plugin-add-module-exports": "^1.0.0",
"moment": "^2.13.0"
},
"dependencies": {

View file

@ -20,7 +20,7 @@
import dateMath from '../src/index';
import moment from 'moment';
import sinon from 'sinon';
import expect from 'expect.js';
import expect from '@kbn/expect';
/**
* Require a new instance of the moment library, bypassing the require cache.

View file

@ -10,6 +10,7 @@ module.exports = {
'mocha',
'babel',
'react',
'react-hooks',
'import',
'no-unsanitized',
'prefer-object-spread',
@ -127,6 +128,8 @@ module.exports = {
arrow: true,
}],
'react/jsx-first-prop-new-line': ['error', 'multiline-multiprop'],
'react-hooks/rules-of-hooks': 'error', // Checks rules of Hooks
'react-hooks/exhaustive-deps': 'warn', // Checks effect dependencies
'jsx-a11y/accessible-emoji': 'error',
'jsx-a11y/alt-text': 'error',
'jsx-a11y/anchor-has-content': 'error',

View file

@ -15,15 +15,16 @@
},
"homepage": "https://github.com/elastic/eslint-config-kibana#readme",
"peerDependencies": {
"babel-eslint": "^9.0.0",
"eslint": "^5.6.0",
"eslint-plugin-babel": "^5.2.0",
"eslint-plugin-jsx-a11y": "^6.1.2",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-jest": "^21.22.1",
"eslint-plugin-mocha": "^5.2.0",
"babel-eslint": "^10.0.1",
"eslint": "^5.14.1",
"eslint-plugin-babel": "^5.3.0",
"eslint-plugin-jsx-a11y": "^6.2.1",
"eslint-plugin-import": "^2.16.0",
"eslint-plugin-jest": "^22.3.0",
"eslint-plugin-mocha": "^5.3.0",
"eslint-plugin-no-unsanitized": "^3.0.2",
"eslint-plugin-prefer-object-spread": "^1.2.1",
"eslint-plugin-react": "^7.11.1"
"eslint-plugin-react": "^7.12.4",
"eslint-plugin-react-hooks": "^1.6.0"
}
}

View file

@ -15,7 +15,7 @@
"kbn:watch": "yarn build --watch"
},
"devDependencies": {
"babel-cli": "^6.26.0"
"@babel/cli": "^7.2.3"
},
"dependencies": {
"@kbn/babel-preset": "1.0.0",

View file

@ -19,20 +19,33 @@
module.exports = {
presets: [
require.resolve('babel-preset-react'),
require.resolve('@babel/preset-typescript'),
require.resolve('@babel/preset-react')
],
plugins: [
require.resolve('babel-plugin-add-module-exports'),
// stage 3
require.resolve('babel-plugin-transform-async-generator-functions'),
require.resolve('babel-plugin-transform-object-rest-spread'),
// the class properties proposal was merged with the private fields proposal
// The class properties proposal was merged with the private fields proposal
// into the "class fields" proposal. Babel doesn't support this combined
// proposal yet, which includes private field, so this transform is
// TECHNICALLY stage 2, but for all intents and purposes it's stage 3
//
// See https://github.com/babel/proposals/issues/12 for progress
require.resolve('babel-plugin-transform-class-properties'),
require.resolve('@babel/plugin-proposal-class-properties'),
],
overrides: [
{
// Babel 7 don't support the namespace feature on typescript code.
// With namespaces only used for type declarations, we can securely
// strip them off for babel on x-pack infra plugin
//
// See https://github.com/babel/babel/issues/8244#issuecomment-466548733
test: /x-pack[\/\\]plugins[\/\\]infra[\/\\].*[\/\\]graphql/,
plugins: [
[
require.resolve('babel-plugin-typescript-strip-namespaces'),
],
]
}
]
};

View file

@ -1,39 +0,0 @@
/*
* 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.
*/
module.exports = {
presets: [
require.resolve('@babel/preset-react'),
require.resolve('@babel/preset-typescript'),
],
plugins: [
require.resolve('babel7-plugin-add-module-exports'),
// stage 3
require.resolve('@babel/plugin-proposal-async-generator-functions'),
require.resolve('@babel/plugin-proposal-object-rest-spread'),
// the class properties proposal was merged with the private fields proposal
// into the "class fields" proposal. Babel doesn't support this combined
// proposal yet, which includes private field, so this transform is
// TECHNICALLY stage 2, but for all intents and purposes it's stage 3
//
// See https://github.com/babel/proposals/issues/12 for progress
require.resolve('@babel/plugin-proposal-class-properties'),
],
};

View file

@ -17,34 +17,37 @@
* under the License.
*/
module.exports = {
presets: [
[
require.resolve('babel-preset-env'),
{
targets: {
// only applies the necessary transformations based on the
// current node.js processes version. For example: running
// `nvm install 8 && node ./src/cli` will run kibana in node
// version 8 and babel will stop transpiling async/await
// because they are supported in the "current" version of node
node: 'current',
},
module.exports = () => {
return {
presets: [
[
require.resolve('@babel/preset-env'),
{
targets: {
// only applies the necessary transformations based on the
// current node.js processes version. For example: running
// `nvm install 8 && node ./src/cli` will run kibana in node
// version 8 and babel will stop transpiling async/await
// because they are supported in the "current" version of node
node: 'current',
},
// replaces `import "babel-polyfill"` with a list of require statements
// for just the polyfills that the target versions don't already supply
// on their own
useBuiltIns: true,
},
// replaces `import "@babel/polyfill"` with a list of require statements
// for just the polyfills that the target versions don't already supply
// on their own
useBuiltIns: 'entry',
modules: 'cjs'
},
],
require('./common_preset'),
],
require('./common_preset'),
],
plugins: [
[
require.resolve('babel-plugin-transform-define'),
{
'global.__BUILT_WITH_BABEL__': 'true'
}
plugins: [
[
require.resolve('babel-plugin-transform-define'),
{
'global.__BUILT_WITH_BABEL__': 'true'
}
]
]
]
};
};

View file

@ -1,50 +0,0 @@
/*
* 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.
*/
module.exports = () => ({
presets: [
[
require.resolve('@babel/preset-env'),
{
targets: {
// only applies the necessary transformations based on the
// current node.js processes version. For example: running
// `nvm install 8 && node ./src/cli` will run kibana in node
// version 8 and babel will stop transpiling async/await
// because they are supported in the "current" version of node
node: 'current',
},
// replaces `import "babel-polyfill"` with a list of require statements
// for just the polyfills that the target versions don't already supply
// on their own
useBuiltIns: 'entry',
},
],
require('./common_preset_7'),
],
plugins: [
[
require.resolve('babel-plugin-transform-define'),
{
'global.__BUILT_WITH_BABEL__': 'true'
}
]
]
});

View file

@ -4,20 +4,12 @@
"version": "1.0.0",
"license": "Apache-2.0",
"dependencies": {
"@babel/core": "^7.3.4",
"@babel/plugin-proposal-async-generator-functions": "^7.2.0",
"@babel/plugin-proposal-class-properties": "^7.3.4",
"@babel/plugin-proposal-object-rest-spread": "^7.3.4",
"@babel/preset-react":"^7.0.0",
"@babel/preset-env": "^7.3.4",
"@babel/preset-react": "^7.0.0",
"@babel/preset-typescript": "^7.3.3",
"babel-plugin-add-module-exports": "^0.2.1",
"babel-plugin-transform-async-generator-functions": "^6.24.1",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-add-module-exports": "^1.0.0",
"babel-plugin-transform-define": "^1.3.1",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"babel7-plugin-add-module-exports": "npm:babel-plugin-add-module-exports@^1.0.0"
"babel-plugin-typescript-strip-namespaces": "^1.1.1"
}
}

View file

@ -17,21 +17,24 @@
* under the License.
*/
module.exports = {
presets: [
[
require.resolve('babel-preset-env'),
{
targets: {
browsers: [
'last 2 versions',
'> 5%',
'Safari 7', // for PhantomJS support: https://github.com/elastic/kibana/issues/27136
],
module.exports = () => {
return {
presets: [
[
require.resolve('@babel/preset-env'),
{
targets: {
browsers: [
'last 2 versions',
'> 5%',
'Safari 7', // for PhantomJS support: https://github.com/elastic/kibana/issues/27136
],
},
useBuiltIns: 'entry',
modules: 'cjs'
},
useBuiltIns: true,
},
],
require('./common_preset'),
]
],
require('./common_preset'),
]
};
};

View file

@ -19,9 +19,9 @@
"tslib": "^1.9.3"
},
"devDependencies": {
"@babel/cli": "^7.2.3",
"@kbn/babel-preset": "1.0.0",
"babel-cli": "^6.26.0",
"chance": "1.0.6",
"expect.js": "0.3.1"
"@kbn/expect": "1.0.0",
"chance": "1.0.6"
}
}

View file

@ -22,8 +22,8 @@
"@babel/preset-typescript": "^7.3.3",
"@kbn/babel-preset": "1.0.0",
"@kbn/dev-utils": "1.0.0",
"@kbn/expect": "1.0.0",
"del": "^3.0.0",
"expect.js": "0.3.1",
"getopts": "^2.2.3",
"supports-color": "^6.1.0",
"typescript": "^3.3.3333"

View file

@ -17,7 +17,7 @@
* under the License.
*/
import expect from 'expect.js';
import expect from '@kbn/expect';
import _ from 'lodash';
import { migrateFilter } from '../migrate_filter';

View file

@ -17,7 +17,7 @@
* under the License.
*/
import expect from 'expect.js';
import expect from '@kbn/expect';
import { buildEsQuery } from '../build_es_query';
import indexPattern from '../../__fixtures__/index_pattern_response.json';
import { fromKueryExpression, toElasticsearchQuery } from '../../kuery';

View file

@ -17,7 +17,7 @@
* under the License.
*/
import expect from 'expect.js';
import expect from '@kbn/expect';
import { decorateQuery } from '../decorate_query';
describe('Query decorator', function () {

View file

@ -17,7 +17,7 @@
* under the License.
*/
import expect from 'expect.js';
import expect from '@kbn/expect';
import { filterMatchesIndex } from '../filter_matches_index';
describe('filterMatchesIndex', function () {

View file

@ -17,7 +17,7 @@
* under the License.
*/
import expect from 'expect.js';
import expect from '@kbn/expect';
import { buildQueryFromFilters } from '../from_filters';
describe('build query', function () {

View file

@ -19,7 +19,7 @@
import { buildQueryFromKuery } from '../from_kuery';
import indexPattern from '../../__fixtures__/index_pattern_response.json';
import expect from 'expect.js';
import expect from '@kbn/expect';
import { fromKueryExpression, toElasticsearchQuery } from '../../kuery';
describe('build query', function () {

View file

@ -17,7 +17,7 @@
* under the License.
*/
import expect from 'expect.js';
import expect from '@kbn/expect';
import { buildQueryFromLucene } from '../from_lucene';
import { decorateQuery } from '../decorate_query';
import { luceneStringToDsl } from '../lucene_string_to_dsl';

View file

@ -18,7 +18,7 @@
*/
import { luceneStringToDsl } from '../lucene_string_to_dsl';
import expect from 'expect.js';
import expect from '@kbn/expect';
describe('build query', function () {

View file

@ -19,7 +19,7 @@
import { buildInlineScriptForPhraseFilter, buildPhraseFilter } from '../phrase';
import expect from 'expect.js';
import expect from '@kbn/expect';
import _ from 'lodash';
import indexPattern from '../../__fixtures__/index_pattern_response.json';
import filterSkeleton from '../../__fixtures__/filter_skeleton';

View file

@ -19,7 +19,7 @@
import { buildQueryFilter } from '../query';
import { cloneDeep } from 'lodash';
import expect from 'expect.js';
import expect from '@kbn/expect';
import indexPattern from '../../__fixtures__/index_pattern_response.json';
import filterSkeleton from '../../__fixtures__/filter_skeleton';

View file

@ -18,7 +18,7 @@
*/
import { buildRangeFilter } from '../range';
import expect from 'expect.js';
import expect from '@kbn/expect';
import _ from 'lodash';
import indexPattern from '../../__fixtures__/index_pattern_response.json';
import filterSkeleton from '../../__fixtures__/filter_skeleton';

View file

@ -18,7 +18,7 @@
*/
import * as ast from '../ast';
import expect from 'expect.js';
import expect from '@kbn/expect';
import { nodeTypes } from '../../node_types/index';
import indexPatternResponse from '../../../__fixtures__/index_pattern_response.json';

View file

@ -17,7 +17,7 @@
* under the License.
*/
import expect from 'expect.js';
import expect from '@kbn/expect';
import { convertExistsFilter } from '../exists';
describe('filter to kuery migration', function () {

View file

@ -18,7 +18,7 @@
*/
import _ from 'lodash';
import expect from 'expect.js';
import expect from '@kbn/expect';
import { filterToKueryAST } from '../filter_to_kuery';
describe('filter to kuery migration', function () {

View file

@ -18,7 +18,7 @@
*/
import _ from 'lodash';
import expect from 'expect.js';
import expect from '@kbn/expect';
import { convertGeoBoundingBox } from '../geo_bounding_box';
describe('filter to kuery migration', function () {

View file

@ -17,7 +17,7 @@
* under the License.
*/
import expect from 'expect.js';
import expect from '@kbn/expect';
import { convertGeoPolygon } from '../geo_polygon';
describe('filter to kuery migration', function () {

View file

@ -17,7 +17,7 @@
* under the License.
*/
import expect from 'expect.js';
import expect from '@kbn/expect';
import { convertPhraseFilter } from '../phrase';
describe('filter to kuery migration', function () {

View file

@ -18,7 +18,7 @@
*/
import _ from 'lodash';
import expect from 'expect.js';
import expect from '@kbn/expect';
import { convertRangeFilter } from '../range';
describe('filter to kuery migration', function () {

View file

@ -17,7 +17,7 @@
* under the License.
*/
import expect from 'expect.js';
import expect from '@kbn/expect';
import * as and from '../and';
import { nodeTypes } from '../../node_types';
import * as ast from '../../ast';

View file

@ -17,7 +17,7 @@
* under the License.
*/
import expect from 'expect.js';
import expect from '@kbn/expect';
import * as exists from '../exists';
import { nodeTypes } from '../../node_types';
import _ from 'lodash';

View file

@ -17,7 +17,7 @@
* under the License.
*/
import expect from 'expect.js';
import expect from '@kbn/expect';
import * as geoBoundingBox from '../geo_bounding_box';
import { nodeTypes } from '../../node_types';
import indexPatternResponse from '../../../__fixtures__/index_pattern_response.json';

View file

@ -17,7 +17,7 @@
* under the License.
*/
import expect from 'expect.js';
import expect from '@kbn/expect';
import * as geoPolygon from '../geo_polygon';
import { nodeTypes } from '../../node_types';
import indexPatternResponse from '../../../__fixtures__/index_pattern_response.json';

View file

@ -17,7 +17,7 @@
* under the License.
*/
import expect from 'expect.js';
import expect from '@kbn/expect';
import * as is from '../is';
import { nodeTypes } from '../../node_types';
import indexPatternResponse from '../../../__fixtures__/index_pattern_response.json';

View file

@ -17,7 +17,7 @@
* under the License.
*/
import expect from 'expect.js';
import expect from '@kbn/expect';
import * as not from '../not';
import { nodeTypes } from '../../node_types';
import * as ast from '../../ast';

View file

@ -17,7 +17,7 @@
* under the License.
*/
import expect from 'expect.js';
import expect from '@kbn/expect';
import * as or from '../or';
import { nodeTypes } from '../../node_types';
import * as ast from '../../ast';

View file

@ -17,7 +17,7 @@
* under the License.
*/
import expect from 'expect.js';
import expect from '@kbn/expect';
import * as range from '../range';
import { nodeTypes } from '../../node_types';
import indexPatternResponse from '../../../__fixtures__/index_pattern_response.json';

View file

@ -18,7 +18,7 @@
*/
import { getFields } from '../../utils/get_fields';
import expect from 'expect.js';
import expect from '@kbn/expect';
import indexPatternResponse from '../../../../__fixtures__/index_pattern_response.json';
import { nodeTypes } from '../../..';

View file

@ -19,7 +19,7 @@
import * as functionType from '../function';
import _ from 'lodash';
import expect from 'expect.js';
import expect from '@kbn/expect';
import * as isFunction from '../../functions/is';
import indexPatternResponse from '../../../__fixtures__/index_pattern_response.json';

View file

@ -17,7 +17,7 @@
* under the License.
*/
import expect from 'expect.js';
import expect from '@kbn/expect';
import * as literal from '../literal';
describe('kuery node types', function () {

View file

@ -17,7 +17,7 @@
* under the License.
*/
import expect from 'expect.js';
import expect from '@kbn/expect';
import * as namedArg from '../named_arg';
import { nodeTypes } from '../../node_types';

View file

@ -17,7 +17,7 @@
* under the License.
*/
import expect from 'expect.js';
import expect from '@kbn/expect';
import * as wildcard from '../wildcard';
describe('kuery node types', function () {

View file

@ -6,6 +6,7 @@
"private": true,
"dependencies": {
"@kbn/dev-utils": "1.0.0",
"abort-controller": "^2.0.3",
"chalk": "^2.4.1",
"dedent": "^0.7.0",
"del": "^3.0.0",

View file

@ -0,0 +1,307 @@
/*
* 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 fetch = require('node-fetch');
const AbortController = require('abort-controller');
const fs = require('fs');
const { promisify } = require('util');
const { pipeline, Transform } = require('stream');
const mkdirp = require('mkdirp');
const chalk = require('chalk');
const { createHash } = require('crypto');
const path = require('path');
const asyncPipeline = promisify(pipeline);
const V1_VERSIONS_API = 'https://artifacts-api.elastic.co/v1/versions';
const { cache } = require('./utils');
const { createCliError } = require('./errors');
const TEST_ES_SNAPSHOT_VERSION = process.env.TEST_ES_SNAPSHOT_VERSION
? process.env.TEST_ES_SNAPSHOT_VERSION
: 'latest';
function getChecksumType(checksumUrl) {
if (checksumUrl.endsWith('.sha512')) {
return 'sha512';
}
throw new Error(`unable to determine checksum type: ${checksumUrl}`);
}
function getPlatform(key) {
if (key.includes('-linux-')) {
return 'linux';
}
if (key.includes('-windows-')) {
return 'win32';
}
if (key.includes('-darwin-')) {
return 'darwin';
}
}
function headersToString(headers, indent = '') {
return [...headers.entries()].reduce(
(acc, [key, value]) => `${acc}\n${indent}${key}: ${value}`,
''
);
}
exports.Artifact = class Artifact {
/**
* Fetch an Artifact from the Artifact API for a license level and version
* @param {('oss'|'basic'|'trial')} license
* @param {string} version
* @param {ToolingLog} log
*/
static async get(license, version, log) {
const urlVersion = `${encodeURIComponent(version)}-SNAPSHOT`;
const urlBuild = encodeURIComponent(TEST_ES_SNAPSHOT_VERSION);
const url = `${V1_VERSIONS_API}/${urlVersion}/builds/${urlBuild}/projects/elasticsearch`;
log.info('downloading artifact info from %s', chalk.bold(url));
const abc = new AbortController();
const resp = await fetch(url, { signal: abc.signal });
const json = await resp.text();
if (resp.status === 404) {
abc.abort();
throw createCliError(
`Snapshots for ${version}/${TEST_ES_SNAPSHOT_VERSION} are not available`
);
}
if (!resp.ok) {
abc.abort();
throw new Error(`Unable to read artifact info from ${url}: ${resp.statusText}\n ${json}`);
}
// parse the api response into an array of Artifact objects
const {
project: { packages: artifactInfoMap },
} = JSON.parse(json);
const filenames = Object.keys(artifactInfoMap);
const hasNoJdkVersions = filenames.some(filename => filename.includes('-no-jdk-'));
const artifactSpecs = filenames.map(filename => ({
filename,
url: artifactInfoMap[filename].url,
checksumUrl: artifactInfoMap[filename].sha_url,
checksumType: getChecksumType(artifactInfoMap[filename].sha_url),
type: artifactInfoMap[filename].type,
isOss: filename.includes('-oss-'),
platform: getPlatform(filename),
jdkRequired: hasNoJdkVersions ? filename.includes('-no-jdk-') : true,
}));
// pick the artifact we are going to use for this license/version combo
const reqOss = license === 'oss';
const reqPlatform = artifactSpecs.some(a => a.platform !== undefined)
? process.platform
: undefined;
const reqJdkRequired = hasNoJdkVersions ? false : true;
const reqType = process.platform === 'win32' ? 'zip' : 'tar';
const artifactSpec = artifactSpecs.find(
spec =>
spec.isOss === reqOss &&
spec.type === reqType &&
spec.platform === reqPlatform &&
spec.jdkRequired === reqJdkRequired
);
if (!artifactSpec) {
throw new Error(
`Unable to determine artifact for license [${license}] and version [${version}]\n` +
` options: ${filenames.join(',')}`
);
}
return new Artifact(artifactSpec, log);
}
constructor(spec, log) {
this._spec = spec;
this._log = log;
}
getUrl() {
return this._spec.url;
}
getChecksumUrl() {
return this._spec.checksumUrl;
}
getChecksumType() {
return this._spec.checksumType;
}
getFilename() {
return this._spec.filename;
}
/**
* Download the artifact to disk, skips the download if the cache is
* up-to-date, verifies checksum when downloaded
* @param {string} dest
* @return {Promise<void>}
*/
async download(dest) {
const cacheMeta = cache.readMeta(dest);
const tmpPath = `${dest}.tmp`;
const artifactResp = await this._download(tmpPath, cacheMeta.etag, cacheMeta.ts);
if (artifactResp.cached) {
return;
}
await this._verifyChecksum(artifactResp);
// cache the etag for future downloads
cache.writeMeta(dest, { etag: artifactResp.etag });
// rename temp download to the destination location
fs.renameSync(tmpPath, dest);
}
/**
* Fetch the artifact with an etag
* @param {string} tmpPath
* @param {string} etag
* @param {string} ts
* @return {{ cached: true }|{ checksum: string, etag: string, first500Bytes: Buffer }}
*/
async _download(tmpPath, etag, ts) {
const url = this.getUrl();
if (etag) {
this._log.info('verifying cache of %s', chalk.bold(url));
} else {
this._log.info('downloading artifact from %s', chalk.bold(url));
}
const abc = new AbortController();
const resp = await fetch(url, {
signal: abc.signal,
headers: {
'If-None-Match': etag,
},
});
if (resp.status === 304) {
this._log.info('etags match, reusing cache from %s', chalk.bold(ts));
abc.abort();
return {
cached: true,
};
}
if (!resp.ok) {
abc.abort();
throw new Error(
`Unable to download elasticsearch snapshot: ${resp.statusText}${headersToString(
resp.headers,
' '
)}`
);
}
if (etag) {
this._log.info('cache invalid, redownloading');
}
const hash = createHash(this.getChecksumType());
let first500Bytes = Buffer.alloc(0);
let contentLength = 0;
mkdirp.sync(path.dirname(tmpPath));
await asyncPipeline(
resp.body,
new Transform({
transform(chunk, encoding, cb) {
contentLength += Buffer.byteLength(chunk);
if (first500Bytes.length < 500) {
first500Bytes = Buffer.concat(
[first500Bytes, chunk],
first500Bytes.length + chunk.length
).slice(0, 500);
}
hash.update(chunk, encoding);
cb(null, chunk);
},
}),
fs.createWriteStream(tmpPath)
);
return {
checksum: hash.digest('hex'),
etag: resp.headers.get('etag'),
contentLength,
first500Bytes,
headers: resp.headers,
};
}
/**
* Verify the checksum of the downloaded artifact with the checksum at checksumUrl
* @param {{ checksum: string, contentLength: number, first500Bytes: Buffer }} artifactResp
* @return {Promise<void>}
*/
async _verifyChecksum(artifactResp) {
this._log.info('downloading artifact checksum from %s', chalk.bold(this.getChecksumUrl()));
const abc = new AbortController();
const resp = await fetch(this.getChecksumUrl(), {
signal: abc.signal,
});
if (!resp.ok) {
abc.abort();
throw new Error(
`Unable to download elasticsearch checksum: ${resp.statusText}${headersToString(
resp.headers,
' '
)}`
);
}
// in format of stdout from `shasum` cmd, which is `<checksum> <filename>`
const [expectedChecksum] = (await resp.text()).split(' ');
if (artifactResp.checksum !== expectedChecksum) {
const len = Buffer.byteLength(artifactResp.first500Bytes);
const lenString = `${len} / ${artifactResp.contentLength}`;
throw createCliError(
`artifact downloaded from ${this.getUrl()} does not match expected checksum\n` +
` expected: ${expectedChecksum}\n` +
` received: ${artifactResp.checksum}\n` +
` headers: ${headersToString(artifactResp.headers, ' ')}\n` +
` content[${lenString} base64]: ${artifactResp.first500Bytes.toString('base64')}`
);
}
this._log.info('checksum verified');
}
};

View file

@ -17,15 +17,12 @@
* under the License.
*/
const fetch = require('node-fetch');
const fs = require('fs');
const os = require('os');
const mkdirp = require('mkdirp');
const chalk = require('chalk');
const path = require('path');
const { BASE_PATH } = require('../paths');
const { installArchive } = require('./archive');
const { log: defaultLog, cache } = require('../utils');
const { log: defaultLog } = require('../utils');
const { Artifact } = require('../artifact');
/**
* Download an ES snapshot
@ -44,15 +41,13 @@ exports.downloadSnapshot = async function installSnapshot({
installPath = path.resolve(basePath, version),
log = defaultLog,
}) {
const fileName = getFilename(license, version);
const url = getUrl(fileName);
const dest = path.resolve(basePath, 'cache', fileName);
log.info('version: %s', chalk.bold(version));
log.info('install path: %s', chalk.bold(installPath));
log.info('license: %s', chalk.bold(license));
await downloadFile(url, dest, log);
const artifact = await Artifact.get(license, version, log);
const dest = path.resolve(basePath, 'cache', artifact.getFilename());
await artifact.download(dest);
return {
downloadPath: dest,
@ -94,83 +89,3 @@ exports.installSnapshot = async function installSnapshot({
log,
});
};
/**
* Downloads to tmp and moves once complete
*
* @param {String} url
* @param {String} dest
* @param {ToolingLog} log
* @returns {Promise}
*/
function downloadFile(url, dest, log) {
const downloadPath = `${dest}.tmp`;
const cacheMeta = cache.readMeta(dest);
mkdirp.sync(path.dirname(dest));
log.info('downloading from %s', chalk.bold(url));
return fetch(url, { headers: { 'If-None-Match': cacheMeta.etag } }).then(
res =>
new Promise((resolve, reject) => {
if (res.status === 304) {
log.info('etags match, using cache from %s', chalk.bold(cacheMeta.ts));
return resolve();
}
if (!res.ok) {
return reject(new Error(`Unable to download elasticsearch snapshot: ${res.statusText}`));
}
const stream = fs.createWriteStream(downloadPath);
res.body
.pipe(stream)
.on('error', error => {
reject(error);
})
.on('finish', () => {
if (res.ok) {
const etag = res.headers.get('etag');
cache.writeMeta(dest, { etag });
fs.renameSync(downloadPath, dest);
resolve();
} else {
reject(new Error(res.statusText));
}
});
})
);
}
function getFilename(license, version) {
const platform = os.platform();
let suffix = null;
switch (platform) {
case 'darwin':
suffix = 'darwin-x86_64.tar.gz';
break;
case 'linux':
suffix = 'linux-x86_64.tar.gz';
break;
case 'win32':
suffix = 'windows-x86_64.zip';
break;
default:
throw new Error(`Unsupported platform ${platform}`);
}
const basename = `elasticsearch${license === 'oss' ? '-oss-' : '-'}${version}`;
return `${basename}-SNAPSHOT-${suffix}`;
}
function getUrl(fileName) {
if (process.env.TEST_ES_SNAPSHOT_VERSION) {
return `https://snapshots.elastic.co/${
process.env.TEST_ES_SNAPSHOT_VERSION
}/downloads/elasticsearch/${fileName}`;
} else {
return `https://snapshots.elastic.co/downloads/elasticsearch/${fileName}`;
}
}

View file

@ -22,5 +22,7 @@ module.exports = {
'require-license-header': require('./rules/require_license_header'),
'disallow-license-headers': require('./rules/disallow_license_headers'),
'no-default-export': require('./rules/no_default_export'),
'no-restricted-paths': require('./rules/no_restricted_paths'),
module_migration: require('./rules/module_migration'),
},
};

View file

@ -4,10 +4,12 @@
"private": true,
"license": "Apache-2.0",
"peerDependencies": {
"eslint": "^5.6.0",
"babel-eslint": "^9.0.0"
"eslint": "^5.14.1",
"babel-eslint": "^10.0.1"
},
"dependencies": {
"dedent": "^0.7.0"
"micromatch": "3.1.10",
"dedent": "^0.7.0",
"eslint-module-utils": "^2.3.0"
}
}

View file

@ -0,0 +1 @@
/* eslint-disable */

View file

@ -0,0 +1 @@
/* eslint-disable */

View file

@ -0,0 +1 @@
/* eslint-disable */

View file

@ -0,0 +1,283 @@
/* eslint-disable-line @kbn/eslint/require-license-header */
/*
* This product uses import/no-restricted-paths which is available under a
* "MIT" license.
*
* The MIT License (MIT)
*
* Copyright (c) 2015-present, Ben Mosher
* https://github.com/benmosher/eslint-plugin-import
*
* 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.
*/
const path = require('path');
const { RuleTester } = require('eslint');
const rule = require('../no_restricted_paths');
const ruleTester = new RuleTester({
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module',
ecmaVersion: 2015,
},
});
ruleTester.run('@kbn/eslint/no-restricted-paths', rule, {
valid: [
{
code: 'import a from "../client/a.js"',
filename: path.join(__dirname, './files/no_restricted_paths/server/b.js'),
options: [
{
basePath: __dirname,
zones: [
{
target: 'files/no_restricted_paths/server/**/*',
from: 'files/no_restricted_paths/other/**/*',
},
],
},
],
},
{
code: 'const a = require("../client/a.js")',
filename: path.join(__dirname, './files/no_restricted_paths/server/b.js'),
options: [
{
basePath: __dirname,
zones: [
{
target: 'files/no_restricted_paths/server/**/*',
from: 'files/no_restricted_paths/other/**/*',
},
],
},
],
},
{
code: 'import b from "../server/b.js"',
filename: path.join(__dirname, './files/no_restricted_paths/client/a.js'),
options: [
{
basePath: __dirname,
zones: [
{
target: '**/no_restricted_paths/client/**/*',
from: '**/no_restricted_paths/other/**/*',
},
],
},
],
},
// irrelevant function calls
{
code: 'notrequire("../server/b.js")',
options: [
{
basePath: __dirname,
},
],
},
{
code: 'notrequire("../server/b.js")',
filename: path.join(__dirname, './files/no_restricted_paths/client/a.js'),
options: [
{
basePath: __dirname,
zones: [
{
target: 'files/no_restricted_paths/client/**/*',
from: 'files/no_restricted_paths/server/**/*',
},
],
},
],
},
// no config
{
code: 'require("../server/b.js")',
options: [
{
basePath: __dirname,
},
],
},
{
code: 'import b from "../server/b.js"',
options: [
{
basePath: __dirname,
},
],
},
// builtin (ignore)
{
code: 'require("os")',
options: [
{
basePath: __dirname,
},
],
},
{
code: 'const d = require("./deep/d.js")',
filename: path.join(__dirname, './files/no_restricted_paths/server/b.js'),
options: [
{
basePath: __dirname,
zones: [
{
allowSameFolder: true,
target: 'files/no_restricted_paths/**/*',
from: 'files/no_restricted_paths/**/*',
},
],
},
],
},
],
invalid: [
{
code: 'import b from "../server/b.js"',
filename: path.join(__dirname, './files/no_restricted_paths/client/a.js'),
options: [
{
basePath: __dirname,
zones: [
{
target: 'files/no_restricted_paths/client/**/*',
from: 'files/no_restricted_paths/server/**/*',
},
],
},
],
errors: [
{
message: 'Unexpected path "../server/b.js" imported in restricted zone.',
line: 1,
column: 15,
},
],
},
{
code: 'import a from "../client/a"\nimport c from "./c"',
filename: path.join(__dirname, './files/no_restricted_paths/server/b.js'),
options: [
{
basePath: __dirname,
zones: [
{
target: 'files/no_restricted_paths/server/**/*',
from: 'files/no_restricted_paths/client/**/*',
},
{
target: 'files/no_restricted_paths/server/**/*',
from: 'files/no_restricted_paths/server/c.js',
},
],
},
],
errors: [
{
message: 'Unexpected path "../client/a" imported in restricted zone.',
line: 1,
column: 15,
},
{
message: 'Unexpected path "./c" imported in restricted zone.',
line: 2,
column: 15,
},
],
},
{
code: 'const b = require("../server/b.js")',
filename: path.join(__dirname, './files/no_restricted_paths/client/a.js'),
options: [
{
basePath: __dirname,
zones: [
{
target: '**/no_restricted_paths/client/**/*',
from: '**/no_restricted_paths/server/**/*',
},
],
},
],
errors: [
{
message: 'Unexpected path "../server/b.js" imported in restricted zone.',
line: 1,
column: 19,
},
],
},
{
code: 'const b = require("../server/b.js")',
filename: path.join(__dirname, './files/no_restricted_paths/client/a.js'),
options: [
{
basePath: path.join(__dirname, 'files', 'no_restricted_paths'),
zones: [
{
target: 'client/**/*',
from: 'server/**/*',
},
],
},
],
errors: [
{
message: 'Unexpected path "../server/b.js" imported in restricted zone.',
line: 1,
column: 19,
},
],
},
{
code: 'const d = require("./deep/d.js")',
filename: path.join(__dirname, './files/no_restricted_paths/server/b.js'),
options: [
{
basePath: __dirname,
zones: [
{
target: 'files/no_restricted_paths/**/*',
from: 'files/no_restricted_paths/**/*',
},
],
},
],
errors: [
{
message: 'Unexpected path "./deep/d.js" imported in restricted zone.',
line: 1,
column: 19,
},
],
},
],
});

View file

@ -0,0 +1,82 @@
/*
* 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 checkModuleNameNode(context, mappings, node) {
const mapping = mappings.find(
mapping => mapping.from === node.value || mapping.from.startsWith(node.value + '/')
);
if (!mapping) {
return;
}
const newSource = node.value.replace(mapping.from, mapping.to);
context.report({
message: `Imported module "${node.value}" should be "${newSource}"`,
loc: node.loc,
fix(fixer) {
return fixer.replaceText(node, `'${newSource}'`);
},
});
}
module.exports = {
meta: {
fixable: 'code',
schema: [
{
type: 'array',
items: {
type: 'object',
properties: {
from: {
type: 'string',
},
to: {
type: 'string',
},
},
required: ['from', 'to'],
additionalProperties: false,
},
default: [],
minItems: 1,
},
],
},
create: context => {
const mappings = context.options[0];
return {
ImportDeclaration(node) {
checkModuleNameNode(context, mappings, node.source);
},
CallExpression(node) {
if (
node.callee.type === 'Identifier' &&
node.callee.name === 'require' &&
node.arguments.length === 1 &&
node.arguments[0].type === 'Literal'
) {
checkModuleNameNode(context, mappings, node.arguments[0]);
}
},
};
},
};

View file

@ -0,0 +1,135 @@
/* eslint-disable-line @kbn/eslint/require-license-header */
/*
* This product uses import/no-restricted-paths which is available under a
* "MIT" license.
*
* The MIT License (MIT)
*
* Copyright (c) 2015-present, Ben Mosher
* https://github.com/benmosher/eslint-plugin-import
*
* 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.
*/
const path = require('path');
const resolve = require('eslint-module-utils/resolve').default;
const mm = require('micromatch');
function isStaticRequire(node) {
return (
node &&
node.callee &&
node.callee.type === 'Identifier' &&
node.callee.name === 'require' &&
node.arguments.length === 1 &&
node.arguments[0].type === 'Literal' &&
typeof node.arguments[0].value === 'string'
);
}
function traverseToTopFolder(src, pattern) {
while (mm([src], pattern).length > 0) {
const srcIdx = src.lastIndexOf(path.sep);
src = src.slice(0, srcIdx);
}
return src;
}
function isSameFolderOrDescendent(src, imported, pattern) {
const srcFileFolderRoot = traverseToTopFolder(src, pattern);
const importedFileFolderRoot = traverseToTopFolder(imported, pattern);
return srcFileFolderRoot === importedFileFolderRoot;
}
module.exports = {
meta: {
schema: [
{
type: 'object',
properties: {
zones: {
type: 'array',
minItems: 1,
items: {
type: 'object',
properties: {
target: {
anyOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }],
},
from: {
anyOf: [{ type: 'string' }, { type: 'array', items: { type: 'string' } }],
},
allowSameFolder: { type: 'boolean' },
},
additionalProperties: false,
},
},
basePath: { type: 'string' },
},
additionalProperties: false,
},
],
},
create(context) {
const options = context.options[0] || {};
const zones = options.zones || [];
const basePath = options.basePath;
if (!basePath || !path.isAbsolute(basePath)) {
throw new Error('basePath option must be specified and must be absolute');
}
function checkForRestrictedImportPath(importPath, node) {
const absoluteImportPath = resolve(importPath, context);
if (!absoluteImportPath) return;
const currentFilename = context.getFilename();
for (const { target, from, allowSameFolder } of zones) {
const srcFilePath = resolve(currentFilename, context);
const relativeSrcFile = path.relative(basePath, srcFilePath);
const relativeImportFile = path.relative(basePath, absoluteImportPath);
if (
!mm([relativeSrcFile], target).length ||
!mm([relativeImportFile], from).length ||
(allowSameFolder && isSameFolderOrDescendent(relativeSrcFile, relativeImportFile, from))
)
continue;
context.report({
node,
message: `Unexpected path "${importPath}" imported in restricted zone.`,
});
}
}
return {
ImportDeclaration(node) {
checkForRestrictedImportPath(node.source.value, node.source);
},
CallExpression(node) {
if (isStaticRequire(node)) {
const [firstArgument] = node.arguments;
checkForRestrictedImportPath(firstArgument.value, firstArgument);
}
},
};
},
};

View file

@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) 2011 Guillermo Rauch <guillermo@learnboost.com>
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.

View file

@ -0,0 +1,191 @@
> NOTE: This is a local fork of https://github.com/Automattic/expect.js
# @kbn/expect
Minimalistic BDD assertion toolkit based on
[should.js](http://github.com/visionmedia/should.js)
```js
expect(window.r).to.be(undefined);
expect({ a: 'b' }).to.eql({ a: 'b' })
expect(5).to.be.a('number');
expect([]).to.be.an('array');
expect(window).not.to.be.an(Image);
```
## Features
- Cross-browser: works on IE6+, Firefox, Safari, Chrome, Opera.
- Compatible with all test frameworks.
- Node.JS ready (`require('@kbn/expect')`).
## API
**ok**: asserts that the value is _truthy_ or not
```js
expect(1).to.be.ok();
expect(true).to.be.ok();
expect({}).to.be.ok();
expect(0).to.not.be.ok();
```
**be** / **equal**: asserts `===` equality
```js
expect(1).to.be(1)
expect(NaN).not.to.equal(NaN);
expect(1).not.to.be(true)
expect('1').to.not.be(1);
```
**eql**: asserts loose equality that works with objects
```js
expect({ a: 'b' }).to.eql({ a: 'b' });
expect(1).to.eql('1');
```
**a**/**an**: asserts `typeof` with support for `array` type and `instanceof`
```js
// typeof with optional `array`
expect(5).to.be.a('number');
expect([]).to.be.an('array'); // works
expect([]).to.be.an('object'); // works too, since it uses `typeof`
// constructors
expect([]).to.be.an(Array);
expect(tobi).to.be.a(Ferret);
expect(person).to.be.a(Mammal);
```
**match**: asserts `String` regular expression match
```js
expect(program.version).to.match(/[0-9]+\.[0-9]+\.[0-9]+/);
```
**contain**: asserts indexOf for an array or string
```js
expect([1, 2]).to.contain(1);
expect('hello world').to.contain('world');
```
**length**: asserts array `.length`
```js
expect([]).to.have.length(0);
expect([1,2,3]).to.have.length(3);
```
**empty**: asserts that an array is empty or not
```js
expect([]).to.be.empty();
expect({}).to.be.empty();
expect({ length: 0, duck: 'typing' }).to.be.empty();
expect({ my: 'object' }).to.not.be.empty();
expect([1,2,3]).to.not.be.empty();
```
**property**: asserts presence of an own property (and value optionally)
```js
expect(window).to.have.property('expect')
expect(window).to.have.property('expect', expect)
expect({a: 'b'}).to.have.property('a');
```
**key**/**keys**: asserts the presence of a key. Supports the `only` modifier
```js
expect({ a: 'b' }).to.have.key('a');
expect({ a: 'b', c: 'd' }).to.only.have.keys('a', 'c');
expect({ a: 'b', c: 'd' }).to.only.have.keys(['a', 'c']);
expect({ a: 'b', c: 'd' }).to.not.only.have.key('a');
```
**throw**/**throwException**/**throwError**: asserts that the `Function` throws or not when called
```js
expect(fn).to.throw(); // synonym of throwException
expect(fn).to.throwError(); // synonym of throwException
expect(fn).to.throwException(function (e) { // get the exception object
expect(e).to.be.a(SyntaxError);
});
expect(fn).to.throwException(/matches the exception message/);
expect(fn2).to.not.throwException();
```
**withArgs**: creates anonymous function to call fn with arguments
```js
expect(fn).withArgs(invalid, arg).to.throwException();
expect(fn).withArgs(valid, arg).to.not.throwException();
```
**within**: asserts a number within a range
```js
expect(1).to.be.within(0, Infinity);
```
**greaterThan**/**above**: asserts `>`
```js
expect(3).to.be.above(0);
expect(5).to.be.greaterThan(3);
```
**lessThan**/**below**: asserts `<`
```js
expect(0).to.be.below(3);
expect(1).to.be.lessThan(3);
```
**fail**: explicitly forces failure.
```js
expect().fail()
expect().fail("Custom failure message")
```
## Using with a test framework
For example, if you create a test suite with
[mocha](http://github.com/visionmedia/mocha).
Let's say we wanted to test the following program:
**math.js**
```js
function add (a, b) { return a + b; };
```
Our test file would look like this:
```js
describe('test suite', function () {
it('should expose a function', function () {
expect(add).to.be.a('function');
});
it('should do math', function () {
expect(add(1, 3)).to.equal(4);
});
});
```
If a certain expectation fails, an exception will be raised which gets captured
and shown/processed by the test runner.
## Differences with should.js
- No need for static `should` methods like `should.strictEqual`. For example,
`expect(obj).to.be(undefined)` works well.
- Some API simplifications / changes.
- API changes related to browser compatibility.

View file

@ -0,0 +1,971 @@
/* eslint-disable */
var exports = module.exports;
/**
* Exports.
*/
module.exports = expect;
expect.Assertion = Assertion;
/**
* Exports version.
*/
expect.version = '0.3.1';
/**
* Possible assertion flags.
*/
var flags = {
not: ['to', 'be', 'have', 'include', 'only']
, to: ['be', 'have', 'include', 'only', 'not']
, only: ['have']
, have: ['own']
, be: ['an']
};
function expect (obj) {
return new Assertion(obj);
}
/**
* Constructor
*
* @api private
*/
function Assertion (obj, flag, parent) {
this.obj = obj;
this.flags = {};
if (undefined != parent) {
this.flags[flag] = true;
for (var i in parent.flags) {
if (parent.flags.hasOwnProperty(i)) {
this.flags[i] = true;
}
}
}
var $flags = flag ? flags[flag] : keys(flags)
, self = this;
if ($flags) {
for (var i = 0, l = $flags.length; i < l; i++) {
// avoid recursion
if (this.flags[$flags[i]]) continue;
var name = $flags[i]
, assertion = new Assertion(this.obj, name, this)
if ('function' == typeof Assertion.prototype[name]) {
// clone the function, make sure we dont touch the prot reference
var old = this[name];
this[name] = function () {
return old.apply(self, arguments);
};
for (var fn in Assertion.prototype) {
if (Assertion.prototype.hasOwnProperty(fn) && fn != name) {
if (typeof this[name] === 'function' && fn === 'length') {
continue;
}
this[name][fn] = bind(assertion[fn], assertion);
}
}
} else {
this[name] = assertion;
}
}
}
}
/**
* Performs an assertion
*
* @api private
*/
Assertion.prototype.assert = function (truth, msg, error, expected) {
var msg = this.flags.not ? error : msg
, ok = this.flags.not ? !truth : truth
, err;
if (!ok) {
err = new Error(msg.call(this));
if (arguments.length > 3) {
err.actual = this.obj;
err.expected = expected;
err.showDiff = true;
}
throw err;
}
this.and = new Assertion(this.obj);
};
/**
* Check if the value is truthy
*
* @api public
*/
Assertion.prototype.ok = function () {
this.assert(
!!this.obj
, function(){ return 'expected ' + i(this.obj) + ' to be truthy' }
, function(){ return 'expected ' + i(this.obj) + ' to be falsy' });
};
/**
* Creates an anonymous function which calls fn with arguments.
*
* @api public
*/
Assertion.prototype.withArgs = function() {
expect(this.obj).to.be.a('function');
var fn = this.obj;
var args = Array.prototype.slice.call(arguments);
return expect(function() { fn.apply(null, args); });
};
/**
* Assert that the function throws.
*
* @param {Function|RegExp} callback, or regexp to match error string against
* @api public
*/
Assertion.prototype['throw'] =
Assertion.prototype.throwError =
Assertion.prototype.throwException = function (fn) {
expect(this.obj).to.be.a('function');
var thrown = false
, not = this.flags.not;
try {
this.obj();
} catch (e) {
if (isRegExp(fn)) {
var subject = 'string' == typeof e ? e : e.message;
if (not) {
expect(subject).to.not.match(fn);
} else {
expect(subject).to.match(fn);
}
} else if ('function' == typeof fn) {
fn(e);
}
thrown = true;
}
if (isRegExp(fn) && not) {
// in the presence of a matcher, ensure the `not` only applies to
// the matching.
this.flags.not = false;
}
var name = this.obj.name || 'fn';
this.assert(
thrown
, function(){ return 'expected ' + name + ' to throw an exception' }
, function(){ return 'expected ' + name + ' not to throw an exception' });
};
/**
* Checks if the array is empty.
*
* @api public
*/
Assertion.prototype.empty = function () {
var expectation;
if ('object' == typeof this.obj && null !== this.obj && !isArray(this.obj)) {
if ('number' == typeof this.obj.length) {
expectation = !this.obj.length;
} else {
expectation = !keys(this.obj).length;
}
} else {
if ('string' != typeof this.obj) {
expect(this.obj).to.be.an('object');
}
expect(this.obj).to.have.property('length');
expectation = !this.obj.length;
}
this.assert(
expectation
, function(){ return 'expected ' + i(this.obj) + ' to be empty' }
, function(){ return 'expected ' + i(this.obj) + ' to not be empty' });
return this;
};
/**
* Checks if the obj exactly equals another.
*
* @api public
*/
Assertion.prototype.be =
Assertion.prototype.equal = function (obj) {
this.assert(
obj === this.obj
, function(){ return 'expected ' + i(this.obj) + ' to equal ' + i(obj) }
, function(){ return 'expected ' + i(this.obj) + ' to not equal ' + i(obj) });
return this;
};
/**
* Checks if the obj sortof equals another.
*
* @api public
*/
Assertion.prototype.eql = function (obj) {
this.assert(
expect.eql(this.obj, obj)
, function(){ return 'expected ' + i(this.obj) + ' to sort of equal ' + i(obj) }
, function(){ return 'expected ' + i(this.obj) + ' to sort of not equal ' + i(obj) }
, obj);
return this;
};
/**
* Assert within start to finish (inclusive).
*
* @param {Number} start
* @param {Number} finish
* @api public
*/
Assertion.prototype.within = function (start, finish) {
var range = start + '..' + finish;
this.assert(
this.obj >= start && this.obj <= finish
, function(){ return 'expected ' + i(this.obj) + ' to be within ' + range }
, function(){ return 'expected ' + i(this.obj) + ' to not be within ' + range });
return this;
};
/**
* Assert typeof / instance of
*
* @api public
*/
Assertion.prototype.a =
Assertion.prototype.an = function (type) {
if ('string' == typeof type) {
// proper english in error msg
var n = /^[aeiou]/.test(type) ? 'n' : '';
// typeof with support for 'array'
this.assert(
'array' == type ? isArray(this.obj) :
'regexp' == type ? isRegExp(this.obj) :
'object' == type
? 'object' == typeof this.obj && null !== this.obj
: type == typeof this.obj
, function(){ return 'expected ' + i(this.obj) + ' to be a' + n + ' ' + type }
, function(){ return 'expected ' + i(this.obj) + ' not to be a' + n + ' ' + type });
} else {
// instanceof
var name = type.name || 'supplied constructor';
this.assert(
this.obj instanceof type
, function(){ return 'expected ' + i(this.obj) + ' to be an instance of ' + name }
, function(){ return 'expected ' + i(this.obj) + ' not to be an instance of ' + name });
}
return this;
};
/**
* Assert numeric value above _n_.
*
* @param {Number} n
* @api public
*/
Assertion.prototype.greaterThan =
Assertion.prototype.above = function (n) {
this.assert(
this.obj > n
, function(){ return 'expected ' + i(this.obj) + ' to be above ' + n }
, function(){ return 'expected ' + i(this.obj) + ' to be below ' + n });
return this;
};
/**
* Assert numeric value below _n_.
*
* @param {Number} n
* @api public
*/
Assertion.prototype.lessThan =
Assertion.prototype.below = function (n) {
this.assert(
this.obj < n
, function(){ return 'expected ' + i(this.obj) + ' to be below ' + n }
, function(){ return 'expected ' + i(this.obj) + ' to be above ' + n });
return this;
};
/**
* Assert string value matches _regexp_.
*
* @param {RegExp} regexp
* @api public
*/
Assertion.prototype.match = function (regexp) {
this.assert(
regexp.exec(this.obj)
, function(){ return 'expected ' + i(this.obj) + ' to match ' + regexp }
, function(){ return 'expected ' + i(this.obj) + ' not to match ' + regexp });
return this;
};
/**
* Assert property "length" exists and has value of _n_.
*
* @param {Number} n
* @api public
*/
Assertion.prototype.length = function (n) {
expect(this.obj).to.have.property('length');
var len = this.obj.length;
this.assert(
n == len
, function(){ return 'expected ' + i(this.obj) + ' to have a length of ' + n + ' but got ' + len }
, function(){ return 'expected ' + i(this.obj) + ' to not have a length of ' + len });
return this;
};
/**
* Assert property _name_ exists, with optional _val_.
*
* @param {String} name
* @param {Mixed} val
* @api public
*/
Assertion.prototype.property = function (name, val) {
if (this.flags.own) {
this.assert(
Object.prototype.hasOwnProperty.call(this.obj, name)
, function(){ return 'expected ' + i(this.obj) + ' to have own property ' + i(name) }
, function(){ return 'expected ' + i(this.obj) + ' to not have own property ' + i(name) });
return this;
}
if (this.flags.not && undefined !== val) {
if (undefined === this.obj[name]) {
throw new Error(i(this.obj) + ' has no property ' + i(name));
}
} else {
var hasProp;
try {
hasProp = name in this.obj
} catch (e) {
hasProp = undefined !== this.obj[name]
}
this.assert(
hasProp
, function(){ return 'expected ' + i(this.obj) + ' to have a property ' + i(name) }
, function(){ return 'expected ' + i(this.obj) + ' to not have a property ' + i(name) });
}
if (undefined !== val) {
this.assert(
val === this.obj[name]
, function(){ return 'expected ' + i(this.obj) + ' to have a property ' + i(name)
+ ' of ' + i(val) + ', but got ' + i(this.obj[name]) }
, function(){ return 'expected ' + i(this.obj) + ' to not have a property ' + i(name)
+ ' of ' + i(val) });
}
this.obj = this.obj[name];
return this;
};
/**
* Assert that the array contains _obj_ or string contains _obj_.
*
* @param {Mixed} obj|string
* @api public
*/
Assertion.prototype.string =
Assertion.prototype.contain = function (obj) {
if ('string' == typeof this.obj) {
this.assert(
~this.obj.indexOf(obj)
, function(){ return 'expected ' + i(this.obj) + ' to contain ' + i(obj) }
, function(){ return 'expected ' + i(this.obj) + ' to not contain ' + i(obj) });
} else {
this.assert(
~indexOf(this.obj, obj)
, function(){ return 'expected ' + i(this.obj) + ' to contain ' + i(obj) }
, function(){ return 'expected ' + i(this.obj) + ' to not contain ' + i(obj) });
}
return this;
};
/**
* Assert exact keys or inclusion of keys by using
* the `.own` modifier.
*
* @param {Array|String ...} keys
* @api public
*/
Assertion.prototype.key =
Assertion.prototype.keys = function ($keys) {
var str
, ok = true;
$keys = isArray($keys)
? $keys
: Array.prototype.slice.call(arguments);
if (!$keys.length) throw new Error('keys required');
var actual = keys(this.obj)
, len = $keys.length;
// Inclusion
ok = every($keys, function (key) {
return ~indexOf(actual, key);
});
// Strict
if (!this.flags.not && this.flags.only) {
ok = ok && $keys.length == actual.length;
}
// Key string
if (len > 1) {
$keys = map($keys, function (key) {
return i(key);
});
var last = $keys.pop();
str = $keys.join(', ') + ', and ' + last;
} else {
str = i($keys[0]);
}
// Form
str = (len > 1 ? 'keys ' : 'key ') + str;
// Have / include
str = (!this.flags.only ? 'include ' : 'only have ') + str;
// Assertion
this.assert(
ok
, function(){ return 'expected ' + i(this.obj) + ' to ' + str }
, function(){ return 'expected ' + i(this.obj) + ' to not ' + str });
return this;
};
/**
* Assert a failure.
*
* @param {String ...} custom message
* @api public
*/
Assertion.prototype.fail = function (msg) {
var error = function() { return msg || "explicit failure"; }
this.assert(false, error, error);
return this;
};
/**
* Function bind implementation.
*/
function bind (fn, scope) {
return function () {
return fn.apply(scope, arguments);
}
}
/**
* Array every compatibility
*
* @see bit.ly/5Fq1N2
* @api public
*/
function every (arr, fn, thisObj) {
var scope = thisObj || global;
for (var i = 0, j = arr.length; i < j; ++i) {
if (!fn.call(scope, arr[i], i, arr)) {
return false;
}
}
return true;
}
/**
* Array indexOf compatibility.
*
* @see bit.ly/a5Dxa2
* @api public
*/
function indexOf (arr, o, i) {
if (Array.prototype.indexOf) {
return Array.prototype.indexOf.call(arr, o, i);
}
if (arr.length === undefined) {
return -1;
}
for (var j = arr.length, i = i < 0 ? i + j < 0 ? 0 : i + j : i || 0
; i < j && arr[i] !== o; i++);
return j <= i ? -1 : i;
}
// https://gist.github.com/1044128/
var getOuterHTML = function(element) {
if ('outerHTML' in element) return element.outerHTML;
var ns = "http://www.w3.org/1999/xhtml";
var container = document.createElementNS(ns, '_');
var xmlSerializer = new XMLSerializer();
var html;
if (document.xmlVersion) {
return xmlSerializer.serializeToString(element);
} else {
container.appendChild(element.cloneNode(false));
html = container.innerHTML.replace('><', '>' + element.innerHTML + '<');
container.innerHTML = '';
return html;
}
};
// Returns true if object is a DOM element.
var isDOMElement = function (object) {
if (typeof HTMLElement === 'object') {
return object instanceof HTMLElement;
} else {
return object &&
typeof object === 'object' &&
object.nodeType === 1 &&
typeof object.nodeName === 'string';
}
};
/**
* Inspects an object.
*
* @see taken from node.js `util` module (copyright Joyent, MIT license)
* @api private
*/
function i (obj, showHidden, depth) {
var seen = [];
function stylize (str) {
return str;
}
function format (value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (value && typeof value.inspect === 'function' &&
// Filter out the util module, it's inspect function is special
value !== exports &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
return value.inspect(recurseTimes);
}
// Primitive types cannot have properties
switch (typeof value) {
case 'undefined':
return stylize('undefined', 'undefined');
case 'string':
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return stylize(simple, 'string');
case 'number':
return stylize('' + value, 'number');
case 'boolean':
return stylize('' + value, 'boolean');
}
// For some reason typeof null is "object", so special case here.
if (value === null) {
return stylize('null', 'null');
}
if (isDOMElement(value)) {
return getOuterHTML(value);
}
// Look up the keys of the object.
var visible_keys = keys(value);
var $keys = showHidden ? Object.getOwnPropertyNames(value) : visible_keys;
// Functions without properties can be shortcutted.
if (typeof value === 'function' && $keys.length === 0) {
if (isRegExp(value)) {
return stylize('' + value, 'regexp');
} else {
var name = value.name ? ': ' + value.name : '';
return stylize('[Function' + name + ']', 'special');
}
}
// Dates without properties can be shortcutted
if (isDate(value) && $keys.length === 0) {
return stylize(value.toUTCString(), 'date');
}
// Error objects can be shortcutted
if (value instanceof Error) {
return stylize("["+value.toString()+"]", 'Error');
}
var base, type, braces;
// Determine the object type
if (isArray(value)) {
type = 'Array';
braces = ['[', ']'];
} else {
type = 'Object';
braces = ['{', '}'];
}
// Make functions say that they are functions
if (typeof value === 'function') {
var n = value.name ? ': ' + value.name : '';
base = (isRegExp(value)) ? ' ' + value : ' [Function' + n + ']';
} else {
base = '';
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + value.toUTCString();
}
if ($keys.length === 0) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return stylize('' + value, 'regexp');
} else {
return stylize('[Object]', 'special');
}
}
seen.push(value);
var output = map($keys, function (key) {
var name, str;
if (value.__lookupGetter__) {
if (value.__lookupGetter__(key)) {
if (value.__lookupSetter__(key)) {
str = stylize('[Getter/Setter]', 'special');
} else {
str = stylize('[Getter]', 'special');
}
} else {
if (value.__lookupSetter__(key)) {
str = stylize('[Setter]', 'special');
}
}
}
if (indexOf(visible_keys, key) < 0) {
name = '[' + key + ']';
}
if (!str) {
if (indexOf(seen, value[key]) < 0) {
if (recurseTimes === null) {
str = format(value[key]);
} else {
str = format(value[key], recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (isArray(value)) {
str = map(str.split('\n'), function (line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + map(str.split('\n'), function (line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = stylize('[Circular]', 'special');
}
}
if (typeof name === 'undefined') {
if (type === 'Array' && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = stylize(name, 'string');
}
}
return name + ': ' + str;
});
seen.pop();
var numLinesEst = 0;
var length = reduce(output, function (prev, cur) {
numLinesEst++;
if (indexOf(cur, '\n') >= 0) numLinesEst++;
return prev + cur.length + 1;
}, 0);
if (length > 50) {
output = braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
} else {
output = braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
return output;
}
return format(obj, (typeof depth === 'undefined' ? 2 : depth));
}
expect.stringify = i;
function isArray (ar) {
return Object.prototype.toString.call(ar) === '[object Array]';
}
function isRegExp(re) {
var s;
try {
s = '' + re;
} catch (e) {
return false;
}
return re instanceof RegExp || // easy case
// duck-type for context-switching evalcx case
typeof(re) === 'function' &&
re.constructor.name === 'RegExp' &&
re.compile &&
re.test &&
re.exec &&
s.match(/^\/.*\/[gim]{0,3}$/);
}
function isDate(d) {
return d instanceof Date;
}
function keys (obj) {
if (Object.keys) {
return Object.keys(obj);
}
var keys = [];
for (var i in obj) {
if (Object.prototype.hasOwnProperty.call(obj, i)) {
keys.push(i);
}
}
return keys;
}
function map (arr, mapper, that) {
if (Array.prototype.map) {
return Array.prototype.map.call(arr, mapper, that);
}
var other= new Array(arr.length);
for (var i= 0, n = arr.length; i<n; i++)
if (i in arr)
other[i] = mapper.call(that, arr[i], i, arr);
return other;
}
function reduce (arr, fun) {
if (Array.prototype.reduce) {
return Array.prototype.reduce.apply(
arr
, Array.prototype.slice.call(arguments, 1)
);
}
var len = +this.length;
if (typeof fun !== "function")
throw new TypeError();
// no value to return if no initial value and an empty array
if (len === 0 && arguments.length === 1)
throw new TypeError();
var i = 0;
if (arguments.length >= 2) {
var rv = arguments[1];
} else {
do {
if (i in this) {
rv = this[i++];
break;
}
// if array contains no values, no initial value to return
if (++i >= len)
throw new TypeError();
} while (true);
}
for (; i < len; i++) {
if (i in this)
rv = fun.call(null, rv, this[i], i, this);
}
return rv;
}
/**
* Asserts deep equality
*
* @see taken from node.js `assert` module (copyright Joyent, MIT license)
* @api private
*/
expect.eql = function eql(actual, expected) {
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if ('undefined' != typeof Buffer
&& Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) {
if (actual.length != expected.length) return false;
for (var i = 0; i < actual.length; i++) {
if (actual[i] !== expected[i]) return false;
}
return true;
// 7.2. If the expected value is a Date object, the actual value is
// equivalent if it is also a Date object that refers to the same time.
} else if (actual instanceof Date && expected instanceof Date) {
return actual.getTime() === expected.getTime();
// 7.3. Other pairs that do not both pass typeof value == "object",
// equivalence is determined by ==.
} else if (typeof actual != 'object' && typeof expected != 'object') {
return actual == expected;
// If both are regular expression use the special `regExpEquiv` method
// to determine equivalence.
} else if (isRegExp(actual) && isRegExp(expected)) {
return regExpEquiv(actual, expected);
// 7.4. For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical "prototype" property. Note: this
// accounts for both named and indexed properties on Arrays.
} else {
return objEquiv(actual, expected);
}
};
function isUndefinedOrNull (value) {
return value === null || value === undefined;
}
function isArguments (object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
}
function regExpEquiv (a, b) {
return a.source === b.source && a.global === b.global &&
a.ignoreCase === b.ignoreCase && a.multiline === b.multiline;
}
function objEquiv (a, b) {
if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
return false;
// an identical "prototype" property.
if (a.prototype !== b.prototype) return false;
//~~~I've managed to break Object.keys through screwy arguments passing.
// Converting to array solves the problem.
if (isArguments(a)) {
if (!isArguments(b)) {
return false;
}
a = pSlice.call(a);
b = pSlice.call(b);
return expect.eql(a, b);
}
try{
var ka = keys(a),
kb = keys(b),
key, i;
} catch (e) {//happens when one is a string literal and the other isn't
return false;
}
// having the same number of owned properties (keys incorporates hasOwnProperty)
if (ka.length != kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] != kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!expect.eql(a[key], b[key]))
return false;
}
return true;
}

221
packages/kbn-expect/expect.js.d.ts vendored Normal file
View file

@ -0,0 +1,221 @@
// tslint:disable
// Type definitions for expect.js 0.3.1
// Project: https://github.com/Automattic/expect.js
// Definitions by: Teppei Sato <https://github.com/teppeis>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// License: MIT
export default function expect(target?: any): Root;
interface Assertion {
/**
* Assert typeof / instanceof.
*/
an: An;
/**
* Check if the value is truthy
*/
ok(): void;
/**
* Creates an anonymous function which calls fn with arguments.
*/
withArgs(...args: any[]): Root;
/**
* Assert that the function throws.
*
* @param fn callback to match error string against
*/
throwError(fn?: (exception: any) => void): void;
/**
* Assert that the function throws.
*
* @param fn callback to match error string against
*/
throwException(fn?: (exception: any) => void): void;
/**
* Assert that the function throws.
*
* @param regexp regexp to match error string against
*/
throwError(regexp: RegExp): void;
/**
* Assert that the function throws.
*
* @param fn callback to match error string against
*/
throwException(regexp: RegExp): void;
/**
* Checks if the array is empty.
*/
empty(): Assertion;
/**
* Checks if the obj exactly equals another.
*/
equal(obj: any): Assertion;
/**
* Checks if the obj sortof equals another.
*/
eql(obj: any): Assertion;
/**
* Assert within start to finish (inclusive).
*
* @param start
* @param finish
*/
within(start: number, finish: number): Assertion;
/**
* Assert typeof.
*/
a(type: string): Assertion;
/**
* Assert instanceof.
*/
a(type: Function): Assertion;
/**
* Assert numeric value above n.
*/
greaterThan(n: number): Assertion;
/**
* Assert numeric value above n.
*/
above(n: number): Assertion;
/**
* Assert numeric value below n.
*/
lessThan(n: number): Assertion;
/**
* Assert numeric value below n.
*/
below(n: number): Assertion;
/**
* Assert string value matches regexp.
*
* @param regexp
*/
match(regexp: RegExp): Assertion;
/**
* Assert property "length" exists and has value of n.
*
* @param n
*/
length(n: number): Assertion;
/**
* Assert property name exists, with optional val.
*
* @param name
* @param val
*/
property(name: string, val?: any): Assertion;
/**
* Assert that string contains str.
*/
contain(str: string): Assertion;
string(str: string): Assertion;
/**
* Assert that the array contains obj.
*/
contain(obj: any): Assertion;
string(obj: any): Assertion;
/**
* Assert exact keys or inclusion of keys by using the `.own` modifier.
*/
key(keys: string[]): Assertion;
/**
* Assert exact keys or inclusion of keys by using the `.own` modifier.
*/
key(...keys: string[]): Assertion;
/**
* Assert exact keys or inclusion of keys by using the `.own` modifier.
*/
keys(keys: string[]): Assertion;
/**
* Assert exact keys or inclusion of keys by using the `.own` modifier.
*/
keys(...keys: string[]): Assertion;
/**
* Assert a failure.
*/
fail(message?: string): Assertion;
}
interface Root extends Assertion {
not: Not;
to: To;
only: Only;
have: Have;
be: Be;
}
interface Be extends Assertion {
/**
* Checks if the obj exactly equals another.
*/
(obj: any): Assertion;
an: An;
}
interface An extends Assertion {
/**
* Assert typeof.
*/
(type: string): Assertion;
/**
* Assert instanceof.
*/
(type: Function): Assertion;
}
interface Not extends NotBase {
to: ToBase;
}
interface NotBase extends Assertion {
be: Be;
have: Have;
include: Assertion;
only: Only;
}
interface To extends ToBase {
not: NotBase;
}
interface ToBase extends Assertion {
be: Be;
have: Have;
include: Assertion;
only: Only;
}
interface Only extends Assertion {
have: Have;
}
interface Have extends Assertion {
own: Assertion;
}

View file

@ -0,0 +1,7 @@
{
"name": "@kbn/expect",
"main": "./expect.js",
"version": "1.0.0",
"license": "MIT",
"private": true
}

View file

@ -0,0 +1,6 @@
{
"extends": "../../tsconfig.json",
"include": [
"expect.js.d.ts"
]
}

View file

@ -921,7 +921,7 @@ describe('I18n engine', () => {
await expect(i18n.load('some-url')).resolves.toBeUndefined();
expect(mockFetch).toHaveBeenCalledTimes(1);
expect(mockFetch).toHaveBeenCalledWith('some-url');
expect(mockFetch).toHaveBeenCalledWith('some-url', { credentials: 'same-origin' });
expect(i18n.getTranslation()).toEqual(translations);
});

View file

@ -240,7 +240,11 @@ export function init(newTranslation?: Translation) {
* @param translationsUrl URL pointing to the JSON bundle with translations.
*/
export async function load(translationsUrl: string) {
const response = await fetch(translationsUrl);
// Once this package is integrated into core Kibana we should switch to an abstraction
// around `fetch` provided by the platform, e.g. `kfetch`.
const response = await fetch(translationsUrl, {
credentials: 'same-origin',
});
if (response.status >= 300) {
throw new Error(`Translations request failed with status code: ${response.status}`);

View file

@ -1,20 +1,20 @@
{
"extends": "../../tsconfig.json",
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"types/intl_format_cache.d.ts",
"types/intl_relativeformat.d.ts"
],
"exclude": [
"target"
],
"compilerOptions": {
"declaration": true,
"declarationDir": "./target/types",
"types": [
"jest",
"node"
]
}
}
{
"extends": "../../tsconfig.json",
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"types/intl_format_cache.d.ts",
"types/intl_relativeformat.d.ts"
],
"exclude": [
"target"
],
"compilerOptions": {
"declaration": true,
"declarationDir": "./target/types",
"types": [
"jest",
"node"
]
}
}

View file

@ -1,8 +1,7 @@
{
"presets": ["@kbn/babel-preset/webpack_preset"],
"plugins": [
["babel-plugin-transform-runtime", {
"polyfill": false,
["@babel/plugin-transform-runtime", {
"regenerator": true
}]
]

View file

@ -9,19 +9,20 @@
"kbn:watch": "node scripts/build --dev --watch"
},
"dependencies": {
"@babel/runtime": "^7.3.4",
"@kbn/i18n": "1.0.0",
"lodash": "npm:@elastic/lodash@3.10.1-kibana1",
"lodash.clone": "^4.5.0",
"uuid": "3.0.1"
},
"devDependencies": {
"@babel/cli": "^7.2.3",
"@babel/core": "7.3.4",
"@babel/plugin-transform-runtime": "^7.3.4",
"@babel/polyfill": "7.2.5",
"@kbn/babel-preset": "1.0.0",
"@kbn/dev-utils": "1.0.0",
"babel-cli": "^6.26.0",
"babel-core": "6.26.3",
"babel-loader": "7.1.5",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-polyfill": "6.20.0",
"babel-loader": "8.0.5",
"copy-webpack-plugin": "^4.6.0",
"css-loader": "1.0.0",
"del": "^3.0.0",

View file

@ -19,7 +19,7 @@
const { extname } = require('path');
const { transform } = require('babel-core');
const { transform } = require('@babel/core');
exports.createServerCodeTransformer = (sourceMaps) => {
return (content, path) => {

View file

@ -28,15 +28,14 @@ describe('js support', () => {
it('transpiles js file', () => {
const transformer = createServerCodeTransformer();
expect(transformer(JS_FIXTURE, JS_FIXTURE_PATH)).toMatchInlineSnapshot(`
"'use strict';
"\\"use strict\\";
var _util = require('util');
var _util2 = _interopRequireDefault(_util);
var _util = _interopRequireDefault(require(\\"util\\"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
console.log(_util2.default.format('hello world')); /* eslint-disable */"
/* eslint-disable */
console.log(_util.default.format('hello world'));"
`);
});

View file

@ -8,9 +8,9 @@
"templateVersion": "<%= templateVersion %>"
},
"scripts": {
"preinstall": "node ../../kibana/preinstall_check",
"kbn": "node ../../kibana/scripts/kbn",
"es": "node ../../kibana/scripts/es",
"preinstall": "node ../../preinstall_check",
"kbn": "node ../../scripts/kbn",
"es": "node ../../scripts/es",
"lint": "eslint .",
"start": "plugin-helpers start",
"test:server": "plugin-helpers test:server",
@ -19,23 +19,23 @@
},
<%_ if (generateTranslations) { _%>
"dependencies": {
"@kbn/i18n": "link:../../kibana/packages/kbn-i18n"
"@kbn/i18n": "link:../../packages/kbn-i18n"
},
<%_ } _%>
"devDependencies": {
"@elastic/eslint-config-kibana": "link:../../kibana/packages/eslint-config-kibana",
"@elastic/eslint-import-resolver-kibana": "link:../../kibana/packages/kbn-eslint-import-resolver-kibana",
"@kbn/plugin-helpers": "link:../../kibana/packages/kbn-plugin-helpers",
"babel-eslint": "^9.0.0",
"eslint": "^5.6.0",
"eslint-plugin-babel": "^5.2.0",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-jest": "^21.26.2",
"eslint-plugin-jsx-a11y": "^6.1.2",
"eslint-plugin-mocha": "^5.2.0",
"@elastic/eslint-config-kibana": "link:../../packages/eslint-config-kibana",
"@elastic/eslint-import-resolver-kibana": "link:../../packages/kbn-eslint-import-resolver-kibana",
"@kbn/expect": "link:../../packages/kbn-expect",
"@kbn/plugin-helpers": "link:../../packages/kbn-plugin-helpers",
"babel-eslint": "^10.0.1",
"eslint": "^5.14.1",
"eslint-plugin-babel": "^5.3.0",
"eslint-plugin-import": "^2.16.0",
"eslint-plugin-jest": "^22.3.0",
"eslint-plugin-jsx-a11y": "^6.2.1",
"eslint-plugin-mocha": "^5.3.0",
"eslint-plugin-no-unsanitized": "^3.0.2",
"eslint-plugin-prefer-object-spread": "^1.2.1",
"eslint-plugin-react": "^7.11.1",
"expect.js": "^0.3.1"
"eslint-plugin-react": "^7.12.4"
}
}

View file

@ -1,4 +1,4 @@
import expect from 'expect.js';
import expect from '@kbn/expect';
describe('suite', () => {
it('is a test', () => {

View file

@ -1,4 +1,4 @@
import expect from 'expect.js';
import expect from '@kbn/expect';
describe('suite', () => {
it('is a test', () => {

View file

@ -25,7 +25,7 @@ function babelRegister() {
const plugin = pluginConfig();
try {
// add support for moved babel-register source: https://github.com/elastic/kibana/pull/13973
// add support for moved @babel/register source: https://github.com/elastic/kibana/pull/13973
require(resolve(plugin.kibanaRoot, 'src/setup_node_env/babel_register')); // eslint-disable-line import/no-dynamic-require
} catch (error) {
if (error.code === 'MODULE_NOT_FOUND') {

View file

@ -1,10 +1,14 @@
{
"presets": [
"stage-3",
["env", {
"@babel/typescript",
["@babel/preset-env", {
"targets": {
"node": "current"
}
}]
],
"plugins": [
"@babel/proposal-class-properties",
"@babel/proposal-object-rest-spread"
]
}
}

File diff suppressed because it is too large Load diff

View file

@ -10,6 +10,11 @@
"prettier": "prettier --write './src/**/*.ts'"
},
"devDependencies": {
"@babel/core": "^7.3.4",
"@babel/plugin-proposal-class-properties": "^7.3.4",
"@babel/plugin-proposal-object-rest-spread": "^7.3.4",
"@babel/preset-env": "^7.3.4",
"@babel/preset-typescript": "^7.3.3",
"@types/cmd-shim": "^2.0.0",
"@types/cpy": "^5.1.0",
"@types/dedent": "^0.7.0",
@ -32,10 +37,7 @@
"@types/tempy": "^0.1.0",
"@types/wrap-ansi": "^2.0.14",
"@types/write-pkg": "^3.1.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"babel-preset-stage-3": "^6.24.1",
"babel-loader": "^8.0.5",
"chalk": "^2.4.1",
"cmd-shim": "^2.0.2",
"cpy": "^7.0.1",
@ -60,7 +62,6 @@
"strip-ansi": "^4.0.0",
"strong-log-transformer": "^2.1.0",
"tempy": "^0.2.1",
"ts-loader": "^5.2.2",
"typescript": "^3.3.3333",
"unlazy-loader": "^0.1.3",
"webpack": "^4.23.1",

View file

@ -4,10 +4,11 @@
"private": true,
"main": "./target/index.js",
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.6.1"
"@babel/cli": "^7.2.3",
"@babel/core": "^7.3.4",
"@babel/preset-env": "^7.3.4"
},
"scripts": {
"build": "babel --presets env --out-dir target src"
"build": "babel --presets=@babel/preset-env --out-dir target src"
}
}

View file

@ -7,11 +7,12 @@
"@elastic/bar": "link:../bar"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.6.1",
"@babel/core": "^7.3.4",
"@babel/cli": "^7.2.3",
"@babel/preset-env": "^7.3.4",
"moment": "2.20.1"
},
"scripts": {
"build": "babel --presets env --out-dir target src"
"build": "babel --presets=@babel/preset-env --out-dir target src"
}
}

View file

@ -20,14 +20,15 @@ Array [
exports[`kbn-pm production builds and copies projects for production: packages/bar/package.json 1`] = `
Object {
"devDependencies": Object {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.6.1",
"@babel/cli": "^7.2.3",
"@babel/core": "^7.3.4",
"@babel/preset-env": "^7.3.4",
},
"main": "./target/index.js",
"name": "@elastic/bar",
"private": true,
"scripts": Object {
"build": "babel --presets env --out-dir target src",
"build": "babel --presets=@babel/preset-env --out-dir target src",
},
"version": "1.0.0",
}
@ -47,15 +48,16 @@ Object {
"@elastic/bar": "link:../bar",
},
"devDependencies": Object {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.6.1",
"@babel/cli": "^7.2.3",
"@babel/core": "^7.3.4",
"@babel/preset-env": "^7.3.4",
"moment": "2.20.1",
},
"main": "./target/index.js",
"name": "@elastic/foo",
"private": true,
"scripts": Object {
"build": "babel --presets env --out-dir target src",
"build": "babel --presets=@babel/preset-env --out-dir target src",
},
"version": "1.0.0",
}

View file

@ -4,7 +4,7 @@
"dist"
],
"include": [
"./src/**/*.ts"
"./src/**/*.ts",
],
"compilerOptions": {
"types": [

View file

@ -44,15 +44,6 @@ module.exports = {
{
loader: 'babel-loader',
},
{
loader: 'ts-loader',
options: {
compilerOptions: {
// enable esnext modules so webpack can do its thing better
module: 'esnext',
},
},
},
],
exclude: /node_modules/,
},

Some files were not shown because too many files have changed in this diff Show more