[6.7] Remove custom WebPack bundles from Canvas (#30123) (#30656)

This commit is contained in:
Chris Davies 2019-02-13 12:06:06 -05:00 committed by GitHub
parent 9f664f15c0
commit 5ec50b6331
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
96 changed files with 204 additions and 879 deletions

View file

@ -29,3 +29,4 @@ export { castProvider } from './interpreter/cast';
export { parse } from './lib/grammar';
export { getByAlias } from './lib/get_by_alias';
export { Registry } from './lib/registry';
export { addRegistries, register, registryFactory } from './registries';

View file

@ -0,0 +1,78 @@
/*
* 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.
*/
/**
* Add a new set of registries to an existing set of registries.
*
* @param {*} registries - The existing set of registries
* @param {*} newRegistries - The new set of registries
*/
export function addRegistries(registries, newRegistries) {
Object.keys(newRegistries).forEach(registryName => {
if (registries[registryName]) {
throw new Error(`There is already a registry named "${registryName}".`);
}
registries[registryName] = newRegistries[registryName];
});
return registries;
}
/**
* Register a set of interpreter specs (functions, types, renderers, etc)
*
* @param {*} registries - The set of registries
* @param {*} specs - The specs to be regsitered (e.g. { types: [], browserFunctions: [] })
*/
export function register(registries, specs) {
Object.keys(specs).forEach(registryName => {
if (!registries[registryName]) {
throw new Error(`There is no registry named "${registryName}".`);
}
if (!registries[registryName].register) {
throw new Error(`Registry "${registryName}" must have a register function.`);
}
specs[registryName].forEach(f => registries[registryName].register(f));
});
return registries;
}
/**
* A convenience function for exposing registries and register in a plugin-friendly way
* as a global in the browser, and as server.plugins.interpreter.register | registries
* on the server.
*
* @param {*} registries - The registries to wrap.
*/
export function registryFactory(registries) {
return {
// This is a getter function. We can't make it a property or a proper
// getter, because Kibana server will improperly clone it.
registries() {
return registries;
},
register(specs) {
return register(registries, specs);
},
};
}

View file

@ -19,6 +19,6 @@
import { clog } from './clog';
export const commonFunctions = [
export const browserFunctions = [
clog,
];

View file

@ -17,4 +17,7 @@
* under the License.
*/
import '../common/register';
import { browserFunctions } from './index';
// eslint-disable-next-line no-undef
browserFunctions.forEach(canvas.register);

View file

@ -17,7 +17,4 @@
* under the License.
*/
import { commonFunctions } from './index';
// eslint-disable-next-line no-undef
commonFunctions.forEach(canvas.register);
import '../common/register';

View file

@ -1,59 +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.
*/
function loadPath(path, callback) {
const script = document.createElement('script');
script.setAttribute('async', '');
script.setAttribute('nonce', window.__webpack_nonce__);
script.addEventListener('error', () => {
console.error('Failed to load plugin bundle', path);
});
script.setAttribute('src', path);
script.addEventListener('load', callback);
document.head.appendChild(script);
}
export const loadBrowserRegistries = (registries, basePath) => {
const remainingTypes = Object.keys(registries);
const populatedTypes = {};
return new Promise(resolve => {
function loadType() {
if (!remainingTypes.length) {
resolve(populatedTypes);
return;
}
const type = remainingTypes.pop();
window.canvas = window.canvas || {};
window.canvas.register = d => registries[type].register(d);
// Load plugins one at a time because each needs a different loader function
// $script will only load each of these once, we so can call this as many times as we need?
const pluginPath = `${basePath}/api/canvas/plugins?type=${type}`;
loadPath(pluginPath, () => {
populatedTypes[type] = registries[type];
loadType();
});
}
loadType();
});
};

View file

@ -17,5 +17,11 @@
* under the License.
*/
export { loadBrowserRegistries } from './browser_registries';
export { initializeInterpreter } from './interpreter';
export { registries } from './registries';
import { registries } from './registries';
import { registryFactory } from '../common';
// Expose kbnInterpreter.register(specs) and kbnInterpreter.registries() globally so that plugins
// can register without a transpile step.
global.kbnInterpreter = Object.assign(global.kbnInterpreter || {}, registryFactory(registries));

View file

@ -17,7 +17,16 @@
* under the License.
*/
import { register, FunctionsRegistry, TypesRegistry } from '../common';
import { browserFunctions } from '../plugin/functions/browser';
import { typeSpecs } from '../plugin/types';
import { FunctionsRegistry } from '@kbn/interpreter/common';
export const registries = {
browserFunctions: new FunctionsRegistry(),
types: new TypesRegistry(),
};
export const functionsRegistry = new FunctionsRegistry();
register(registries, {
browserFunctions,
types: typeSpecs,
});

View file

@ -1,110 +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.
*/
import path from 'path';
import fs from 'fs';
import { promisify } from 'util';
import { flatten } from 'lodash';
import { pluginPaths } from './plugin_paths';
const lstat = promisify(fs.lstat);
const readdir = promisify(fs.readdir);
const canvasPluginDirectoryName = 'canvas_plugin';
const isDirectory = path =>
lstat(path)
.then(stat => stat.isDirectory())
.catch(() => false); // if lstat fails, it doesn't exist and is not a directory
const isDirname = (p, name) => path.basename(p) === name;
const filterDirectories = (paths, { exclude = false } = {}) => {
return Promise.all(paths.map(p => isDirectory(p))).then(directories => {
return paths.filter((p, i) => (exclude ? !directories[i] : directories[i]));
});
};
const getPackagePluginPath = () => {
let basePluginPath = path.resolve(__dirname, '..');
if (isDirname(basePluginPath, 'target')) {
basePluginPath = path.join(basePluginPath, '..');
}
return basePluginPath;
};
const getKibanaPluginsPath = () => {
let kibanaPath = path.resolve(getPackagePluginPath(), '..', '..');
// in dev mode we are in kibana folder, else we are in node_modules
if (!isDirname(kibanaPath, 'kibana')) {
kibanaPath = path.join(kibanaPath, '..');
}
return path.join(kibanaPath, 'plugins');
};
const getXPackPluginsPath = () => {
const kibanaPath = path.resolve(getPackagePluginPath(), '..', '..');
// in dev mode we are in kibana folder, else we are in node_modules
return path.join(kibanaPath, 'x-pack/plugins');
};
// These must all exist
const paths = [
getPackagePluginPath(),
getXPackPluginsPath(), // Canvas core plugins
getKibanaPluginsPath(), // Kibana plugin directory
].filter(Boolean);
export const getPluginPaths = type => {
const typePath = pluginPaths[type];
if (!typePath) throw new Error(`Unknown type: ${type}`);
async function findPlugins(directory) {
const isDir = await isDirectory(directory);
if (!isDir) return;
const names = await readdir(directory); // Get names of everything in the directory
return names
.filter(name => name[0] !== '.')
.map(name => path.resolve(directory, name, canvasPluginDirectoryName, ...typePath));
}
return Promise.all(paths.map(findPlugins))
.then(dirs =>
dirs.reduce((list, dir) => {
if (!dir) return list;
return list.concat(dir);
}, [])
)
.then(possibleCanvasPlugins => filterDirectories(possibleCanvasPlugins, { exclude: false }))
.then(canvasPluginDirectories => {
return Promise.all(
canvasPluginDirectories.map(dir =>
// Get the full path of all files in the directory
readdir(dir).then(files => files.map(file => path.resolve(dir, file)))
)
)
.then(flatten)
.then(files => filterDirectories(files, { exclude: true }));
});
};

View file

@ -17,6 +17,14 @@
* under the License.
*/
export { populateServerRegistries } from './server_registries';
export { getPluginPaths } from './get_plugin_paths';
export { pluginPaths } from './plugin_paths';
import { typeSpecs as types } from '../plugin/types';
import { register, TypesRegistry, FunctionsRegistry } from '../common';
export const registries = {
types: new TypesRegistry(),
serverFunctions: new FunctionsRegistry(),
};
register(registries, {
types,
});

View file

@ -1,35 +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.
*/
export const pluginPaths = {
serverFunctions: ['functions', 'server'],
browserFunctions: ['functions', 'browser'],
commonFunctions: ['functions', 'common'],
types: ['types'],
elements: ['elements'],
renderers: ['renderers'],
interfaces: ['interfaces'],
transformUIs: ['uis', 'transforms'],
datasourceUIs: ['uis', 'datasources'],
modelUIs: ['uis', 'models'],
viewUIs: ['uis', 'views'],
argumentUIs: ['uis', 'arguments'],
templates: ['templates'],
tagUIs: ['uis', 'tags'],
};

View file

@ -1,54 +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.
*/
import { getPluginPaths } from './get_plugin_paths';
export const populateServerRegistries = registries => {
if (!registries) throw new Error('registries are required');
return new Promise(resolve => {
const remainingTypes = Object.keys(registries);
const populatedTypes = {};
const loadType = () => {
const type = remainingTypes.pop();
getPluginPaths(type).then(paths => {
global.canvas = global.canvas || {};
global.canvas.register = d => registries[type].register(d);
paths.forEach(path => {
require(path); // eslint-disable-line import/no-dynamic-require
});
delete global.canvas;
populatedTypes[type] = registries[type];
if (remainingTypes.length) {
loadType();
}
else {
resolve(populatedTypes);
}
});
};
if (remainingTypes.length) loadType();
});
};

View file

@ -26,7 +26,6 @@ const { ToolingLog, withProcRunner, pickLevelFromFlags } = require('@kbn/dev-uti
const {
ROOT_DIR,
PLUGIN_SOURCE_DIR,
BUILD_DIR,
WEBPACK_CONFIG_PATH
} = require('./paths');
@ -82,7 +81,7 @@ withProcRunner(log, async (proc) => {
cmd: 'babel',
args: [
'src',
'--ignore', `${relative(cwd, PLUGIN_SOURCE_DIR)},*.test.js`,
'--ignore', `*.test.js`,
'--out-dir', relative(cwd, BUILD_DIR),
'--copy-files',
...(flags.dev ? ['--source-maps', 'inline'] : []),

View file

@ -18,16 +18,10 @@
*/
import { routes } from './server/routes';
import { FunctionsRegistry, TypesRegistry } from '@kbn/interpreter/common';
import { populateServerRegistries } from '@kbn/interpreter/server';
import { registryFactory } from '@kbn/interpreter/common';
import { registries } from '@kbn/interpreter/server';
export default async function (server /*options*/) {
const registries = {
serverFunctions: new FunctionsRegistry(),
types: new TypesRegistry()
};
server.injectUiAppVars('canvas', () => {
const config = server.config();
const basePath = config.get('server.basePath');
@ -47,8 +41,9 @@ export default async function (server /*options*/) {
};
});
await populateServerRegistries(registries);
// Expose server.plugins.interpreter.register(specs) and
// server.plugins.interpreter.registries() (a getter).
server.expose(registryFactory(registries));
server.expose(registries);
routes(server);
}

View file

@ -17,33 +17,21 @@
* under the License.
*/
import { initializeInterpreter, loadBrowserRegistries } from '@kbn/interpreter/public';
import { initializeInterpreter, registries } from '@kbn/interpreter/public';
import { kfetch } from 'ui/kfetch';
import chrome from 'ui/chrome';
import { functionsRegistry } from './functions_registry';
import { typesRegistry } from './types_registry';
const basePath = chrome.getInjected('serverBasePath');
const types = {
browserFunctions: functionsRegistry,
types: typesRegistry
};
let _resolve;
let _interpreterPromise;
const initialize = async () => {
await loadBrowserRegistries(types, basePath);
initializeInterpreter(kfetch, typesRegistry, functionsRegistry).then(interpreter => {
initializeInterpreter(kfetch, registries.types, registries.browserFunctions).then(interpreter => {
_resolve({ interpreter });
});
};
export const getInterpreter = async () => {
if (!_interpreterPromise) {
_interpreterPromise = new Promise(resolve => _resolve = resolve);
_interpreterPromise = new Promise(resolve => (_resolve = resolve));
initialize();
}
return await _interpreterPromise;

View file

@ -1,23 +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.
*/
import { TypesRegistry } from '@kbn/interpreter/common';
export const typesRegistry = new TypesRegistry();

View file

@ -1,37 +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.
*/
import fs from 'fs';
import ss from 'stream-stream';
import { getPluginPaths } from '@kbn/interpreter/server';
export const getPluginStream = type => {
const stream = ss({
separator: '\n',
});
getPluginPaths(type).then(files => {
files.forEach(file => {
stream.write(fs.createReadStream(file));
});
stream.end();
});
return stream;
};

View file

@ -21,7 +21,7 @@ import { interpreterProvider } from '@kbn/interpreter/common';
import { createHandlers } from '../create_handlers';
export const server = async ({ server, request }) => {
const { serverFunctions, types } = server.plugins.interpreter;
const { serverFunctions, types } = server.plugins.interpreter.registries();
return {
interpret: (ast, context) => {

View file

@ -18,11 +18,9 @@
*/
import { translate } from './translate';
import { plugins } from './plugins';
import { registerServerFunctions } from './server_functions';
export function routes(server) {
plugins(server);
translate(server);
registerServerFunctions(server);
}

View file

@ -1,40 +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.
*/
import { pluginPaths } from '@kbn/interpreter/server';
import { getPluginStream } from '../lib/get_plugin_stream';
export function plugins(server) {
server.route({
method: 'GET',
path: '/api/canvas/plugins',
handler: function (request, h) {
const { type } = request.query;
if (!pluginPaths[type]) {
return h.response({ error: 'Invalid type' }).code(400);
}
return getPluginStream(type);
},
config: {
auth: false,
},
});
}

View file

@ -51,7 +51,7 @@ function runServerFunctions(server) {
id: Joi.number().required(),
functionName: Joi.string().required(),
args: Joi.object().default({}),
context: Joi.object().default({}),
context: Joi.object().allow(null).default({}),
}),
).required(),
}).required(),
@ -88,7 +88,7 @@ function getServerFunctions(server) {
method: 'GET',
path: `${API_ROUTE}/fns`,
handler() {
return server.plugins.interpreter.serverFunctions.toJS();
return server.plugins.interpreter.registries().serverFunctions.toJS();
},
});
}
@ -101,10 +101,11 @@ function getServerFunctions(server) {
* @param {*} fnCall - Describes the function being run `{ functionName, args, context }`
*/
async function runFunction(server, handlers, fnCall) {
const registries = server.plugins.interpreter.registries();
const { functionName, args, context } = fnCall;
const types = server.plugins.interpreter.types.toJS();
const types = registries.types.toJS();
const { deserialize } = serializeProvider(types);
const fnDef = server.plugins.interpreter.serverFunctions.toJS()[functionName];
const fnDef = registries.serverFunctions.toJS()[functionName];
if (!fnDef) {
throw Boom.notFound(`Function "${functionName}" could not be found.`);

View file

@ -326,8 +326,8 @@ export default class BaseOptimizer {
loader: 'raw-loader'
},
{
test: /\.png$/,
loader: 'url-loader'
test: /\.(png|jpg|gif|jpeg)$/,
loader: ['url-loader'],
},
{
test: /\.(woff|woff2|ttf|eot|svg|ico)(\?|$)/,

View file

@ -17,6 +17,8 @@
* under the License.
*/
// @ts-ignore untyped dependency
import { registries } from '@kbn/interpreter/public';
import { EventEmitter } from 'events';
import { debounce, forEach } from 'lodash';
import * as Rx from 'rxjs';

View file

@ -57,6 +57,7 @@ export {
docViews,
hacks,
home,
canvas,
visTypeEnhancers,
aliases,
visualize,

View file

@ -51,6 +51,7 @@ export const devTools = appExtension;
export const docViews = appExtension;
export const hacks = appExtension;
export const home = appExtension;
export const canvas = appExtension;
export const inspectorViews = appExtension;
export const search = appExtension;
export const shareContextMenuExtensions = appExtension;

View file

@ -6,7 +6,6 @@
"license": "Elastic-License",
"scripts": {
"kbn": "node ../scripts/kbn",
"kbn:bootstrap": "gulp canvas:plugins:build",
"start": "gulp dev",
"build": "gulp build",
"testonly": "gulp testonly",

View file

@ -7,6 +7,6 @@
import { Fn } from '@kbn/interpreter/common';
import { functions as browserFns } from '../../canvas_plugin_src/functions/browser';
import { functions as commonFns } from '../../canvas_plugin_src/functions/common';
import { functions as serverFns } from '../../canvas_plugin_src/functions/server/src';
import { functions as serverFns } from '../../canvas_plugin_src/functions/server';
export const functionSpecs = [...browserFns, ...commonFns, ...serverFns].map(fn => new Fn(fn()));

View file

@ -1,10 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import 'babel-polyfill';
import { elementSpecs } from './index';
elementSpecs.forEach(canvas.register);

View file

@ -1,10 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import 'babel-polyfill';
import { functions } from './index';
functions.forEach(canvas.register);

View file

@ -1,10 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import 'babel-polyfill';
import { functions } from './index';
functions.forEach(canvas.register);

View file

@ -6,7 +6,7 @@
import expect from 'expect.js';
import { getExpressionType } from '../pointseries/lib/get_expression_type';
import { emptyTable, testTable } from '../../../common/__tests__/fixtures/test_tables';
import { emptyTable, testTable } from '../../common/__tests__/fixtures/test_tables';
describe('getExpressionType', () => {
it('returns the result type of an evaluated math expression', () => {

View file

@ -6,7 +6,7 @@
import expect from 'expect.js';
import { pointseries } from '../pointseries';
import { emptyTable, testTable } from '../../../common/__tests__/fixtures/test_tables';
import { emptyTable, testTable } from '../../common/__tests__/fixtures/test_tables';
describe('pointseries', () => {
const fn = pointseries().fn;

View file

@ -5,7 +5,7 @@
*/
import { sortBy } from 'lodash';
import { queryDatatable } from '../../../../../common/lib/datatable/query';
import { queryDatatable } from '../../../../common/lib/datatable/query';
import { getDemoRows } from './get_demo_rows';
export const demodata = () => ({

View file

@ -4,7 +4,7 @@
* you may not use this file except in compliance with the Elastic License.
*/
import { buildESRequest } from '../../../../server/lib/build_es_request';
import { buildESRequest } from '../../../server/lib/build_es_request';
export const escount = () => ({
name: 'escount',

View file

@ -5,7 +5,7 @@
*/
import squel from 'squel';
import { queryEsSQL } from '../../../../server/lib/query_es_sql';
import { queryEsSQL } from '../../../server/lib/query_es_sql';
export const esdocs = () => ({
name: 'esdocs',

View file

@ -4,7 +4,7 @@
* you may not use this file except in compliance with the Elastic License.
*/
import { queryEsSQL } from '../../../../server/lib/query_es_sql';
import { queryEsSQL } from '../../../server/lib/query_es_sql';
export const essql = () => ({
name: 'essql',

View file

@ -8,8 +8,8 @@ import uniqBy from 'lodash.uniqby';
import { evaluate } from 'tinymath';
import { groupBy, zipObject, omit, values } from 'lodash';
import moment from 'moment';
import { pivotObjectArray } from '../../../../../common/lib/pivot_object_array';
import { unquoteString } from '../../../../../common/lib/unquote_string';
import { pivotObjectArray } from '../../../../common/lib/pivot_object_array';
import { unquoteString } from '../../../../common/lib/unquote_string';
import { isColumnReference } from './lib/is_column_reference';
import { getExpressionType } from './lib/get_expression_type';

View file

@ -5,7 +5,7 @@
*/
import { parse } from 'tinymath';
import { getFieldType } from '../../../../../../common/lib/get_field_type';
import { getFieldType } from '../../../../../common/lib/get_field_type';
import { isColumnReference } from './is_column_reference';
import { getFieldNames } from './get_field_names';

View file

@ -1,9 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { functions } from './src/index';
functions.forEach(canvas.register);

View file

@ -1,7 +0,0 @@
// Making variables available to plugins
@import '~@elastic/eui/src/themes/k6/k6_globals';
@import '~@elastic/eui/src/themes/k6/k6_colors_light';
@import '~@elastic/eui/src/global_styling/functions/index';
@import '~@elastic/eui/src/global_styling/variables/index';
@import '~@elastic/eui/src/global_styling/mixins/index';

View file

@ -7,7 +7,6 @@
import React from 'react';
import PropTypes from 'prop-types';
import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui';
import './advanced_filter.scss';
export const AdvancedFilter = ({ value, onChange, commit }) => (
<form

View file

@ -1,5 +1,3 @@
@import '../../../lib/eui.scss';
.canvasAdvancedFilter {
width: 100%;
font-size: inherit;

View file

@ -7,7 +7,6 @@
import React from 'react';
import PropTypes from 'prop-types';
import { EuiIcon } from '@elastic/eui';
import './dropdown_filter.scss';
export const DropdownFilter = ({ value, onChange, commit, choices }) => {
const options = [{ value: '%%CANVAS_MATCH_ALL%%', text: '-- ANY --' }];

View file

@ -1,5 +1,3 @@
@import '../../../lib/eui.scss';
.canvasDropdownFilter {
width: 100%;
font-size: inherit;

View file

@ -7,7 +7,6 @@
import React from 'react';
import ReactDOM from 'react-dom';
import Markdown from 'markdown-it';
import './markdown.scss';
const md = new Markdown();

View file

@ -1,5 +1,3 @@
@import '../../lib/eui.scss';
// Kibana Canvas - Default styles for Markdown element
//
// 1. Links

View file

@ -11,7 +11,6 @@ import '../../lib/flot-charts';
import { debounce, includes } from 'lodash';
import { size } from './plugins/size';
import { text } from './plugins/text';
import './plot.scss';
const render = (domNode, config, handlers) => {
// TODO: OH NOES

View file

@ -1,5 +1,3 @@
@import '../../lib/eui.scss';
// I assume these are flot specific selector names and should not be renamed
.legendLabel {
color: $euiTextColor;

View file

@ -1,10 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import 'babel-polyfill';
import { renderFunctions } from './index';
renderFunctions.forEach(canvas.register);

View file

@ -6,7 +6,6 @@
import { elasticOutline } from '../../lib/elastic_outline';
import { isValidUrl } from '../../../common/lib/url';
import './reveal_image.scss';
export const revealImage = () => ({
name: 'revealImage',

View file

@ -9,7 +9,6 @@ import PropTypes from 'prop-types';
import dateMath from '@elastic/datemath';
import { EuiDatePicker } from '@elastic/eui';
import { DatetimeInput } from '../datetime_input';
import './datetime_calendar.scss';
export const DatetimeCalendar = ({
value,

View file

@ -1,5 +1,3 @@
@import '../../../../lib/eui.scss';
.canvasDateTimeCal {
display: inline-grid;
height: 100%;

View file

@ -8,7 +8,6 @@ import React from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import { DatetimeCalendar } from '../datetime_calendar';
import './datetime_range_absolute.scss';
export const DatetimeRangeAbsolute = ({ from, to, onSelect }) => (
<div className="canvasDateTimeRangeAbsolute">

View file

@ -1,5 +1,3 @@
@import '../../../../lib/eui.scss';
.canvasDateTimeRangeAbsolute {
display: flex;

View file

@ -11,7 +11,6 @@ import { EuiButton } from '@elastic/eui';
import moment from 'moment';
import { DatetimeRangeAbsolute } from '../datetime_range_absolute';
import { DatetimeQuickList } from '../datetime_quick_list';
import './time_picker.scss';
export const quickRanges = [
{ from: 'now-24h', to: 'now', display: 'Last 24 hours' },

View file

@ -1,5 +1,3 @@
@import '../../../../lib/eui.scss';
.canvasTimePicker {
display: flex;

View file

@ -9,7 +9,6 @@ import PropTypes from 'prop-types';
import { Popover } from '../../../../../public/components/popover';
import { PrettyDuration } from '../pretty_duration';
import { TimePicker } from '../time_picker';
import './time_picker_mini.scss';
export const TimePickerMini = ({ from, to, onSelect }) => {
const button = handleClick => (

View file

@ -1,5 +1,3 @@
@import '../../../../lib/eui.scss';
.canvasTimePickerMini {
width: 100%;

View file

@ -1,10 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import 'babel-polyfill';
import { templateSpecs } from './index';
templateSpecs.forEach(canvas.register);

View file

@ -1,5 +1,3 @@
@import '../../../lib/eui.scss';
.canvasArgImage {
.canvasArgImage--preview {
max-height: 100px;

View file

@ -14,7 +14,6 @@ import { resolveFromArgs } from '../../../../common/lib/resolve_dataurl';
import { isValidHttpUrl } from '../../../../common/lib/httpurl';
import { encode } from '../../../../common/lib/dataurl';
import { templateFromReactComponent } from '../../../../public/lib/template_from_react_component';
import './image_upload.scss';
import { VALID_IMAGE_TYPES } from '../../../../common/lib/constants';
import { FileForm, LinkForm } from './forms';

View file

@ -1,10 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import 'babel-polyfill';
import { args } from './index';
args.forEach(canvas.register);

View file

@ -1,10 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import 'babel-polyfill';
import { datasourceSpecs } from './index';
datasourceSpecs.forEach(canvas.register);

View file

@ -1,10 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import 'babel-polyfill';
import { modelSpecs } from './index';
modelSpecs.forEach(canvas.register);

View file

@ -1,10 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import 'babel-polyfill';
import { tagSpecs } from './index';
tagSpecs.forEach(canvas.register);

View file

@ -1,10 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import 'babel-polyfill';
import { transformSpecs } from './index';
transformSpecs.forEach(canvas.register);

View file

@ -1,10 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import 'babel-polyfill';
import { viewSpecs } from './index';
viewSpecs.forEach(canvas.register);

View file

@ -6,7 +6,6 @@
import { resolve } from 'path';
import init from './init';
import './server/build_fix';
import { mappings } from './server/mappings';
import { CANVAS_APP } from './common/lib';

View file

@ -7,10 +7,13 @@
import { routes } from './server/routes';
import { commonFunctions } from './common/functions';
import { registerCanvasUsageCollector } from './server/usage';
import { functions } from './canvas_plugin_src/functions/server';
import { loadSampleData } from './server/sample_data';
export default async function(server /*options*/) {
const functionsRegistry = server.plugins.interpreter.serverFunctions;
const { serverFunctions } = server.plugins.interpreter.register({
serverFunctions: commonFunctions.concat(functions),
});
server.injectUiAppVars('canvas', async () => {
const config = server.config();
@ -29,15 +32,12 @@ export default async function(server /*options*/) {
kbnIndex: config.get('kibana.index'),
esShardTimeout: config.get('elasticsearch.shardTimeout'),
esApiVersion: config.get('elasticsearch.apiVersion'),
serverFunctions: functionsRegistry.toArray(),
serverFunctions: serverFunctions.toArray(),
basePath,
reportingBrowserType,
};
});
// There are some common functions that use private APIs, load them here
commonFunctions.forEach(func => functionsRegistry.register(func));
registerCanvasUsageCollector(server);
loadSampleData(server);
routes(server);

View file

@ -22,6 +22,7 @@ import 'uiExports/fieldFormats';
// load application code
import './lib/load_expression_types';
import './lib/load_transitions';
import 'uiExports/canvas';
// load the application
chrome.setRootController('canvas', CanvasRootController);

View file

@ -4,18 +4,31 @@
* you may not use this file except in compliance with the Elastic License.
*/
import { functionsRegistry } from 'plugins/interpreter/functions_registry';
import { getInterpreter } from 'plugins/interpreter/interpreter';
import { loadBrowserRegistries } from '@kbn/interpreter/public';
import { registries } from '@kbn/interpreter/public';
import { register, addRegistries } from '@kbn/interpreter/common';
import { connect } from 'react-redux';
import { compose, withProps } from 'recompose';
import { getAppReady, getBasePath } from '../../state/selectors/app';
import { appReady, appError } from '../../state/actions/app';
import { loadPrivateBrowserFunctions } from '../../lib/load_private_browser_functions';
import { elementsRegistry } from '../../lib/elements_registry';
import { templatesRegistry } from '../../lib/templates_registry';
import { tagsRegistry } from '../../lib/tags_registry';
import { renderFunctionsRegistry } from '../../lib/render_functions_registry';
import { elementSpecs } from '../../../canvas_plugin_src/elements';
import { renderFunctions } from '../../../canvas_plugin_src/renderers';
import { transformSpecs } from '../../../canvas_plugin_src/uis/transforms';
import { modelSpecs } from '../../../canvas_plugin_src/uis/models';
import { viewSpecs } from '../../../canvas_plugin_src/uis/views';
import { datasourceSpecs } from '../../../canvas_plugin_src/uis/datasources';
import { args as argSpecs } from '../../../canvas_plugin_src/uis/arguments';
import { tagSpecs } from '../../../canvas_plugin_src/uis/tags';
import { functions as browserFunctions } from '../../../canvas_plugin_src/functions/browser';
import { functions as commonPluginFunctions } from '../../../canvas_plugin_src/functions/common';
import { templateSpecs } from '../../../canvas_plugin_src/templates';
import { commonFunctions } from '../../../common/functions';
import { clientFunctions } from '../../functions';
import {
argTypeRegistry,
datasourceRegistry,
@ -36,7 +49,7 @@ const mapStateToProps = state => {
};
};
const types = {
addRegistries(registries, {
elements: elementsRegistry,
renderers: renderFunctionsRegistry,
transformUIs: transformRegistry,
@ -46,18 +59,28 @@ const types = {
argumentUIs: argTypeRegistry,
templates: templatesRegistry,
tagUIs: tagsRegistry,
};
});
register(registries, {
elements: elementSpecs,
renderers: renderFunctions,
transformUIs: transformSpecs,
modelUIs: modelSpecs,
viewUIs: viewSpecs,
datasourceUIs: datasourceSpecs,
argumentUIs: argSpecs,
browserFunctions: browserFunctions
.concat(commonFunctions)
.concat(clientFunctions)
.concat(commonPluginFunctions),
templates: templateSpecs,
tagUIs: tagSpecs,
});
const mapDispatchToProps = dispatch => ({
// TODO: the correct socket path should come from upstream, using the constant here is not ideal
setAppReady: basePath => async () => {
setAppReady: () => async () => {
try {
// wait for core interpreter to load
await getInterpreter();
// initialize the socket and interpreter
loadPrivateBrowserFunctions(functionsRegistry);
await loadBrowserRegistries(types, basePath);
// set app state to ready
dispatch(appReady());

View file

@ -8,7 +8,7 @@ import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { compose, withProps } from 'recompose';
import { get } from 'lodash';
import { renderFunctionsRegistry } from '../../lib/render_functions_registry';
import { registries } from '@kbn/interpreter/public';
import { getSelectedPage, getPageById } from '../../state/selectors/workpad';
import { ElementContent as Component } from './element_content';
@ -19,7 +19,7 @@ const mapStateToProps = state => ({
export const ElementContent = compose(
connect(mapStateToProps),
withProps(({ renderable }) => ({
renderFunction: renderFunctionsRegistry.get(get(renderable, 'as')),
renderFunction: registries.renderers.get(get(renderable, 'as')),
}))
)(Component);

View file

@ -5,7 +5,7 @@
*/
import { interpretAst } from 'plugins/interpreter/interpreter';
import { typesRegistry } from 'plugins/interpreter/types_registry';
import { registries } from '@kbn/interpreter/public';
import { fromExpression } from '@kbn/interpreter/common';
import { getState } from '../state/store';
import { getGlobalFilterExpression } from '../state/selectors/workpad';
@ -24,7 +24,7 @@ export const filters = () => ({
const filterAST = fromExpression(filterExpression);
return interpretAst(filterAST);
} else {
const filterType = typesRegistry.get('filter');
const filterType = registries.types.get('filter');
return filterType.from(null);
}
},

View file

@ -4,11 +4,11 @@
* you may not use this file except in compliance with the Elastic License.
*/
import { functionsRegistry } from 'plugins/interpreter/functions_registry';
import { registries } from '@kbn/interpreter/public';
import uniqBy from 'lodash.uniqby';
import { getServerFunctions } from '../state/selectors/app';
export async function getFunctionDefinitions(state) {
const serverFunctions = getServerFunctions(state);
return uniqBy(serverFunctions.concat(functionsRegistry.toArray()), 'name');
return uniqBy(serverFunctions.concat(registries.browserFunctions.toArray()), 'name');
}

View file

@ -1,24 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { commonFunctions } from '../../common/functions';
import { clientFunctions } from '../functions';
/*
Functions loaded here use PRIVATE APIs
That is, they probably import a canvas singleton, eg a registry and
thus must be part of the main Canvas bundle. There should be *very*
few of these things as we can't thread them.
*/
export const loadPrivateBrowserFunctions = functionsRegistry => {
function addFunction(fnDef) {
functionsRegistry.register(fnDef);
}
clientFunctions.forEach(addFunction);
commonFunctions.forEach(addFunction);
};

View file

@ -57,3 +57,14 @@
@import '../components/workpad_loader/workpad_loader';
@import '../components/workpad_loader/workpad_dropzone/workpad_dropzone';
@import '../components/workpad_page/workpad_page';
@import '../../canvas_plugin_src/renderers/markdown/markdown.scss';
@import '../../canvas_plugin_src/renderers/advanced_filter/component/advanced_filter.scss';
@import '../../canvas_plugin_src/renderers/dropdown_filter/component/dropdown_filter.scss';
@import '../../canvas_plugin_src/renderers/plot/plot.scss';
@import '../../canvas_plugin_src/renderers/reveal_image/reveal_image.scss';
@import '../../canvas_plugin_src/renderers/time_filter/components/datetime_calendar/datetime_calendar.scss';
@import '../../canvas_plugin_src/renderers/time_filter/components/datetime_range_absolute/datetime_range_absolute.scss';
@import '../../canvas_plugin_src/renderers/time_filter/components/time_picker/time_picker.scss';
@import '../../canvas_plugin_src/renderers/time_filter/components/time_picker_mini/time_picker_mini.scss';
@import '../../canvas_plugin_src/uis/arguments/image_upload/image_upload.scss';

View file

@ -1,7 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
require('./_helpers').runGulpTask('canvas:plugins:build');

View file

@ -1,7 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
require('./_helpers').runGulpTask('canvas:dev');

View file

@ -1,13 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
// this simply imports functions that run on the server from canvas_plugin_src.
// it's an ugly hack to trick Kibana's build into including dependencies in
// those functions which it would otherwise strip out.
// see https://github.com/elastic/kibana/issues/27729 for an example build issue.
import '../canvas_plugin_src/functions/server/src/index';
import '../canvas_plugin_src/functions/common/index';

View file

@ -1,11 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
export default (gulp, { multiProcess }) => {
gulp.task('canvas:dev', done => {
return multiProcess(['canvas:plugins:dev', 'dev'], done, true);
});
};

View file

@ -1,160 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const {
createServerCodeTransformer,
} = require('@kbn/interpreter/tasks/build/server_code_transformer');
const sourceDir = path.resolve(__dirname, '../../canvas_plugin_src');
const buildDir = path.resolve(__dirname, '../../canvas_plugin');
export function getWebpackConfig({ devtool, watch } = {}) {
return {
watch,
devtool,
mode: 'none',
entry: {
'elements/all': path.join(sourceDir, 'elements/register.js'),
'renderers/all': path.join(sourceDir, 'renderers/register.js'),
'uis/transforms/all': path.join(sourceDir, 'uis/transforms/register.js'),
'uis/models/all': path.join(sourceDir, 'uis/models/register.js'),
'uis/views/all': path.join(sourceDir, 'uis/views/register.js'),
'uis/datasources/all': path.join(sourceDir, 'uis/datasources/register.js'),
'uis/arguments/all': path.join(sourceDir, 'uis/arguments/register.js'),
'functions/browser/all': path.join(sourceDir, 'functions/browser/register.js'),
'functions/browser/common': path.join(sourceDir, 'functions/common/register.js'),
'templates/all': path.join(sourceDir, 'templates/register.js'),
'uis/tags/all': path.join(sourceDir, 'uis/tags/register.js'),
},
// there were problems with the node and web targets since this code is actually
// targetting both the browser and node.js. If there was a hybrid target we'd use
// it, but this seems to work either way.
target: 'webworker',
output: {
path: buildDir,
filename: '[name].js', // Need long paths here.
libraryTarget: 'umd',
// Note: this is needed due to a not yet resolved bug on
// webpack 4 with umd modules generation.
// For now we have 2 quick workarounds: one is what is implemented
// below another is to change the libraryTarget to commonjs
//
// The issues can be followed on:
// https://github.com/webpack/webpack/issues/6642
// https://github.com/webpack/webpack/issues/6525
// https://github.com/webpack/webpack/issues/6677
globalObject: `(typeof self !== 'undefined' ? self : this)`,
},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.json'],
mainFields: ['browser', 'main'],
},
plugins: [
function LoaderFailHandlerPlugin() {
// bails on error, including loader errors
// see https://github.com/webpack/webpack/issues/708, which does not fix loader errors
this.hooks.done.tapPromise('LoaderFailHandlerPlugin', async stats => {
if (!stats.hasErrors()) {
return;
}
const errorMessage = stats.toString('errors-only');
if (watch) {
console.error(errorMessage);
} else {
throw new Error(errorMessage);
}
});
},
new CopyWebpackPlugin([
{
from: path.resolve(sourceDir, 'functions/server'),
to: path.resolve(buildDir, 'functions/server'),
transform: createServerCodeTransformer(!!devtool),
ignore: '**/__tests__/**',
},
{
from: path.resolve(sourceDir, 'functions/common'),
to: path.resolve(buildDir, 'functions/common'),
transform: createServerCodeTransformer(!!devtool),
ignore: '**/__tests__/**',
},
{
from: path.resolve(sourceDir, 'lib'),
to: path.resolve(buildDir, 'lib'),
transform: createServerCodeTransformer(!!devtool),
ignore: '**/__tests__/**',
},
]),
],
module: {
rules: [
{
test: /\.js$/,
exclude: [/node_modules/],
loaders: 'babel-loader',
options: {
babelrc: false,
presets: [require.resolve('@kbn/babel-preset/webpack_preset')],
},
},
{
test: /\.(png|jpg|gif|jpeg|svg)$/,
loaders: ['url-loader'],
},
{
test: /\.(css|scss)$/,
loaders: ['style-loader', 'css-loader', 'sass-loader'],
},
{
test: /\.tsx?$/,
include: sourceDir,
use: [
{
loader: 'ts-loader',
options: {
transpileOnly: true,
experimentalWatchApi: true,
onlyCompileBundledFiles: true,
configFile: require.resolve('../../../../tsconfig.json'),
compilerOptions: {
sourceMap: Boolean(devtool),
},
},
},
],
},
],
},
node: {
// Don't replace built-in globals
__filename: false,
__dirname: false,
},
watchOptions: {
ignored: [/node_modules/],
},
stats: {
// when typescript doesn't do a full type check, as we have the ts-loader
// configured here, it does not have enough information to determine
// whether an imported name is a type or not, so when the name is then
// exported, typescript has no choice but to emit the export. Fortunately,
// the extraneous export should not be harmful, so we just suppress these warnings
// https://github.com/TypeStrong/ts-loader#transpileonly-boolean-defaultfalse
warningsFilter: /export .* was not found in/,
},
};
}

View file

@ -4,14 +4,8 @@
* you may not use this file except in compliance with the Elastic License.
*/
import dev from './dev';
import plugins from './plugins';
import prepare from './prepare';
import test from './test';
export default function canvasTasks(gulp, gulpHelpers) {
dev(gulp, gulpHelpers);
plugins(gulp, gulpHelpers);
prepare(gulp, gulpHelpers);
test(gulp, gulpHelpers);
}

View file

@ -1,45 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import path from 'path';
// eslint-disable-next-line import/no-extraneous-dependencies
import webpack from 'webpack';
import del from 'del';
import { getWebpackConfig } from './helpers/webpack.plugins';
const devtool = 'inline-cheap-module-source-map';
const buildDir = path.resolve(__dirname, '../canvas_plugin');
export default function pluginsTasks(gulp, { log, colors }) {
log(buildDir);
const onComplete = done => (err, stats) => {
if (err) {
done && done(err);
} else {
const seconds = ((stats.endTime - stats.startTime) / 1000).toFixed(2);
log(`${colors.green.bold('canvas:plugins')} Plugins built in ${seconds} seconds`);
done && done();
}
};
gulp.task('canvas:plugins:build', function(done) {
del(buildDir).then(() => webpack(getWebpackConfig({ devtool }), onComplete(done)));
});
// eslint-disable-next-line no-unused-vars
gulp.task('canvas:plugins:dev', function(done /* added to make gulp async */) {
log(`${colors.green.bold('canvas:plugins')} Starting initial build, this will take a while`);
del(buildDir).then(() =>
webpack(getWebpackConfig({ devtool, watch: true }), (err, stats) => {
onComplete()(err, stats);
})
);
});
gulp.task('canvas:plugins:build-prod', function(done) {
del(buildDir).then(() => webpack(getWebpackConfig(), onComplete(done)));
});
}

View file

@ -1,10 +0,0 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
export default gulp => {
// anything that needs to happen pre-build or pre-dev
gulp.task('canvas:prepare', ['canvas:plugins:build-prod']);
};

View file

@ -14,5 +14,5 @@ export default gulp => {
gulp.task('prepare:dev', ['prepare']);
// anything that needs to happen before building
gulp.task('prepare:build', ['prepare', 'canvas:prepare']);
gulp.task('prepare:build', ['prepare']);
};