UNPKG

@stencil/core

Version:

A Compiler for Web Components and Progressive Web Apps

2,051 lines (1,708 loc) • 1.12 MB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var vm = _interopDefault(require('vm')); var fs = _interopDefault(require('fs')); var path$1 = require('path'); var path$1__default = _interopDefault(path$1); var os = _interopDefault(require('os')); var util$3 = _interopDefault(require('util')); var tty = _interopDefault(require('tty')); var net = _interopDefault(require('net')); var url = require('url'); var url__default = _interopDefault(url); var constants = _interopDefault(require('constants')); var stream = _interopDefault(require('stream')); var assert = _interopDefault(require('assert')); var console$1 = _interopDefault(require('console')); var process$1 = _interopDefault(require('process')); var utils$3 = require('../utils'); var ts = _interopDefault(require('typescript')); require('readline'); var mockDoc = require('../mock-doc'); var crypto = require('crypto'); var child_process = require('child_process'); async function startPuppeteerBrowser(config) { if (!config.flags.e2e) { return null; } const env = process.env; const puppeteerDep = config.testing.browserExecutablePath ? 'puppeteer-core' : 'puppeteer'; const puppeteerModulePath = config.sys.lazyRequire.getModulePath(puppeteerDep); const puppeteer = require(puppeteerModulePath); env.__STENCIL_PUPPETEER_MODULE__ = puppeteerModulePath; env.__STENCIL_BROWSER_WAIT_UNTIL = config.testing.browserWaitUntil; if (config.flags.devtools) { config.testing.browserDevtools = true; config.testing.browserHeadless = false; env.__STENCIL_E2E_DEVTOOLS__ = 'true'; } config.logger.debug(`puppeteer: ${puppeteerModulePath}`); config.logger.debug(`puppeteer headless: ${config.testing.browserHeadless}`); if (Array.isArray(config.testing.browserArgs)) { config.logger.debug(`puppeteer args: ${config.testing.browserArgs.join(' ')}`); } if (typeof config.testing.browserDevtools === 'boolean') { config.logger.debug(`puppeteer devtools: ${config.testing.browserDevtools}`); } if (typeof config.testing.browserSlowMo === 'number') { config.logger.debug(`puppeteer slowMo: ${config.testing.browserSlowMo}`); } const launchOpts = { ignoreHTTPSErrors: true, args: config.testing.browserArgs, headless: config.testing.browserHeadless, devtools: config.testing.browserDevtools, slowMo: config.testing.browserSlowMo }; if (config.testing.browserExecutablePath) { launchOpts.executablePath = config.testing.browserExecutablePath; } const browser = await ((config.testing.browserWSEndpoint) ? puppeteer.connect(Object.assign({}, launchOpts, { browserWSEndpoint: config.testing.browserWSEndpoint })) : puppeteer.launch(Object.assign({}, launchOpts))); env.__STENCIL_BROWSER_WS_ENDPOINT__ = browser.wsEndpoint(); config.logger.debug(`puppeteer browser wsEndpoint: ${env.__STENCIL_BROWSER_WS_ENDPOINT__}`); return browser; } async function connectBrowser() { // the reason we're connecting to the browser from // a web socket is because jest probably has us // in a different thread, this is also why this // uses process.env for data const env = process.env; const wsEndpoint = env.__STENCIL_BROWSER_WS_ENDPOINT__; if (!wsEndpoint) { return null; } const connectOpts = { browserWSEndpoint: wsEndpoint, ignoreHTTPSErrors: true }; const puppeteer = require(env.__STENCIL_PUPPETEER_MODULE__); return await puppeteer.connect(connectOpts); } async function disconnectBrowser(browserContext) { if (browserContext) { const browser = browserContext.browser(); try { await browserContext.close(); } catch (e) { } try { browser.disconnect(); } catch (e) { } } } function newBrowserPage(browserContext) { return browserContext.newPage(); } var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function unwrapExports (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } function getCjsExportFromNamespace (n) { return n && n['default'] || n; } var build = createCommonjsModule(function (module) { function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } /** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /** * Possible types of a MockFunctionResult. * 'return': The call completed by returning normally. * 'throw': The call completed by throwing a value. * 'incomplete': The call has not completed yet. This is possible if you read * the mock function result from within the mock function itself * (or a function called by the mock function). */ /** * Represents the result of a single call to a mock function. */ // see https://github.com/Microsoft/TypeScript/issues/25215 const MOCK_CONSTRUCTOR_NAME = 'mockConstructor'; const FUNCTION_NAME_RESERVED_PATTERN = /[\s!-\/:-@\[-`{-~]/; const FUNCTION_NAME_RESERVED_REPLACE = new RegExp( FUNCTION_NAME_RESERVED_PATTERN.source, 'g' ); const RESERVED_KEYWORDS = new Set([ 'arguments', 'await', 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'enum', 'eval', 'export', 'extends', 'false', 'finally', 'for', 'function', 'if', 'implements', 'import', 'in', 'instanceof', 'interface', 'let', 'new', 'null', 'package', 'private', 'protected', 'public', 'return', 'static', 'super', 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'var', 'void', 'while', 'with', 'yield' ]); function matchArity(fn, length) { let mockConstructor; switch (length) { case 1: mockConstructor = function mockConstructor(_a) { return fn.apply(this, arguments); }; break; case 2: mockConstructor = function mockConstructor(_a, _b) { return fn.apply(this, arguments); }; break; case 3: mockConstructor = function mockConstructor(_a, _b, _c) { return fn.apply(this, arguments); }; break; case 4: mockConstructor = function mockConstructor(_a, _b, _c, _d) { return fn.apply(this, arguments); }; break; case 5: mockConstructor = function mockConstructor(_a, _b, _c, _d, _e) { return fn.apply(this, arguments); }; break; case 6: mockConstructor = function mockConstructor(_a, _b, _c, _d, _e, _f) { return fn.apply(this, arguments); }; break; case 7: mockConstructor = function mockConstructor(_a, _b, _c, _d, _e, _f, _g) { return fn.apply(this, arguments); }; break; case 8: mockConstructor = function mockConstructor( _a, _b, _c, _d, _e, _f, _g, _h ) { return fn.apply(this, arguments); }; break; case 9: mockConstructor = function mockConstructor( _a, _b, _c, _d, _e, _f, _g, _h, _i ) { return fn.apply(this, arguments); }; break; default: mockConstructor = function mockConstructor() { return fn.apply(this, arguments); }; break; } return mockConstructor; } function getObjectType(value) { return Object.prototype.toString.apply(value).slice(8, -1); } function getType(ref) { const typeName = getObjectType(ref); if ( typeName === 'Function' || typeName === 'AsyncFunction' || typeName === 'GeneratorFunction' ) { return 'function'; } else if (Array.isArray(ref)) { return 'array'; } else if (typeName === 'Object') { return 'object'; } else if ( typeName === 'Number' || typeName === 'String' || typeName === 'Boolean' || typeName === 'Symbol' ) { return 'constant'; } else if ( typeName === 'Map' || typeName === 'WeakMap' || typeName === 'Set' ) { return 'collection'; } else if (typeName === 'RegExp') { return 'regexp'; } else if (ref === undefined) { return 'undefined'; } else if (ref === null) { return 'null'; } else { return null; } } function isReadonlyProp(object, prop) { if ( prop === 'arguments' || prop === 'caller' || prop === 'callee' || prop === 'name' || prop === 'length' ) { const typeName = getObjectType(object); return ( typeName === 'Function' || typeName === 'AsyncFunction' || typeName === 'GeneratorFunction' ); } if ( prop === 'source' || prop === 'global' || prop === 'ignoreCase' || prop === 'multiline' ) { return getObjectType(object) === 'RegExp'; } return false; } class ModuleMockerClass { /** * @see README.md * @param global Global object of the test environment, used to create * mocks */ constructor(global) { _defineProperty(this, '_environmentGlobal', void 0); _defineProperty(this, '_mockState', void 0); _defineProperty(this, '_mockConfigRegistry', void 0); _defineProperty(this, '_spyState', void 0); _defineProperty(this, '_invocationCallCounter', void 0); _defineProperty(this, 'ModuleMocker', void 0); this._environmentGlobal = global; this._mockState = new WeakMap(); this._mockConfigRegistry = new WeakMap(); this._spyState = new Set(); this.ModuleMocker = ModuleMockerClass; this._invocationCallCounter = 1; } _getSlots(object) { if (!object) { return []; } const slots = new Set(); const EnvObjectProto = this._environmentGlobal.Object.prototype; const EnvFunctionProto = this._environmentGlobal.Function.prototype; const EnvRegExpProto = this._environmentGlobal.RegExp.prototype; // Also check the builtins in the current context as they leak through // core node modules. const ObjectProto = Object.prototype; const FunctionProto = Function.prototype; const RegExpProto = RegExp.prototype; // Properties of Object.prototype, Function.prototype and RegExp.prototype // are never reported as slots while ( object != null && object !== EnvObjectProto && object !== EnvFunctionProto && object !== EnvRegExpProto && object !== ObjectProto && object !== FunctionProto && object !== RegExpProto ) { const ownNames = Object.getOwnPropertyNames(object); for (let i = 0; i < ownNames.length; i++) { const prop = ownNames[i]; if (!isReadonlyProp(object, prop)) { const propDesc = Object.getOwnPropertyDescriptor(object, prop); // @ts-ignore Object.__esModule if ((propDesc !== undefined && !propDesc.get) || object.__esModule) { slots.add(prop); } } } object = Object.getPrototypeOf(object); } return Array.from(slots); } _ensureMockConfig(f) { let config = this._mockConfigRegistry.get(f); if (!config) { config = this._defaultMockConfig(); this._mockConfigRegistry.set(f, config); } return config; } _ensureMockState(f) { let state = this._mockState.get(f); if (!state) { state = this._defaultMockState(); this._mockState.set(f, state); } return state; } _defaultMockConfig() { return { defaultReturnValue: undefined, isReturnValueLastSet: false, mockImpl: undefined, mockName: 'jest.fn()', specificMockImpls: [], specificReturnValues: [] }; } _defaultMockState() { return { calls: [], instances: [], invocationCallOrder: [], results: [] }; } _makeComponent(metadata, restore) { if (metadata.type === 'object') { return new this._environmentGlobal.Object(); } else if (metadata.type === 'array') { return new this._environmentGlobal.Array(); } else if (metadata.type === 'regexp') { return new this._environmentGlobal.RegExp(''); } else if ( metadata.type === 'constant' || metadata.type === 'collection' || metadata.type === 'null' || metadata.type === 'undefined' ) { return metadata.value; } else if (metadata.type === 'function') { const prototype = (metadata.members && metadata.members.prototype && metadata.members.prototype.members) || {}; const prototypeSlots = this._getSlots(prototype); const mocker = this; const mockConstructor = matchArity(function(...args) { const mockState = mocker._ensureMockState(f); const mockConfig = mocker._ensureMockConfig(f); mockState.instances.push(this); mockState.calls.push(args); // Create and record an "incomplete" mock result immediately upon // calling rather than waiting for the mock to return. This avoids // issues caused by recursion where results can be recorded in the // wrong order. const mockResult = { type: 'incomplete', value: undefined }; mockState.results.push(mockResult); mockState.invocationCallOrder.push(mocker._invocationCallCounter++); // Will be set to the return value of the mock if an error is not thrown let finalReturnValue; // Will be set to the error that is thrown by the mock (if it throws) let thrownError; // Will be set to true if the mock throws an error. The presence of a // value in `thrownError` is not a 100% reliable indicator because a // function could throw a value of undefined. let callDidThrowError = false; try { // The bulk of the implementation is wrapped in an immediately // executed arrow function so the return value of the mock function // can be easily captured and recorded, despite the many separate // return points within the logic. finalReturnValue = (() => { if (this instanceof f) { // This is probably being called as a constructor prototypeSlots.forEach(slot => { // Copy prototype methods to the instance to make // it easier to interact with mock instance call and // return values if (prototype[slot].type === 'function') { // @ts-ignore no index signature const protoImpl = this[slot]; // @ts-ignore no index signature this[slot] = mocker.generateFromMetadata(prototype[slot]); // @ts-ignore no index signature this[slot]._protoImpl = protoImpl; } }); // Run the mock constructor implementation const mockImpl = mockConfig.specificMockImpls.length ? mockConfig.specificMockImpls.shift() : mockConfig.mockImpl; return mockImpl && mockImpl.apply(this, arguments); } const returnValue = mockConfig.defaultReturnValue; // If return value is last set, either specific or default, i.e. // mockReturnValueOnce()/mockReturnValue() is called and no // mockImplementationOnce()/mockImplementation() is called after // that. // use the set return value. if (mockConfig.specificReturnValues.length) { return mockConfig.specificReturnValues.shift(); } if (mockConfig.isReturnValueLastSet) { return mockConfig.defaultReturnValue; } // If mockImplementationOnce()/mockImplementation() is last set, // or specific return values are used up, use the mock // implementation. let specificMockImpl; if (returnValue === undefined) { specificMockImpl = mockConfig.specificMockImpls.shift(); if (specificMockImpl === undefined) { specificMockImpl = mockConfig.mockImpl; } if (specificMockImpl) { return specificMockImpl.apply(this, arguments); } } // Otherwise use prototype implementation if (returnValue === undefined && f._protoImpl) { return f._protoImpl.apply(this, arguments); } return returnValue; })(); } catch (error) { // Store the thrown error so we can record it, then re-throw it. thrownError = error; callDidThrowError = true; throw error; } finally { // Record the result of the function. // NOTE: Intentionally NOT pushing/indexing into the array of mock // results here to avoid corrupting results data if mockClear() // is called during the execution of the mock. mockResult.type = callDidThrowError ? 'throw' : 'return'; mockResult.value = callDidThrowError ? thrownError : finalReturnValue; } return finalReturnValue; }, metadata.length || 0); const f = this._createMockFunction(metadata, mockConstructor); f._isMockFunction = true; f.getMockImplementation = () => this._ensureMockConfig(f).mockImpl; if (typeof restore === 'function') { this._spyState.add(restore); } this._mockState.set(f, this._defaultMockState()); this._mockConfigRegistry.set(f, this._defaultMockConfig()); Object.defineProperty(f, 'mock', { configurable: false, enumerable: true, get: () => this._ensureMockState(f), set: val => this._mockState.set(f, val) }); f.mockClear = () => { this._mockState.delete(f); return f; }; f.mockReset = () => { f.mockClear(); this._mockConfigRegistry.delete(f); return f; }; f.mockRestore = () => { f.mockReset(); return restore ? restore() : undefined; }; f.mockReturnValueOnce = value => { // next function call will return this value or default return value const mockConfig = this._ensureMockConfig(f); mockConfig.specificReturnValues.push(value); return f; }; f.mockResolvedValueOnce = value => f.mockImplementationOnce(() => Promise.resolve(value)); f.mockRejectedValueOnce = value => f.mockImplementationOnce(() => Promise.reject(value)); f.mockReturnValue = value => { // next function call will return specified return value or this one const mockConfig = this._ensureMockConfig(f); mockConfig.isReturnValueLastSet = true; mockConfig.defaultReturnValue = value; return f; }; f.mockResolvedValue = value => f.mockImplementation(() => Promise.resolve(value)); f.mockRejectedValue = value => f.mockImplementation(() => Promise.reject(value)); f.mockImplementationOnce = fn => { // next function call will use this mock implementation return value // or default mock implementation return value const mockConfig = this._ensureMockConfig(f); mockConfig.isReturnValueLastSet = false; mockConfig.specificMockImpls.push(fn); return f; }; f.mockImplementation = fn => { // next function call will use mock implementation return value const mockConfig = this._ensureMockConfig(f); mockConfig.isReturnValueLastSet = false; mockConfig.defaultReturnValue = undefined; mockConfig.mockImpl = fn; return f; }; f.mockReturnThis = () => f.mockImplementation(function() { return this; }); f.mockName = name => { if (name) { const mockConfig = this._ensureMockConfig(f); mockConfig.mockName = name; } return f; }; f.getMockName = () => { const mockConfig = this._ensureMockConfig(f); return mockConfig.mockName || 'jest.fn()'; }; if (metadata.mockImpl) { f.mockImplementation(metadata.mockImpl); } return f; } else { const unknownType = metadata.type || 'undefined type'; throw new Error('Unrecognized type ' + unknownType); } } _createMockFunction(metadata, mockConstructor) { let name = metadata.name; if (!name) { return mockConstructor; } // Preserve `name` property of mocked function. const boundFunctionPrefix = 'bound '; let bindCall = ''; // if-do-while for perf reasons. The common case is for the if to fail. if (name && name.startsWith(boundFunctionPrefix)) { do { name = name.substring(boundFunctionPrefix.length); // Call bind() just to alter the function name. bindCall = '.bind(null)'; } while (name && name.startsWith(boundFunctionPrefix)); } // Special case functions named `mockConstructor` to guard for infinite // loops. if (name === MOCK_CONSTRUCTOR_NAME) { return mockConstructor; } if ( // It's a syntax error to define functions with a reserved keyword // as name. RESERVED_KEYWORDS.has(name) || // It's also a syntax error to define functions with a name that starts with a number /^\d/.test(name) ) { name = '$' + name; } // It's also a syntax error to define a function with a reserved character // as part of it's name. if (FUNCTION_NAME_RESERVED_PATTERN.test(name)) { name = name.replace(FUNCTION_NAME_RESERVED_REPLACE, '$'); } const body = 'return function ' + name + '() {' + 'return ' + MOCK_CONSTRUCTOR_NAME + '.apply(this,arguments);' + '}' + bindCall; const createConstructor = new this._environmentGlobal.Function( MOCK_CONSTRUCTOR_NAME, body ); return createConstructor(mockConstructor); } _generateMock(metadata, callbacks, refs) { // metadata not compatible but it's the same type, maybe problem with // overloading of _makeComponent and not _generateMock? // @ts-ignore const mock = this._makeComponent(metadata); if (metadata.refID != null) { refs[metadata.refID] = mock; } this._getSlots(metadata.members).forEach(slot => { const slotMetadata = (metadata.members && metadata.members[slot]) || {}; if (slotMetadata.ref != null) { callbacks.push( (function(ref) { return () => (mock[slot] = refs[ref]); })(slotMetadata.ref) ); } else { mock[slot] = this._generateMock(slotMetadata, callbacks, refs); } }); if ( metadata.type !== 'undefined' && metadata.type !== 'null' && mock.prototype && typeof mock.prototype === 'object' ) { mock.prototype.constructor = mock; } return mock; } /** * @see README.md * @param _metadata Metadata for the mock in the schema returned by the * getMetadata method of this module. */ generateFromMetadata(_metadata) { const callbacks = []; const refs = {}; const mock = this._generateMock(_metadata, callbacks, refs); callbacks.forEach(setter => setter()); return mock; } /** * @see README.md * @param component The component for which to retrieve metadata. */ getMetadata(component, _refs) { const refs = _refs || new Map(); const ref = refs.get(component); if (ref != null) { return { ref }; } const type = getType(component); if (!type) { return null; } const metadata = { type }; if ( type === 'constant' || type === 'collection' || type === 'undefined' || type === 'null' ) { metadata.value = component; return metadata; } else if (type === 'function') { // @ts-ignore this is a function so it has a name metadata.name = component.name; // @ts-ignore may be a mock if (component._isMockFunction === true) { // @ts-ignore may be a mock metadata.mockImpl = component.getMockImplementation(); } } metadata.refID = refs.size; refs.set(component, metadata.refID); let members = null; // Leave arrays alone if (type !== 'array') { this._getSlots(component).forEach(slot => { if ( type === 'function' && // @ts-ignore may be a mock component._isMockFunction === true && slot.match(/^mock/) ) { return; } // @ts-ignore no index signature const slotMetadata = this.getMetadata(component[slot], refs); if (slotMetadata) { if (!members) { members = {}; } members[slot] = slotMetadata; } }); } if (members) { metadata.members = members; } return metadata; } isMockFunction(fn) { return !!fn && fn._isMockFunction === true; } fn(implementation) { const length = implementation ? implementation.length : 0; const fn = this._makeComponent({ length, type: 'function' }); if (implementation) { fn.mockImplementation(implementation); } return fn; } spyOn(object, methodName, accessType) { if (accessType) { return this._spyOnProperty(object, methodName, accessType); } if (typeof object !== 'object' && typeof object !== 'function') { throw new Error( 'Cannot spyOn on a primitive value; ' + this._typeOf(object) + ' given' ); } const original = object[methodName]; if (!this.isMockFunction(original)) { if (typeof original !== 'function') { throw new Error( 'Cannot spy the ' + methodName + ' property because it is not a function; ' + this._typeOf(original) + ' given instead' ); } // @ts-ignore overriding original method with a Mock object[methodName] = this._makeComponent( { type: 'function' }, () => { object[methodName] = original; } ); // @ts-ignore original method is now a Mock object[methodName].mockImplementation(function() { return original.apply(this, arguments); }); } return object[methodName]; } _spyOnProperty(obj, propertyName, accessType = 'get') { if (typeof obj !== 'object' && typeof obj !== 'function') { throw new Error( 'Cannot spyOn on a primitive value; ' + this._typeOf(obj) + ' given' ); } if (!obj) { throw new Error( 'spyOn could not find an object to spy upon for ' + propertyName + '' ); } if (!propertyName) { throw new Error('No property name supplied'); } let descriptor = Object.getOwnPropertyDescriptor(obj, propertyName); let proto = Object.getPrototypeOf(obj); while (!descriptor && proto !== null) { descriptor = Object.getOwnPropertyDescriptor(proto, propertyName); proto = Object.getPrototypeOf(proto); } if (!descriptor) { throw new Error(propertyName + ' property does not exist'); } if (!descriptor.configurable) { throw new Error(propertyName + ' is not declared configurable'); } if (!descriptor[accessType]) { throw new Error( 'Property ' + propertyName + ' does not have access type ' + accessType ); } const original = descriptor[accessType]; if (!this.isMockFunction(original)) { if (typeof original !== 'function') { throw new Error( 'Cannot spy the ' + propertyName + ' property because it is not a function; ' + this._typeOf(original) + ' given instead' ); } descriptor[accessType] = this._makeComponent( { type: 'function' }, () => { descriptor[accessType] = original; Object.defineProperty(obj, propertyName, descriptor); } ); descriptor[accessType].mockImplementation(function() { // @ts-ignore return original.apply(this, arguments); }); } Object.defineProperty(obj, propertyName, descriptor); return descriptor[accessType]; } clearAllMocks() { this._mockState = new WeakMap(); } resetAllMocks() { this._mockConfigRegistry = new WeakMap(); this._mockState = new WeakMap(); } restoreAllMocks() { this._spyState.forEach(restore => restore()); this._spyState = new Set(); } _typeOf(value) { return value == null ? '' + value : typeof value; } } /* eslint-disable-next-line no-redeclare */ const JestMock = new ModuleMockerClass(commonjsGlobal); module.exports = JestMock; }); unwrapExports(build); var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; var escapeStringRegexp = function (str) { if (typeof str !== 'string') { throw new TypeError('Expected a string'); } return str.replace(matchOperatorsRe, '\\$&'); }; var colorName = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "grey": [128, 128, 128], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "rebeccapurple": [102, 51, 153], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50] }; var conversions = createCommonjsModule(function (module) { /* MIT license */ // NOTE: conversions should only return primitive values (i.e. arrays, or // values that give correct `typeof` results). // do not use box values types (i.e. Number(), String(), etc.) var reverseKeywords = {}; for (var key in colorName) { if (colorName.hasOwnProperty(key)) { reverseKeywords[colorName[key]] = key; } } var convert = module.exports = { rgb: {channels: 3, labels: 'rgb'}, hsl: {channels: 3, labels: 'hsl'}, hsv: {channels: 3, labels: 'hsv'}, hwb: {channels: 3, labels: 'hwb'}, cmyk: {channels: 4, labels: 'cmyk'}, xyz: {channels: 3, labels: 'xyz'}, lab: {channels: 3, labels: 'lab'}, lch: {channels: 3, labels: 'lch'}, hex: {channels: 1, labels: ['hex']}, keyword: {channels: 1, labels: ['keyword']}, ansi16: {channels: 1, labels: ['ansi16']}, ansi256: {channels: 1, labels: ['ansi256']}, hcg: {channels: 3, labels: ['h', 'c', 'g']}, apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, gray: {channels: 1, labels: ['gray']} }; // hide .channels and .labels properties for (var model in convert) { if (convert.hasOwnProperty(model)) { if (!('channels' in convert[model])) { throw new Error('missing channels property: ' + model); } if (!('labels' in convert[model])) { throw new Error('missing channel labels property: ' + model); } if (convert[model].labels.length !== convert[model].channels) { throw new Error('channel and label counts mismatch: ' + model); } var channels = convert[model].channels; var labels = convert[model].labels; delete convert[model].channels; delete convert[model].labels; Object.defineProperty(convert[model], 'channels', {value: channels}); Object.defineProperty(convert[model], 'labels', {value: labels}); } } convert.rgb.hsl = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var min = Math.min(r, g, b); var max = Math.max(r, g, b); var delta = max - min; var h; var s; var l; if (max === min) { h = 0; } else if (r === max) { h = (g - b) / delta; } else if (g === max) { h = 2 + (b - r) / delta; } else if (b === max) { h = 4 + (r - g) / delta; } h = Math.min(h * 60, 360); if (h < 0) { h += 360; } l = (min + max) / 2; if (max === min) { s = 0; } else if (l <= 0.5) { s = delta / (max + min); } else { s = delta / (2 - max - min); } return [h, s * 100, l * 100]; }; convert.rgb.hsv = function (rgb) { var rdif; var gdif; var bdif; var h; var s; var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var v = Math.max(r, g, b); var diff = v - Math.min(r, g, b); var diffc = function (c) { return (v - c) / 6 / diff + 1 / 2; }; if (diff === 0) { h = s = 0; } else { s = diff / v; rdif = diffc(r); gdif = diffc(g); bdif = diffc(b); if (r === v) { h = bdif - gdif; } else if (g === v) { h = (1 / 3) + rdif - bdif; } else if (b === v) { h = (2 / 3) + gdif - rdif; } if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } } return [ h * 360, s * 100, v * 100 ]; }; convert.rgb.hwb = function (rgb) { var r = rgb[0]; var g = rgb[1]; var b = rgb[2]; var h = convert.rgb.hsl(rgb)[0]; var w = 1 / 255 * Math.min(r, Math.min(g, b)); b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); return [h, w * 100, b * 100]; }; convert.rgb.cmyk = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var c; var m; var y; var k; k = Math.min(1 - r, 1 - g, 1 - b); c = (1 - r - k) / (1 - k) || 0; m = (1 - g - k) / (1 - k) || 0; y = (1 - b - k) / (1 - k) || 0; return [c * 100, m * 100, y * 100, k * 100]; }; /** * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance * */ function comparativeDistance(x, y) { return ( Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2) ); } convert.rgb.keyword = function (rgb) { var reversed = reverseKeywords[rgb]; if (reversed) { return reversed; } var currentClosestDistance = Infinity; var currentClosestKeyword; for (var keyword in colorName) { if (colorName.hasOwnProperty(keyword)) { var value = colorName[keyword]; // Compute comparative distance var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest if (distance < currentClosestDistance) { currentClosestDistance = distance; currentClosestKeyword = keyword; } } } return currentClosestKeyword; }; convert.keyword.rgb = function (keyword) { return colorName[keyword]; }; convert.rgb.xyz = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; // assume sRGB r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); return [x * 100, y * 100, z * 100]; }; convert.rgb.lab = function (rgb) { var xyz = convert.rgb.xyz(rgb); var x = xyz[0]; var y = xyz[1]; var z = xyz[2]; var l; var a; var b; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); l = (116 * y) - 16; a = 500 * (x - y); b = 200 * (y - z); return [l, a, b]; }; convert.hsl.rgb = function (hsl) { var h = hsl[0] / 360; var s = hsl[1] / 100; var l = hsl[2] / 100; var t1; var t2; var t3; var rgb; var val; if (s === 0) { val = l * 255; return [val, val, val]; } if (l < 0.5) { t2 = l * (1 + s); } else { t2 = l + s - l * s; } t1 = 2 * l - t2; rgb = [0, 0, 0]; for (var i = 0; i < 3; i++) { t3 = h + 1 / 3 * -(i - 1); if (t3 < 0) { t3++; } if (t3 > 1) { t3--; } if (6 * t3 < 1) { val = t1 + (t2 - t1) * 6 * t3; } else if (2 * t3 < 1) { val = t2; } else if (3 * t3 < 2) { val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; } else { val = t1; } rgb[i] = val * 255; } return rgb; }; convert.hsl.hsv = function (hsl) { var h = hsl[0]; var s = hsl[1] / 100; var l = hsl[2] / 100; var smin = s; var lmin = Math.max(l, 0.01); var sv; var v; l *= 2; s *= (l <= 1) ? l : 2 - l; smin *= lmin <= 1 ? lmin : 2 - lmin; v = (l + s) / 2; sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); return [h, sv * 100, v * 100]; }; convert.hsv.rgb = function (hsv) { var h = hsv[0] / 60; var s = hsv[1] / 100; var v = hsv[2] / 100; var hi = Math.floor(h) % 6; var f = h - Math.floor(h); var p = 255 * v * (1 - s); var q = 255 * v * (1 - (s * f)); var t = 255 * v * (1 - (s * (1 - f))); v *= 255; switch (hi) { case 0: return [v, t, p]; case 1: return [q, v, p]; case 2: return [p, v, t]; case 3: return [p, q, v]; case 4: return [t, p, v]; case 5: return [v, p, q]; } }; convert.hsv.hsl = function (hsv) { var h = hsv[0]; var s = hsv[1] / 100; var v = hsv[2] / 100; var vmin = Math.max(v, 0.01); var lmin; var sl; var l; l = (2 - s) * v; lmin = (2 - s) * vmin; sl = s * vmin; sl /= (lmin <= 1) ? lmin : 2 - lmin; sl = sl || 0; l /= 2; return [h, sl * 100, l * 100]; }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb convert.hwb.rgb = function (hwb) { var h = hwb[0] / 360; var wh = hwb[1] / 100; var bl = hwb[2] / 100; var ratio = wh + bl; var i; var v; var f; var n; // wh + bl cant be > 1 if (ratio > 1) { wh /= ratio; bl /= ratio; } i = Math.floor(6 * h); v = 1 - bl; f = 6 * h - i; if ((i & 0x01) !== 0) { f = 1 - f; } n = wh + f * (v - wh); // linear interpolation var r; var g; var b; switch (i) { default: case 6: case 0: r = v; g = n; b = wh; break; case 1: r = n; g = v; b = wh; break; case 2: r = wh; g = v; b = n; break; case 3: r = wh; g = n; b = v; break; case 4: r = n; g = wh; b = v; break; case 5: r = v; g = wh; b = n; break; } return [r * 255, g * 255, b * 255]; }; convert.cmyk.rgb = function (cmyk) { var c = cmyk[0] / 100; var m = cmyk[1] / 100; var y = cmyk[2] / 100; var k = cmyk[3] / 100; var r; var g; var b; r = 1 - Math.min(1, c * (1 - k) + k); g = 1 - Math.min(1, m * (1 - k) + k); b = 1 - Math.min(1, y * (1 - k) + k); return [r * 255, g * 255, b * 255]; }; convert.xyz.rgb = function (xyz) { var x = xyz[0] / 100; var y = xyz[1] / 100; var z = xyz[2] / 100; var r; var g; var b; r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); // assume sRGB r = r > 0.0031308 ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055) : r * 12.92; g = g > 0.0031308 ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055) : g * 12.92; b = b > 0.0031308 ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055) : b * 12.92; r = Math.min(Math.max(0, r), 1); g = Math.min(Math.max(0, g), 1); b = Math.min(Math.max(0, b), 1); return [r * 255, g * 255, b * 255]; }; convert.xyz.lab = function (xyz) { var x = xyz[0]; var y = xyz[1]; var z = xyz[2]; var l; var a; var b; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); l = (116 * y) - 16; a = 500 * (x - y); b = 200 * (y - z); return [l, a, b]; }; convert.lab.xyz = function (lab) { var l = lab[0]; var a = lab[1]; var b = lab[2]; var x; var y; var z; y = (l + 16) / 116; x = a / 500 + y; z = y - b / 200; var y2 = Math.pow(y, 3); var x2 = Math.pow(x, 3); var z2 = Math.pow(z, 3); y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; x *= 95.047; y *= 100; z *= 108.883; return [x, y, z]; }; convert.lab.lch = function (lab) { var l = lab[0]; var a = lab[1]; var b = lab[2]; var hr; var h; var c; hr = Math.atan2(b, a); h = hr * 360 / 2 / Math.PI; if (h < 0) { h += 360; } c = Math.sqrt(a * a + b * b); return [l, c, h]; }; convert.lch.lab = function (lch) { var l = lch[0]; var c = lch[1]; var h = lch[2]; var a; var b; var hr; hr = h / 360 * 2 * Math.PI; a = c * Math.cos(hr); b = c * Math.sin(hr); return [l, a, b]; }; convert.rgb.ansi16 = function (args) { var r = args[0]; var g = args[1]; var b = args[2]; var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization value = Math.round(value / 50); if (value === 0) { return 30; } var ansi = 30 + ((Math.round(b / 255) << 2) | (Math.round(g / 255) << 1) | Math.round(r / 255)); if (value === 2) { ansi += 60; } return ansi; }; convert.hsv.ansi16 = function (args) { // optimization here; we already know the value and don't need to get // it converted for us. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); }; convert.rgb.ansi256 = function (args) { var r = args[0]; var g = args[1]; var b = args[2]; // we use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (r === g && g === b) { if (r < 8) { return 16; } if (r > 248) { return 231; } return Math.round(((r - 8) / 247) * 24) + 232; } var ansi = 16 + (36 * Math.round(r / 255 * 5)) + (6 * Math.round(g / 255 * 5)) + Math.round(b / 255 * 5); return ansi; }; convert.ansi16.rgb = function (args) { var color = args % 10; // handle greyscale if (color === 0 || color === 7) { if (args > 50) { color += 3.5; } color = color / 10.5 * 255; return [color, color, color]; } var mult = (~~(args > 50) + 1) * 0.5; var r = ((color & 1) * mult) * 255; var g = (((color >> 1) & 1) * mult) * 255; var b = (((color >> 2) & 1) * mult) * 255; return [r, g, b]; }; convert.ansi256.rgb = function (args) { // handle greyscale if (args >= 232) { var c = (args - 232) * 10 + 8; return [c, c, c]; } args -= 16; var rem; var r = Math.floor(args / 36) / 5 * 255; var g = Math.floor((rem = args % 36) / 6) / 5 * 255; var b = (rem % 6) / 5 * 255; return [r, g, b]; }; convert.rgb.hex = function (args) { var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); var string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.hex.rgb = function (args) { var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); if (!match) { return [0, 0, 0]; } var colorString = match[0]; if (match[0].length === 3) { colorString = colorString.split('').map(function (char) { return char + char; }).join(''); } var integer = parseInt(colorString, 16); var r = (integer >> 16) & 0xFF; var g = (integer >> 8) & 0xFF; var b = integer & 0xFF; return [r, g, b]; }; convert.rgb.hcg = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var max = Math.max(Math.max(r, g), b); var min = Math.min(Math.min(r, g), b); var chroma = (max - min); var grayscale; var hue; if (chroma < 1) { grayscale = min / (1 - chroma); } else { grayscale = 0; } if (chroma <= 0) { hue = 0; } else if (max === r) { hue = ((g - b) / chroma) % 6; } else if (max === g) { hue = 2 + (b - r) / chroma; } else { hue = 4 + (r - g) / chroma + 4; } hue /= 6; hue %= 1; return [hue * 360, chroma * 100, grayscale * 100]; }; convert.hsl.hcg = function (hsl) { var s = hsl[1] / 100; var l = hsl[2] / 100; var c = 1; var f = 0; if (l < 0.5) { c = 2.0 * s * l; } else { c = 2.0 * s * (1.0 - l); } if (c < 1.0) { f = (l - 0.5 * c) / (1.0 - c); } return [hsl[0], c * 100, f * 100]; }; convert.hsv.hcg = function (hsv) { var s = hsv[1] / 100; var v = hsv[2] / 100; var c = s * v; var f = 0; if (c < 1.0) { f = (v - c) / (1 - c); } return [hsv[0], c * 100, f * 100]; }; convert.hcg.rgb = function (hcg) { var h = hcg[0] / 360; var c = hcg[1] / 100; var g = hcg[2] / 100; if (c === 0.0) { return [g * 255, g * 255, g * 255]; } var pure = [0, 0, 0]; var hi = (h % 1) * 6; var v = hi % 1; var w = 1 - v; var mg = 0; switch (Math.floor(hi)) { case 0: pure[0] = 1; pure[1] = v; pure[2] = 0; break; case 1: pure[0] = w; pure[1] = 1; pure[2] = 0; break; case 2: pure[0] = 0; pure[1] = 1; pure[2] = v; break; case 3: pure[0] = 0; pure[1] = w; pure[2] = 1; break; case 4: pure[0] = v; pure[1] = 0; pure[2] = 1; break; default: pure[0] = 1; pure[1] = 0; pure[2] = w; } mg = (1.0 - c) * g; return [ (c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255 ]; }; convert.hcg.hsv = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var v = c + g * (1.0 - c); var f = 0; if (v > 0.0) { f = c / v; } return [hcg[0], f * 100, v * 100]; }; convert.hcg.hsl = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var l = g * (1.0 - c) + 0.5 * c; var s = 0; if (l > 0.0 && l < 0.5) { s = c / (2 * l); } else if (l >= 0.5 && l < 1.0) { s = c / (2 * (1 - l)); } return [hcg[0], s * 100, l * 100]; };