text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { BigNumber } from '@0x/utils'; import { SourceFilters } from './source_filters'; import { CurveFunctionSelectors, CurveInfo, ERC20BridgeSource, GetMarketOrdersOpts } from './types'; // tslint:disable: custom-no-magic-numbers no-bitwise /** * Valid sources for market sell. */ export const SELL_SOURCE_FILTER = new SourceFilters([ ERC20BridgeSource.Native, ERC20BridgeSource.Uniswap, ERC20BridgeSource.UniswapV2, ERC20BridgeSource.Eth2Dai, ERC20BridgeSource.Kyber, ERC20BridgeSource.Curve, ERC20BridgeSource.Balancer, // Bancor is sampled off-chain, but this list should only include on-chain sources (used in ERC20BridgeSampler) // ERC20BridgeSource.Bancor, ERC20BridgeSource.MStable, ERC20BridgeSource.Mooniswap, ERC20BridgeSource.Swerve, ERC20BridgeSource.SnowSwap, ERC20BridgeSource.SushiSwap, ERC20BridgeSource.Shell, ERC20BridgeSource.MultiHop, ERC20BridgeSource.Dodo, ERC20BridgeSource.Cream, ]); /** * Valid sources for market buy. */ export const BUY_SOURCE_FILTER = new SourceFilters( [ ERC20BridgeSource.Native, ERC20BridgeSource.Uniswap, ERC20BridgeSource.UniswapV2, ERC20BridgeSource.Eth2Dai, ERC20BridgeSource.Kyber, ERC20BridgeSource.Curve, ERC20BridgeSource.Balancer, // ERC20BridgeSource.Bancor, // FIXME: Disabled until Bancor SDK supports buy quotes ERC20BridgeSource.MStable, ERC20BridgeSource.Mooniswap, ERC20BridgeSource.Shell, ERC20BridgeSource.Swerve, ERC20BridgeSource.SnowSwap, ERC20BridgeSource.SushiSwap, ERC20BridgeSource.MultiHop, ERC20BridgeSource.Dodo, ERC20BridgeSource.Cream, ], [ERC20BridgeSource.MultiBridge], ); export const DEFAULT_GET_MARKET_ORDERS_OPTS: GetMarketOrdersOpts = { // tslint:disable-next-line: custom-no-magic-numbers runLimit: 2 ** 15, excludedSources: [], excludedFeeSources: [], includedSources: [], bridgeSlippage: 0.005, maxFallbackSlippage: 0.05, numSamples: 13, sampleDistributionBase: 1.05, feeSchedule: {}, gasSchedule: {}, exchangeProxyOverhead: () => ZERO_AMOUNT, allowFallback: true, shouldGenerateQuoteReport: false, }; /** * Sources to poll for ETH fee price estimates. */ export const FEE_QUOTE_SOURCES = [ERC20BridgeSource.Uniswap, ERC20BridgeSource.UniswapV2]; export const SOURCE_FLAGS: { [source in ERC20BridgeSource]: number } = Object.assign( {}, ...Object.values(ERC20BridgeSource).map((source: ERC20BridgeSource, index) => ({ [source]: 1 << index })), ); /** * Mainnet Curve configuration */ export const MAINNET_CURVE_INFOS: { [name: string]: CurveInfo } = { DaiUsdc: { exchangeFunctionSelector: CurveFunctionSelectors.exchange_underlying, sellQuoteFunctionSelector: CurveFunctionSelectors.get_dy_underlying, buyQuoteFunctionSelector: CurveFunctionSelectors.get_dx_underlying, poolAddress: '0xa2b47e3d5c44877cca798226b7b8118f9bfb7a56', tokens: ['0x6b175474e89094c44da98b954eedeac495271d0f', '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48'], }, // DaiUsdcUsdt: { // exchangeFunctionSelector: CurveFunctionSelectors.exchange_underlying, // sellQuoteFunctionSelector: CurveFunctionSelectors.get_dy_underlying, // buyQuoteFunctionSelector: CurveFunctionSelectors.get_dx_underlying, // poolAddress: '0x52ea46506b9cc5ef470c5bf89f17dc28bb35d85c', // tokens: [ // '0x6b175474e89094c44da98b954eedeac495271d0f', // '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', // '0xdac17f958d2ee523a2206206994597c13d831ec7', // ], // }, DaiUsdcUsdtTusd: { exchangeFunctionSelector: CurveFunctionSelectors.exchange_underlying, sellQuoteFunctionSelector: CurveFunctionSelectors.get_dy_underlying, buyQuoteFunctionSelector: CurveFunctionSelectors.get_dx_underlying, poolAddress: '0x45f783cce6b7ff23b2ab2d70e416cdb7d6055f51', tokens: [ '0x6b175474e89094c44da98b954eedeac495271d0f', '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', '0xdac17f958d2ee523a2206206994597c13d831ec7', '0x0000000000085d4780b73119b644ae5ecd22b376', ], }, // Looks like it's dying. DaiUsdcUsdtBusd: { exchangeFunctionSelector: CurveFunctionSelectors.exchange_underlying, sellQuoteFunctionSelector: CurveFunctionSelectors.get_dy_underlying, buyQuoteFunctionSelector: CurveFunctionSelectors.get_dx_underlying, poolAddress: '0x79a8c46dea5ada233abaffd40f3a0a2b1e5a4f27', tokens: [ '0x6b175474e89094c44da98b954eedeac495271d0f', '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', '0xdac17f958d2ee523a2206206994597c13d831ec7', '0x4fabb145d64652a948d72533023f6e7a623c7c53', ], }, DaiUsdcUsdtSusd: { exchangeFunctionSelector: CurveFunctionSelectors.exchange_underlying, sellQuoteFunctionSelector: CurveFunctionSelectors.get_dy_underlying, buyQuoteFunctionSelector: CurveFunctionSelectors.None, poolAddress: '0xa5407eae9ba41422680e2e00537571bcc53efbfd', tokens: [ '0x6b175474e89094c44da98b954eedeac495271d0f', '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', '0xdac17f958d2ee523a2206206994597c13d831ec7', '0x57ab1ec28d129707052df4df418d58a2d46d5f51', ], }, RenbtcWbtc: { exchangeFunctionSelector: CurveFunctionSelectors.exchange, sellQuoteFunctionSelector: CurveFunctionSelectors.get_dy, buyQuoteFunctionSelector: CurveFunctionSelectors.None, poolAddress: '0x93054188d876f558f4a66b2ef1d97d16edf0895b', tokens: ['0xeb4c2781e4eba804ce9a9803c67d0893436bb27d', '0x2260fac5e5542a773aa44fbcfedf7c193bc2c599'], }, RenbtcWbtcSbtc: { exchangeFunctionSelector: CurveFunctionSelectors.exchange, sellQuoteFunctionSelector: CurveFunctionSelectors.get_dy, buyQuoteFunctionSelector: CurveFunctionSelectors.None, poolAddress: '0x7fc77b5c7614e1533320ea6ddc2eb61fa00a9714', tokens: [ '0xeb4c2781e4eba804ce9a9803c67d0893436bb27d', '0x2260fac5e5542a773aa44fbcfedf7c193bc2c599', '0xfe18be6b3bd88a2d2a7f928d00292e7a9963cfc6', ], }, TriPool: { exchangeFunctionSelector: CurveFunctionSelectors.exchange, sellQuoteFunctionSelector: CurveFunctionSelectors.get_dy, buyQuoteFunctionSelector: CurveFunctionSelectors.None, poolAddress: '0xbebc44782c7db0a1a60cb6fe97d0b483032ff1c7', tokens: [ '0x6b175474e89094c44da98b954eedeac495271d0f', '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', '0xdac17f958d2ee523a2206206994597c13d831ec7', ], }, }; export const MAINNET_SWERVE_INFOS: { [name: string]: CurveInfo } = { swUSD: { exchangeFunctionSelector: CurveFunctionSelectors.exchange, sellQuoteFunctionSelector: CurveFunctionSelectors.get_dy, buyQuoteFunctionSelector: CurveFunctionSelectors.None, poolAddress: '0x329239599afb305da0a2ec69c58f8a6697f9f88d', // _target: 0xa5407eae9ba41422680e2e00537571bcc53efbfd tokens: [ '0x6b175474e89094c44da98b954eedeac495271d0f', '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', '0xdac17f958d2ee523a2206206994597c13d831ec7', '0x0000000000085d4780b73119b644ae5ecd22b376', ], }, }; export const MAINNET_SNOWSWAP_INFOS: { [name: string]: CurveInfo } = { yVaultCurve: { exchangeFunctionSelector: CurveFunctionSelectors.exchange, sellQuoteFunctionSelector: CurveFunctionSelectors.get_dy, buyQuoteFunctionSelector: CurveFunctionSelectors.get_dx, poolAddress: '0xbf7ccd6c446acfcc5df023043f2167b62e81899b', tokens: [ '0x5dbcf33d8c2e976c6b560249878e6f1491bca25c', // yUSD '0x2994529c0652d127b7842094103715ec5299bbed', // ybCRV ], }, yVaultCurveUnderlying: { exchangeFunctionSelector: CurveFunctionSelectors.exchange_underlying, sellQuoteFunctionSelector: CurveFunctionSelectors.get_dy_underlying, buyQuoteFunctionSelector: CurveFunctionSelectors.get_dx_underlying, poolAddress: '0xbf7ccd6c446acfcc5df023043f2167b62e81899b', tokens: [ '0xdf5e0e81dff6faf3a7e52ba697820c5e32d806a8', // yCRV '0x3b3ac5386837dc563660fb6a0937dfaa5924333b', // bCRV ], }, yVaultUSD: { exchangeFunctionSelector: CurveFunctionSelectors.exchange, sellQuoteFunctionSelector: CurveFunctionSelectors.get_dy, buyQuoteFunctionSelector: CurveFunctionSelectors.get_dx, poolAddress: '0x4571753311e37ddb44faa8fb78a6df9a6e3c6c0b', tokens: [ '0xacd43e627e64355f1861cec6d3a6688b31a6f952', // yDAI '0x597ad1e0c13bfe8025993d9e79c69e1c0233522e', // yUSDC '0x2f08119c6f07c006695e079aafc638b8789faf18', // yUSDT '0x37d19d1c4e1fa9dc47bd1ea12f742a0887eda74a', // yTUSD ], }, // Gas is too high for these underlying tokens (3M+) // yVaultUSDUnderlying: { // exchangeFunctionSelector: CurveFunctionSelectors.exchange_underlying, // sellQuoteFunctionSelector: CurveFunctionSelectors.get_dy_underlying, // buyQuoteFunctionSelector: CurveFunctionSelectors.get_dx_underlying, // poolAddress: '0x4571753311e37ddb44faa8fb78a6df9a6e3c6c0b', // tokens: [ // '0x6b175474e89094c44da98b954eedeac495271d0f', // DAI // '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', // USDC // '0xdac17f958d2ee523a2206206994597c13d831ec7', // USDT // '0x0000000000085d4780b73119b644ae5ecd22b376', // TUSD // ], // }, }; export const MAINNET_KYBER_RESERVE_IDS: { [name: string]: string } = { Reserve1: '0xff4b796265722046707200000000000000000000000000000000000000000000', Reserve2: '0xffabcd0000000000000000000000000000000000000000000000000000000000', Reserve3: '0xff4f6e65426974205175616e7400000000000000000000000000000000000000', }; export const MAINNET_KYBER_TOKEN_RESERVE_IDS: { [token: string]: string } = { // USDC ['0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48']: '0xaa55534443303041505200000000000000000000000000000000000000000000', // AMPL ['0xd46ba6d942050d489dbd938a2c909a5d5039a161']: '0xaad46ba6d942050d489dbd938a2c909a5d5039a1610000000000000000000000', // UBT ['0x8400d94a5cb0fa0d041a3788e395285d61c9ee5e']: '0xaa55425400000000000000000000000000000000000000000000000000000000', // ANT ['0x960b236a07cf122663c4303350609a66a7b288c0']: '0xaa414e5400000000000000000000000000000000000000000000000000000000', // KNC ['0xdd974d5c2e2928dea5f71b9825b8b646686bd200']: '0xaa4b4e435f4d4547414c41444f4e000000000000000000000000000000000000', // sUSD ['0x57ab1ec28d129707052df4df418d58a2d46d5f51']: '0xaa73555344000000000000000000000000000000000000000000000000000000', // SNX ['0xc011a73ee8576fb46f5e1c5751ca3b9fe0af2a6f']: '0xaa534e5800000000000000000000000000000000000000000000000000000000', // REN ['0x408e41876cccdc0f92210600ef50372656052a38']: '0xaa72656e00000000000000000000000000000000000000000000000000000000', // BAND ['0xba11d00c5f74255f56a5e366f4f77f5a186d7f55']: '0xaa42414e44000000000000000000000000000000000000000000000000000000', }; export const MAINNET_SUSHI_SWAP_ROUTER = '0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F'; export const ERC20_PROXY_ID = '0xf47261b0'; export const WALLET_SIGNATURE = '0x04'; export const ONE_ETHER = new BigNumber(1e18); export const NEGATIVE_INF = new BigNumber('-Infinity'); export const POSITIVE_INF = new BigNumber('Infinity'); export const ZERO_AMOUNT = new BigNumber(0); export const MAX_UINT256 = new BigNumber(2).pow(256).minus(1); export const ONE_HOUR_IN_SECONDS = 60 * 60; export const ONE_SECOND_MS = 1000; export const NULL_BYTES = '0x'; export const NULL_ADDRESS = '0x0000000000000000000000000000000000000000'; export const COMPARISON_PRICE_DECIMALS = 5;
the_stack
import { dew as _npmNgraphDew } from "/npm:ngraph.events@1?dew"; var exports = {}, _dewExec = false; var _global = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : global; export function dew() { if (_dewExec) return exports; _dewExec = true; /** * @fileOverview Contains definition of the core graph object. */ // TODO: need to change storage layer: // 1. Be able to get all nodes O(1) // 2. Be able to get number of links O(1) /** * @example * var graph = require('ngraph.graph')(); * graph.addNode(1); // graph has one node. * graph.addLink(2, 3); // now graph contains three nodes and one link. * */ exports = createGraph; var eventify = _npmNgraphDew(); /** * Creates a new graph */ function createGraph(options) { // Graph structure is maintained as dictionary of nodes // and array of links. Each node has 'links' property which // hold all links related to that node. And general links // array is used to speed up all links enumeration. This is inefficient // in terms of memory, but simplifies coding. options = options || {}; if ('uniqueLinkId' in options) { console.warn('ngraph.graph: Starting from version 0.14 `uniqueLinkId` is deprecated.\n' + 'Use `multigraph` option instead\n', '\n', 'Note: there is also change in default behavior: From now on each graph\n' + 'is considered to be not a multigraph by default (each edge is unique).'); options.multigraph = options.uniqueLinkId; } // Dear reader, the non-multigraphs do not guarantee that there is only // one link for a given pair of node. When this option is set to false // we can save some memory and CPU (18% faster for non-multigraph); if (options.multigraph === undefined) options.multigraph = false; if (typeof Map !== 'function') { // TODO: Should we polyfill it ourselves? We don't use much operations there.. throw new Error('ngraph.graph requires `Map` to be defined. Please polyfill it before using ngraph'); } var nodes = new Map(); var links = [], // Hash of multi-edges. Used to track ids of edges between same nodes multiEdges = {}, suspendEvents = 0, createLink = options.multigraph ? createUniqueLink : createSingleLink, // Our graph API provides means to listen to graph changes. Users can subscribe // to be notified about changes in the graph by using `on` method. However // in some cases they don't use it. To avoid unnecessary memory consumption // we will not record graph changes until we have at least one subscriber. // Code below supports this optimization. // // Accumulates all changes made during graph updates. // Each change element contains: // changeType - one of the strings: 'add', 'remove' or 'update'; // node - if change is related to node this property is set to changed graph's node; // link - if change is related to link this property is set to changed graph's link; changes = [], recordLinkChange = noop, recordNodeChange = noop, enterModification = noop, exitModification = noop; // this is our public API: var graphPart = { /** * Adds node to the graph. If node with given id already exists in the graph * its data is extended with whatever comes in 'data' argument. * * @param nodeId the node's identifier. A string or number is preferred. * @param [data] additional data for the node being added. If node already * exists its data object is augmented with the new one. * * @return {node} The newly added node or node with given id if it already exists. */ addNode: addNode, /** * Adds a link to the graph. The function always create a new * link between two nodes. If one of the nodes does not exists * a new node is created. * * @param fromId link start node id; * @param toId link end node id; * @param [data] additional data to be set on the new link; * * @return {link} The newly created link */ addLink: addLink, /** * Removes link from the graph. If link does not exist does nothing. * * @param link - object returned by addLink() or getLinks() methods. * * @returns true if link was removed; false otherwise. */ removeLink: removeLink, /** * Removes node with given id from the graph. If node does not exist in the graph * does nothing. * * @param nodeId node's identifier passed to addNode() function. * * @returns true if node was removed; false otherwise. */ removeNode: removeNode, /** * Gets node with given identifier. If node does not exist undefined value is returned. * * @param nodeId requested node identifier; * * @return {node} in with requested identifier or undefined if no such node exists. */ getNode: getNode, /** * Gets number of nodes in this graph. * * @return number of nodes in the graph. */ getNodeCount: getNodeCount, /** * Gets total number of links in the graph. */ getLinkCount: getLinkCount, /** * Synonym for `getLinkCount()` */ getLinksCount: getLinkCount, /** * Synonym for `getNodeCount()` */ getNodesCount: getNodeCount, /** * Gets all links (inbound and outbound) from the node with given id. * If node with given id is not found null is returned. * * @param nodeId requested node identifier. * * @return Array of links from and to requested node if such node exists; * otherwise null is returned. */ getLinks: getLinks, /** * Invokes callback on each node of the graph. * * @param {Function(node)} callback Function to be invoked. The function * is passed one argument: visited node. */ forEachNode: forEachNode, /** * Invokes callback on every linked (adjacent) node to the given one. * * @param nodeId Identifier of the requested node. * @param {Function(node, link)} callback Function to be called on all linked nodes. * The function is passed two parameters: adjacent node and link object itself. * @param oriented if true graph treated as oriented. */ forEachLinkedNode: forEachLinkedNode, /** * Enumerates all links in the graph * * @param {Function(link)} callback Function to be called on all links in the graph. * The function is passed one parameter: graph's link object. * * Link object contains at least the following fields: * fromId - node id where link starts; * toId - node id where link ends, * data - additional data passed to graph.addLink() method. */ forEachLink: forEachLink, /** * Suspend all notifications about graph changes until * endUpdate is called. */ beginUpdate: enterModification, /** * Resumes all notifications about graph changes and fires * graph 'changed' event in case there are any pending changes. */ endUpdate: exitModification, /** * Removes all nodes and links from the graph. */ clear: clear, /** * Detects whether there is a link between two nodes. * Operation complexity is O(n) where n - number of links of a node. * NOTE: this function is synonim for getLink() * * @returns link if there is one. null otherwise. */ hasLink: getLink, /** * Detects whether there is a node with given id * * Operation complexity is O(1) * NOTE: this function is synonim for getNode() * * @returns node if there is one; Falsy value otherwise. */ hasNode: getNode, /** * Gets an edge between two nodes. * Operation complexity is O(n) where n - number of links of a node. * * @param {string} fromId link start identifier * @param {string} toId link end identifier * * @returns link if there is one. null otherwise. */ getLink: getLink }; // this will add `on()` and `fire()` methods. eventify(graphPart); monitorSubscribers(); return graphPart; function monitorSubscribers() { var realOn = graphPart.on; // replace real `on` with our temporary on, which will trigger change // modification monitoring: graphPart.on = on; function on() { // now it's time to start tracking stuff: graphPart.beginUpdate = enterModification = enterModificationReal; graphPart.endUpdate = exitModification = exitModificationReal; recordLinkChange = recordLinkChangeReal; recordNodeChange = recordNodeChangeReal; // this will replace current `on` method with real pub/sub from `eventify`. graphPart.on = realOn; // delegate to real `on` handler: return realOn.apply(graphPart, arguments); } } function recordLinkChangeReal(link, changeType) { changes.push({ link: link, changeType: changeType }); } function recordNodeChangeReal(node, changeType) { changes.push({ node: node, changeType: changeType }); } function addNode(nodeId, data) { if (nodeId === undefined) { throw new Error('Invalid node identifier'); } enterModification(); var node = getNode(nodeId); if (!node) { node = new Node(nodeId, data); recordNodeChange(node, 'add'); } else { node.data = data; recordNodeChange(node, 'update'); } nodes.set(nodeId, node); exitModification(); return node; } function getNode(nodeId) { return nodes.get(nodeId); } function removeNode(nodeId) { var node = getNode(nodeId); if (!node) { return false; } enterModification(); var prevLinks = node.links; if (prevLinks) { node.links = null; for (var i = 0; i < prevLinks.length; ++i) { removeLink(prevLinks[i]); } } nodes.delete(nodeId); recordNodeChange(node, 'remove'); exitModification(); return true; } function addLink(fromId, toId, data) { enterModification(); var fromNode = getNode(fromId) || addNode(fromId); var toNode = getNode(toId) || addNode(toId); var link = createLink(fromId, toId, data); links.push(link); // TODO: this is not cool. On large graphs potentially would consume more memory. addLinkToNode(fromNode, link); if (fromId !== toId) { // make sure we are not duplicating links for self-loops addLinkToNode(toNode, link); } recordLinkChange(link, 'add'); exitModification(); return link; } function createSingleLink(fromId, toId, data) { var linkId = makeLinkId(fromId, toId); return new Link(fromId, toId, data, linkId); } function createUniqueLink(fromId, toId, data) { // TODO: Get rid of this method. var linkId = makeLinkId(fromId, toId); var isMultiEdge = multiEdges.hasOwnProperty(linkId); if (isMultiEdge || getLink(fromId, toId)) { if (!isMultiEdge) { multiEdges[linkId] = 0; } var suffix = '@' + ++multiEdges[linkId]; linkId = makeLinkId(fromId + suffix, toId + suffix); } return new Link(fromId, toId, data, linkId); } function getNodeCount() { return nodes.size; } function getLinkCount() { return links.length; } function getLinks(nodeId) { var node = getNode(nodeId); return node ? node.links : null; } function removeLink(link) { if (!link) { return false; } var idx = indexOfElementInArray(link, links); if (idx < 0) { return false; } enterModification(); links.splice(idx, 1); var fromNode = getNode(link.fromId); var toNode = getNode(link.toId); if (fromNode) { idx = indexOfElementInArray(link, fromNode.links); if (idx >= 0) { fromNode.links.splice(idx, 1); } } if (toNode) { idx = indexOfElementInArray(link, toNode.links); if (idx >= 0) { toNode.links.splice(idx, 1); } } recordLinkChange(link, 'remove'); exitModification(); return true; } function getLink(fromNodeId, toNodeId) { // TODO: Use sorted links to speed this up var node = getNode(fromNodeId), i; if (!node || !node.links) { return null; } for (i = 0; i < node.links.length; ++i) { var link = node.links[i]; if (link.fromId === fromNodeId && link.toId === toNodeId) { return link; } } return null; // no link. } function clear() { enterModification(); forEachNode(function (node) { removeNode(node.id); }); exitModification(); } function forEachLink(callback) { var i, length; if (typeof callback === 'function') { for (i = 0, length = links.length; i < length; ++i) { callback(links[i]); } } } function forEachLinkedNode(nodeId, callback, oriented) { var node = getNode(nodeId); if (node && node.links && typeof callback === 'function') { if (oriented) { return forEachOrientedLink(node.links, nodeId, callback); } else { return forEachNonOrientedLink(node.links, nodeId, callback); } } } function forEachNonOrientedLink(links, nodeId, callback) { var quitFast; for (var i = 0; i < links.length; ++i) { var link = links[i]; var linkedNodeId = link.fromId === nodeId ? link.toId : link.fromId; quitFast = callback(nodes.get(linkedNodeId), link); if (quitFast) { return true; // Client does not need more iterations. Break now. } } } function forEachOrientedLink(links, nodeId, callback) { var quitFast; for (var i = 0; i < links.length; ++i) { var link = links[i]; if (link.fromId === nodeId) { quitFast = callback(nodes.get(link.toId), link); if (quitFast) { return true; // Client does not need more iterations. Break now. } } } } // we will not fire anything until users of this library explicitly call `on()` // method. function noop() {} // Enter, Exit modification allows bulk graph updates without firing events. function enterModificationReal() { suspendEvents += 1; } function exitModificationReal() { suspendEvents -= 1; if (suspendEvents === 0 && changes.length > 0) { graphPart.fire('changed', changes); changes.length = 0; } } function forEachNode(callback) { if (typeof callback !== 'function') { throw new Error('Function is expected to iterate over graph nodes. You passed ' + callback); } var valuesIterator = nodes.values(); var nextValue = valuesIterator.next(); while (!nextValue.done) { if (callback(nextValue.value)) { return true; // client doesn't want to proceed. Return. } nextValue = valuesIterator.next(); } } } // need this for old browsers. Should this be a separate module? function indexOfElementInArray(element, array) { if (!array) return -1; if (array.indexOf) { return array.indexOf(element); } var len = array.length, i; for (i = 0; i < len; i += 1) { if (array[i] === element) { return i; } } return -1; } /** * Internal structure to represent node; */ function Node(id, data) { (this || _global).id = id; (this || _global).links = null; (this || _global).data = data; } function addLinkToNode(node, link) { if (node.links) { node.links.push(link); } else { node.links = [link]; } } /** * Internal structure to represent links; */ function Link(fromId, toId, data, id) { (this || _global).fromId = fromId; (this || _global).toId = toId; (this || _global).data = data; (this || _global).id = id; } function makeLinkId(fromId, toId) { return fromId.toString() + '👉 ' + toId.toString(); } return exports; }
the_stack
import { CloseOutlined, EditOutlined, EyeOutlined, FileAddOutlined, GithubOutlined, PlusOutlined, SettingOutlined, UploadOutlined, } from '@ant-design/icons'; import { Button, Drawer, message } from 'antd'; import React, { useCallback, useEffect, useRef, useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import usePostMessage from '~/hooks/usePostMessage'; import { Dispatch, RootState } from '~/redux/store'; import MiniDashboard from '../MiniDashboard'; import s from './Responsive.module.less'; import Draggable from 'react-draggable'; import Ruler from './Ruler'; import Repository from '../MiniDashboard/Repository'; import PageSetting from '../MiniDashboard/PageSetting'; import CreateProject from '../CreateProject'; import classNames from 'classnames'; import { AppDataListTypes } from '~/types/appData'; import useLocalStorage from '~/hooks/useLocalStorage'; import { createTemplate, updateTemplate } from '~/api'; import { cloneDeep } from 'lodash'; import TemplateInfoModal from '../TemplateInfoModal'; import { TemplateInfo } from '../TemplateInfoModal/TemplateInfoModal'; import { Template } from '~/types/pageData'; import { useHistory } from 'react-router-dom'; import LoadingAnimate from './LoadingAnimate'; import { trackPageView } from '~/core/tracking'; // import loading from "~/core/loading"; interface Props {} const Responsive: React.FC<Props> = () => { useEffect(() => { trackPageView('/首页'); }, []); /** * ---------- * 定义编辑模式 * ---------- */ const { isEditing, auth } = useSelector( (state: RootState) => state.controller, ); const history = useHistory(); const appData = useSelector((state: RootState) => state.appData); const activationItem = useSelector( (state: RootState) => state.activationItem, ); const stateTag = useSelector((state: RootState) => state.controller.stateTag); const forceUpdateByStateTag = useDispatch<Dispatch>().controller.forceUpdateByStateTag; const setIsEditing = useDispatch<Dispatch>().controller.setIsEditing; const updateAppData = useDispatch<Dispatch>().appData.updateAppData; const updatePageData = useDispatch<Dispatch>().pageData.updatePage; const setWindowHeight = useDispatch<Dispatch>().pageData.setWindowHeight; const setWindowWidth = useDispatch<Dispatch>().pageData.setWindowWidth; const updateActivationItem = useDispatch<Dispatch>().activationItem.updateActivationItem; const removeActivationItem = useDispatch<Dispatch>().activationItem.removeActivationItem; const setRunningTimes = useDispatch<Dispatch>().runningTimes.setRunningTimes; const ref = useRef(null); const pageData = useSelector((state: RootState) => state.pageData); const [, setLocalPageData] = useLocalStorage('pageData', null); const [showDrawer, setShowDrawer] = useState(false); const [showPageDrawer, setShowPageDrawer] = useState(false); const [isCreate, setIsCreate] = useState(true); const [showTemplateModal, setShowTemplateModal] = useState(false); const [hideIframe, sethideIframe] = useState(true); // 创建postmessage通信 usePostMessage收集数据 redux 更新数据 const sendMessage = usePostMessage(({ tag, value }) => { switch (tag) { case 'setIsEditing': setIsEditing(value); break; case 'updateAppData': updateAppData(value); // 同步更新被选模块的属性 if (activationItem.moduleId === undefined) return; const asynAcactivationItem = (value as AppDataListTypes).find( (item) => item.moduleId === activationItem.moduleId, ); if (asynAcactivationItem?.moduleId) { updateActivationItem(asynAcactivationItem); } break; case 'updateRunningTimes': setRunningTimes(value); break; case 'updatePage': updatePageData(value); break; case 'id': // 设置当前项正在被编辑 // 禁止重复设置当前编辑项 if (activationItem.moduleId === value) return; for (let index = 0; index < appData.length; index++) { const element = appData[index]; if (element.moduleId === value) { updateActivationItem({ ...element }); break; } } setShowDashboard(true); break; default: break; } }); // 收发处理,子窗口onload时向子窗口发送信息, 通知当前正处于编辑模式下, const win: Window | null = ref.current ? (ref.current as any).contentWindow : null; useEffect(() => { const windows = (document.getElementById('wrapiframe') as any) ?.contentWindow; if (windows && !isCreate) { windows.onload = () => { sendMessage({ tag: 'setIsEditing', value: true }, windows); setIsEditing(true); sethideIframe(false); }; } }, [sendMessage, setIsEditing, isCreate]); useEffect(() => { sendMessage({ tag: 'setIsEditing', value: true }, win); setIsEditing(true); }, [sendMessage, setIsEditing, win]); const toggleEdit = useCallback(() => { const states = !isEditing; sendMessage({ tag: 'setIsEditing', value: states }, win); setIsEditing(states); }, [isEditing, sendMessage, setIsEditing, win]); const toggleCreate = useCallback(() => { setIsCreate(!isCreate); }, [isCreate]); // 收发处理,编辑完数据后通过sendMessage向子窗口发送最新数据。 useEffect(() => { sendMessage( { tag: 'updateAppData', value: appData, }, win, ); }, [sendMessage, win, appData]); const onChangeRule = ( width: number, height: number = window.innerHeight - 140, ) => { setWindowWidth(width); setWindowHeight(height); const optPageData = { ...pageData }; optPageData.windowWidth = width; optPageData.windowHeight = height; setLocalPageData(optPageData); if (win) { sendMessage({ tag: 'updatePage', value: true }, win); sendMessage({ tag: 'setIsEditing', value: isEditing }, win); } setIsEditing(true); forceUpdateByStateTag(); }; const [showDashboard, setShowDashboard] = useState(false); const [opacity, setOpacity] = useState('1'); // 无激活模块时隐藏设置面板 useEffect(() => { if (!activationItem.moduleId) { setShowDashboard(false); } }, [activationItem]); const hideDashboard = useCallback(() => { setShowDashboard(false); removeActivationItem(); if (win) { sendMessage({ tag: 'removeActivationItem', value: undefined }, win); } }, [removeActivationItem, sendMessage, win]); // const saveProjects = useCallback( // async (data: Template) => { // const id: number = await createTemplate(data); // if (id) { // const copyPageData = cloneDeep(pageData); // copyPageData.template = {...copyPageData.template || {}, id}; // return updatePageData(copyPageData) // } // }, // [pageData, updatePageData], // ) const updateProject = useCallback( (data: Template) => { data.id = pageData.template?.id; return updateTemplate(data); }, [pageData.template?.id], ); interface TemplateAll extends Template { pageData: string; appData: string; } // 保存或更新项目 const onSaveProject = useCallback( async ({ cove = [], terminal, isPublic, describe, tag, title, id, }: TemplateInfo) => { if (!auth?.isLogin) { history.push('/login'); return; } // copy const pageDataCopy = cloneDeep(pageData); // template数据 const templateData: Template = { title: title || pageData.pageTitle, terminal, cove: cove[0]?.thumbUrl, describe, tag: tag?.join(','), isPublic: isPublic === true ? 1 : 0, }; // 存入模板信息到pageData pageDataCopy.template = templateData || {}; // 完整数据 const params: TemplateAll = { pageData: JSON.stringify(pageData), appData: JSON.stringify(appData), id, userId: auth.session?.id, ...templateData, }; // 更新 if (!!pageData.template?.id) { await updateProject(params); } else { // 新增 const newId = await createTemplate(params); pageDataCopy.template.id = newId; } message.success('已发布'); // 更新 updatePageData(pageDataCopy); // 关闭弹窗 setShowTemplateModal(false); }, [ appData, auth?.isLogin, auth?.session?.id, history, pageData, updatePageData, updateProject, ], ); const showPublishModal = useCallback(() => { if (!auth?.isLogin) { history.push('/login'); } setShowTemplateModal(true); }, [auth?.isLogin, history]); return ( <> {isCreate ? ( <CreateProject goBack={() => toggleCreate()} /> ) : ( <div className={s.main}> {showDashboard && isEditing ? ( <Draggable axis="both" handle={`.${s.header}`} onDrag={() => setOpacity('0.5')} onStop={() => setOpacity('1')} > <div className={s.dashboard} style={{ opacity }}> <div className={s.header}> <h3>设置面板</h3> <CloseOutlined className={s.icon} onClick={hideDashboard} /> </div> <MiniDashboard /> </div> </Draggable> ) : null} <div className={s.topmenu}> <div className={s.create}> <Button type="primary" onClick={toggleCreate} icon={<FileAddOutlined />} /> &nbsp; {!isEditing ? ( <Button type="default" className={s.toggle} onClick={toggleEdit} icon={<EditOutlined />} /> ) : null} {isEditing ? ( <Button type="default" className={s.toggle} onClick={toggleEdit} icon={<EyeOutlined />} /> ) : null} &nbsp; <Button type="default" icon={<SettingOutlined />} onClick={() => setShowPageDrawer(true)} > 页面 </Button> &nbsp; <Button type="default" icon={<PlusOutlined />} onClick={() => setShowDrawer(true)} > 组件 </Button> {process.env.REACT_APP_DEMO === 'true' ? ( <> &nbsp; <a href="https://github.com/eightfeet/yugong"> <Button type="default" icon={<GithubOutlined />}> github </Button> </a> </> ) : null} </div> <div className={s.save}> <Button type="primary" icon={<UploadOutlined />} onClick={showPublishModal} > {pageData.template?.id ? '修改' : '发布'} </Button> </div> </div> <Ruler onChange={onChangeRule} /> <Drawer className={s.drawer} title="页面设置" width={580} onClose={() => setShowPageDrawer(false)} visible={showPageDrawer} bodyStyle={{ padding: '0', overflow: 'auto' }} maskStyle={{ backgroundColor: 'transparent' }} footer={null} > {showPageDrawer ? <PageSetting /> : null} </Drawer> <Drawer className={s.drawer} title="组件库" width={580} onClose={() => setShowDrawer(false)} visible={showDrawer} bodyStyle={{ padding: '0px' }} maskStyle={{ backgroundColor: 'transparent' }} footer={null} > <Repository /> </Drawer> <div className={s.box}> <div className={classNames({ [s.viewbg]: !isEditing, })} style={{ transition: 'all 0.5s' }} /> {!stateTag ? ( <div className={s.iframebox} style={{ width: pageData.windowWidth === -1 ? `100%` : `${pageData.windowWidth}px`, height: `${pageData.windowHeight}px`, }} > <LoadingAnimate /> <iframe ref={ref} id="wrapiframe" title="wrapiframe" src={`${process.env.REACT_APP_PUBLIC_PATH}${ window.location.search || '' }`} style={{ border: 'none', opacity: hideIframe ? 0 : 1, minWidth: '100%', minHeight: `${pageData.windowHeight}px`, }} /> </div> ) : null} </div> </div> )} <TemplateInfoModal visible={showTemplateModal} onOk={onSaveProject} onCancel={() => setShowTemplateModal(false)} /> </> ); }; export default Responsive;
the_stack
import React, { Component } from 'react' import { StyleSheet, Text, View, Image, Dimensions, TouchableNativeFeedback, InteractionManager, ActivityIndicator, StatusBar, Animated, Easing, FlatList, Linking } from 'react-native' import { updown, fav } from '../../dao/sync' import Ionicons from 'react-native-vector-icons/Ionicons' import { standardColor, idColor, accentColor } from '../../constant/colorConfig' import { getQaTopicAPI } from '../../dao' import ComplexComment from '../../component/ComplexComment' let screen = Dimensions.get('window') declare var global let config = { tension: 30, friction: 7, ease: Easing.in(Easing.ease(1, 0, 1, 1)), duration: 200 } /* tslint:disable */ let toolbarActions = [ { title: '回复', iconName: 'md-create', iconSize: 22, show: 'always', onPress: function () { const { params } = this.props.navigation.state if (this.isReplyShowing === true) return const cb = () => { this.props.navigation.navigate('Reply', { type: params.type, id: params.rowData ? params.rowData.id : this.state.data && this.state.data.titleInfo && this.state.data.titleInfo.psnid, callback: this.preFetch, shouldSeeBackground: true }) } if (this.state.openVal._value === 1) { this._animateToolbar(0, cb) } else if (this.state.openVal._value === 0) { cb() } } }, { title: '刷新', iconName: 'md-refresh', show: 'never', onPress: function () { this.preFetch() } }, { title: '在浏览器中打开', iconName: 'md-refresh', show: 'never', onPress: function () { const { params = {} } = this.props.navigation.state Linking.openURL(params.URL).catch(err => global.toast(err.toString())) } }, { title: '收藏', iconName: 'md-star-half', show: 'never', onPress: function () { const { params } = this.props.navigation.state // console.log(params) fav({ type: 'qa', param: params.rowData && params.rowData.id }).then(res => res.text()).then(text => { if (text) return global.toast(text) global.toast('操作成功') }).catch(err => { const msg = `操作失败: ${err.toString()}` global.toast(msg) }) } }, { title: '顶', iconName: 'md-star-half', show: 'never', onPress: function () { const { params } = this.props.navigation.state updown({ type: 'qa', param: params.rowData && params.rowData.id, updown: 'up' }).then(res => res.text()).then(text => { if (text) return global.toast(text) global.toast('操作成功') }).catch(err => { const msg = `操作失败: ${err.toString()}` global.toast(msg) }) } }, { title: '分享', iconName: 'md-share-alt', show: 'never', onPress: function () { try { const { params } = this.props.navigation.state global.Share.open({ url: params.URL, message: '[PSNINE] ' + this.state.data.titleInfo.title, title: 'PSNINE' }).catch((err) => { err && console.log(err) }) url && Linking.openURL(url).catch(err => global.toast(err.toString())) || global.toast('暂无出处') } catch (err) { } } }, { title: '出处', iconName: 'md-share-alt', show: 'never', onPress: function () { try { const url = this.state.data.titleInfo.shareInfo.source url && Linking.openURL(url).catch(err => global.toast(err.toString())) || global.toast('暂无出处') } catch (err) { } } } ] /* tslint:enable */ class QaTopic extends Component<any, any> { constructor(props) { super(props) this.state = { data: false, isLoading: true, mainContent: false, rotation: new Animated.Value(1), scale: new Animated.Value(1), opacity: new Animated.Value(1), openVal: new Animated.Value(0), modalVisible: false, modalOpenVal: new Animated.Value(0), topicMarginTop: new Animated.Value(0) } } _onActionSelected = (index) => { const { params } = this.props.navigation.state switch (index) { case 0: if (this.isReplyShowing === true) return const cb = () => { this.props.navigation.navigate('Reply', { type: params.type, id: params.rowData.id, callback: () => this.preFetch(), shouldSeeBackground: true }) } if (this.state.openVal._value === 1) { this._animateToolbar(0, cb) } else if (this.state.openVal._value === 0) { cb() } return default: return } } componentWillMount() { this.preFetch() } hasGame = false hasComment = false preFetch = () => { this.setState({ isLoading: true }) const { params } = this.props.navigation.state InteractionManager.runAfterInteractions(() => { getQaTopicAPI(params.URL).then(data => { const content = data.contentInfo.html this.hasGame = !!data.gameInfo.url this.hasComment = data.commentList.length !== 0 this.hasContent = content !== '<div></div>' this.setState({ data, mainContent: data.contentInfo.html, commentList: data.commentList, isLoading: false }) }) }) } handleImageOnclick = (url) => this.props.navigation.navigate('ImageViewer', { images: [ { url } ] }) renderHeader = (titleInfo) => { const { modeInfo } = this.props.screenProps const { params } = this.props.navigation.state const textStyle: any = { flex: -1, color: modeInfo.standardTextColor, textAlign: 'center', textAlignVertical: 'center' } return ['battle'].includes(params.type) ? undefined : ( <View key={'header'} style={{ flex: 1, backgroundColor: modeInfo.backgroundColor, elevation: 1, margin: 5, marginBottom: 0, marginTop: 0 }}> <TouchableNativeFeedback useForeground={true} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} > <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', padding: 5 }}> <Image source={{ uri: titleInfo.avatar.replace('@50w.png', '@75w.png') }} style={{ width: 50, height: 50 }} /> <View style={{ flex: 1, flexDirection: 'column', padding: 5 }}> <global.HTMLView value={titleInfo.title} modeInfo={modeInfo} stylesheet={styles} shouldForceInline={true} onImageLongPress={this.handleImageOnclick} imagePaddingOffset={30 + 50 + 10} /> <View style={{ flex: 1.1, flexDirection: 'row', justifyContent: 'space-between' }}> <Text selectable={false} style={{ flex: -1, color: modeInfo.standardColor, textAlign: 'center', textAlignVertical: 'center' }} onPress={ () => { this.props.navigation.navigate('Home', { title: titleInfo.psnid, id: titleInfo.psnid, URL: `https://psnine.com/psnid/${titleInfo.psnid}` }) } }>{titleInfo.psnid}</Text> <Text selectable={false} style={textStyle}>{titleInfo.date}</Text> </View> </View> </View> </TouchableNativeFeedback> </View> ) } hasContent = false renderContent = (html) => { const { modeInfo } = this.props.screenProps return ( <View key={'content'} style={{ elevation: 1, margin: 5, marginTop: 0, backgroundColor: modeInfo.backgroundColor, padding: 10 }}> <global.HTMLView value={html} modeInfo={modeInfo} shouldShowLoadingIndicator={true} stylesheet={styles} imagePaddingOffset={30} onImageLongPress={this.handleImageOnclick} /> </View> ) } hasGameGame = false renderGame = (rowData) => { const { modeInfo } = this.props.screenProps return ( <View style={{ backgroundColor: modeInfo.backgroundColor, elevation: 1, margin: 5, marginTop: 0 }}> <TouchableNativeFeedback onPress={() => { const { navigation } = this.props navigation.navigate('GamePage', { // URL: 'https://psnine.com/psngame/5424?psnid=Smallpath', URL: rowData.url, title: rowData.title, rowData, type: 'game' }) }} useForeground={true} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} > <View pointerEvents='box-only' style={{ flex: 1, flexDirection: 'row', padding: 12 }}> <Image source={{ uri: rowData.avatar }} style={[styles.avatar, { width: 91 }]} /> <View style={{ marginLeft: 10, flex: 1, flexDirection: 'column' }}> <Text ellipsizeMode={'tail'} numberOfLines={3} style={{ flex: 2.5, color: modeInfo.titleTextColor }}> {rowData.title} </Text> <View style={{ flex: 1.1, flexDirection: 'row', justifyContent: 'space-between' }}> <Text selectable={false} style={{ flex: -1, color: modeInfo.standardTextColor, textAlign: 'center', textAlignVertical: 'center' }}>{rowData.platform.join(' ')}</Text> </View> </View> </View> </TouchableNativeFeedback> </View> ) } renderComment = (commentList) => { const { modeInfo } = this.props.screenProps const { navigation } = this.props const list: any[] = [] for (const rowData of commentList) { list.push( <ComplexComment key={rowData.id || list.length} {...{ navigation, rowData, modeInfo, onLongPress: () => { }, preFetch: this.preFetch, index: list.length }} /> ) } const shouldMarginTop = !this.hasComment return ( <View style={{ marginTop: shouldMarginTop ? 5 : 0 }}> <View style={{ elevation: 1, margin: 5, marginTop: 0, backgroundColor: modeInfo.backgroundColor }}> {list} </View> </View> ) } isReplyShowing = false _readMore = (URL) => { this.props.navigation.navigate('CommentList', { URL }) } viewTopIndex = 0 viewBottomIndex = 0 render() { const { params } = this.props.navigation.state // console.log('QaTopic.js rendered'); const { modeInfo } = this.props.screenProps const { data: source } = this.state const data: any[] = [] const renderFuncArr: any[] = [] const shouldPushData = !this.state.isLoading if (shouldPushData) { data.push(source.titleInfo) renderFuncArr.push(this.renderHeader) } if (shouldPushData && this.hasGame) { data.push(source.gameInfo) renderFuncArr.push(this.renderGame) } if (shouldPushData && this.hasContent) { data.push(source.contentInfo.html) renderFuncArr.push(this.renderContent) } if (shouldPushData && this.hasComment) { data.push(this.state.commentList) renderFuncArr.push(this.renderComment) } this.viewBottomIndex = Math.max(data.length - 1, 0) const targetActions = toolbarActions.slice() try { if (this.state.data && this.state.data.titleInfo && this.state.data.titleInfo.shareInfo && this.state.data.titleInfo.shareInfo.source) { // } else { targetActions.pop() } } catch (err) { } if (shouldPushData && this.state.data.titleInfo && this.state.data.titleInfo.shareInfo && this.state.data.titleInfo.shareInfo.edit) { targetActions.push( { title: '编辑', iconName: 'md-create', iconSize: 22, show: 'never', onPress: function () { const { navigation } = this.props navigation.navigate('NewGene', { URL: this.state.data.titleInfo.shareInfo.edit }) } } ) } return ( <View style={{ flex: 1, backgroundColor: modeInfo.backgroundColor }} onStartShouldSetResponder={() => false} onMoveShouldSetResponder={() => false} > <Ionicons.ToolbarAndroid navIconName='md-arrow-back' overflowIconName='md-more' iconColor={modeInfo.isNightMode ? '#000' : '#fff'} title={params.title ? params.title : `No.${params.rowData.id}`} titleColor={modeInfo.isNightMode ? '#000' : '#fff'} style={[styles.toolbar, { backgroundColor: modeInfo.standardColor }]} actions={targetActions} onIconClicked={() => { this.props.navigation.goBack() }} onActionSelected={(index) => { targetActions[index].onPress.bind(this)() }} /> {this.state.isLoading && ( <ActivityIndicator animating={this.state.isLoading} style={{ flex: 999, justifyContent: 'center', alignItems: 'center' }} color={modeInfo.accentColor} size={50} /> )} {!this.state.isLoading && <FlatList style={{ flex: -1, backgroundColor: modeInfo.standardColor }} ref={flatlist => this.flatlist = flatlist} data={data} keyExtractor={(item, index) => item.id || index} renderItem={({ item, index }) => { return renderFuncArr[index](item) }} extraData={this.state} windowSize={999} disableVirtualization={true} viewabilityConfig={{ minimumViewTime: 3000, viewAreaCoveragePercentThreshold: 100, waitForInteraction: true }} > </FlatList> } </View> ) } renderToolbarItem = (props, index, maxLength) => { const { modeInfo } = this.props.screenProps return ( <Animated.View ref={float => this[`float${index}`] = float} collapsable={false} key={index} style={{ width: 40, height: 40, borderRadius: 20, backgroundColor: modeInfo.accentColor, position: 'absolute', bottom: props.openVal.interpolate({ inputRange: [0, 1], outputRange: [24, 56 + 10 + 16 * 2 + index * 50] }), right: 24, elevation: 1, zIndex: 1, opacity: 1 }}> <TouchableNativeFeedback onPress={() => this.pressToolbar(maxLength - index - 1)} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} onPressIn={() => { this.float1.setNativeProps({ style: { elevation: 12 } }) }} onPressOut={() => { this.float1.setNativeProps({ style: { elevation: 6 } }) }} style={{ width: 40, height: 40, borderRadius: 20, flex: 1, zIndex: 1, backgroundColor: accentColor }}> <View style={{ borderRadius: 20, width: 40, height: 40, justifyContent: 'center', alignItems: 'center' }}> <Ionicons name={props.iconName} size={20} color='#fff' /> </View> </TouchableNativeFeedback> </Animated.View> ) } index = 0 flatlist: any = false float1: any = false pressToolbar = index => { const target = index === 0 ? this.viewTopIndex : this.viewBottomIndex this.flatlist && this.flatlist.scrollToIndex({ animated: true, viewPosition: 0, index: target }) } _animateToolbar = (value, cb) => { const ratationPreValue = this.state.rotation._value const rotationValue = value === 0 ? 0 : ratationPreValue + 3 / 8 const scaleAnimation = Animated.timing(this.state.rotation, { toValue: rotationValue, ...config }) const moveAnimation = Animated.timing(this.state.openVal, { toValue: value, ...config }) const target = [ moveAnimation ] if (value !== 0 || value !== 1) target.unshift(scaleAnimation) const type = value === 1 ? 'sequence' : 'parallel' Animated[type](target).start() setTimeout(() => { typeof cb === 'function' && cb() }, 200) } pressNew = (cb) => { if (this.state.openVal._value === 0) { this._animateToolbar(1, cb) } else { this._animateToolbar(0, cb) } } } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', backgroundColor: '#F5FCFF' }, toolbar: { backgroundColor: standardColor, height: 56, elevation: 4 }, selectedTitle: { // backgroundColor: '#00ffff' // fontSize: 20 }, avatar: { width: 50, height: 50 }, a: { fontWeight: '300', color: idColor // make links coloured pink } }) export default QaTopic
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type SellerReplyEstimate_Test_QueryVariables = {}; export type SellerReplyEstimate_Test_QueryResponse = { readonly me: { readonly conversation: { readonly orderConnection: { readonly edges: ReadonlyArray<{ readonly node: { readonly " $fragmentRefs": FragmentRefs<"SellerReplyEstimate_order">; } | null; } | null> | null; } | null; } | null; } | null; }; export type SellerReplyEstimate_Test_Query = { readonly response: SellerReplyEstimate_Test_QueryResponse; readonly variables: SellerReplyEstimate_Test_QueryVariables; }; /* query SellerReplyEstimate_Test_Query { me { conversation(id: "test-id") { orderConnection(first: 10) { edges { node { __typename ...SellerReplyEstimate_order id } } } id } id } } fragment SellerReplyEstimate_order on CommerceOrder { __isCommerceOrder: __typename displayState stateExpiresAt(format: "MMM D") requestedFulfillment { __typename } ... on CommerceOfferOrder { buyerAction } lineItems { edges { node { selectedShippingQuote { displayName id } id } } } } */ const node: ConcreteRequest = (function(){ var v0 = [ { "kind": "Literal", "name": "id", "value": "test-id" } ], v1 = [ { "kind": "Literal", "name": "first", "value": 10 } ], v2 = { "alias": null, "args": null, "kind": "ScalarField", "name": "__typename", "storageKey": null }, v3 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }; return { "fragment": { "argumentDefinitions": [], "kind": "Fragment", "metadata": null, "name": "SellerReplyEstimate_Test_Query", "selections": [ { "alias": null, "args": null, "concreteType": "Me", "kind": "LinkedField", "name": "me", "plural": false, "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": "Conversation", "kind": "LinkedField", "name": "conversation", "plural": false, "selections": [ { "alias": null, "args": (v1/*: any*/), "concreteType": "CommerceOrderConnectionWithTotalCount", "kind": "LinkedField", "name": "orderConnection", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceOrderEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": null, "kind": "LinkedField", "name": "node", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "SellerReplyEstimate_order" } ], "storageKey": null } ], "storageKey": null } ], "storageKey": "orderConnection(first:10)" } ], "storageKey": "conversation(id:\"test-id\")" } ], "storageKey": null } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": [], "kind": "Operation", "name": "SellerReplyEstimate_Test_Query", "selections": [ { "alias": null, "args": null, "concreteType": "Me", "kind": "LinkedField", "name": "me", "plural": false, "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": "Conversation", "kind": "LinkedField", "name": "conversation", "plural": false, "selections": [ { "alias": null, "args": (v1/*: any*/), "concreteType": "CommerceOrderConnectionWithTotalCount", "kind": "LinkedField", "name": "orderConnection", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceOrderEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": null, "kind": "LinkedField", "name": "node", "plural": false, "selections": [ (v2/*: any*/), { "kind": "TypeDiscriminator", "abstractKey": "__isCommerceOrder" }, { "alias": null, "args": null, "kind": "ScalarField", "name": "displayState", "storageKey": null }, { "alias": null, "args": [ { "kind": "Literal", "name": "format", "value": "MMM D" } ], "kind": "ScalarField", "name": "stateExpiresAt", "storageKey": "stateExpiresAt(format:\"MMM D\")" }, { "alias": null, "args": null, "concreteType": null, "kind": "LinkedField", "name": "requestedFulfillment", "plural": false, "selections": [ (v2/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "CommerceLineItemConnection", "kind": "LinkedField", "name": "lineItems", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceLineItemEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceLineItem", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceShippingQuote", "kind": "LinkedField", "name": "selectedShippingQuote", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "displayName", "storageKey": null }, (v3/*: any*/) ], "storageKey": null }, (v3/*: any*/) ], "storageKey": null } ], "storageKey": null } ], "storageKey": null }, (v3/*: any*/), { "kind": "InlineFragment", "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "buyerAction", "storageKey": null } ], "type": "CommerceOfferOrder", "abstractKey": null } ], "storageKey": null } ], "storageKey": null } ], "storageKey": "orderConnection(first:10)" }, (v3/*: any*/) ], "storageKey": "conversation(id:\"test-id\")" }, (v3/*: any*/) ], "storageKey": null } ] }, "params": { "id": "3f0fa0b78930ff11249815649455b511", "metadata": {}, "name": "SellerReplyEstimate_Test_Query", "operationKind": "query", "text": null } }; })(); (node as any).hash = 'b370a648d14d05afb0307bc971722dc3'; export default node;
the_stack
import * as Electron from 'electron'; import * as Types from '@meetalva/types'; import * as M from '@meetalva/message'; import * as Matchers from '../../matchers'; import { MessageType as MT } from '@meetalva/message'; import * as ContextMenu from '../../context-menu'; import { ElectronUpdater } from './electron-updater'; import { ElectronMainMenu } from './electron-main-menu'; import { AlvaApp, Project } from '@meetalva/model'; import * as Serde from '../../sender/serde'; import * as uuid from 'uuid'; import * as Url from 'url'; import { HostWindowVariant } from '@meetalva/types'; import * as Mobx from 'mobx'; import * as RouteParser from 'route-parser'; import * as Model from '@meetalva/model'; const throat = require('throat'); export interface ElectronAdapterInit { server: Types.AlvaServer<Model.AlvaApp<M.Message>, Model.Project, M.Message>; forceUpdates: boolean; } export class ElectronAdapter { private server: Types.AlvaServer<Model.AlvaApp<M.Message>, Model.Project, M.Message>; private menu: ElectronMainMenu; private updater: ElectronUpdater; private get windows(): Set<Electron.BrowserWindow> { return new Set(Electron.BrowserWindow.getAllWindows()); } public constructor({ server, forceUpdates }: ElectronAdapterInit) { this.server = server; this.menu = new ElectronMainMenu({ server }); this.updater = new ElectronUpdater({ server, force: forceUpdates }); } public async start(opts?: { filePath?: string }): Promise<void> { const server = this.server; const sender = this.server.sender; const host = this.server.host; const dataHost = this.server.dataHost; const context = { dataHost, host, location: server.location }; Electron.app.on('window-all-closed', () => { if (process.platform !== 'darwin') { Electron.app.quit(); } }); Electron.app.on('activate', async () => { if (process.platform === 'darwin' && this.windows.size === 0) { await host.createWindow({ address: server.location.origin, variant: HostWindowVariant.Splashscreen }); } }); Electron.app.on('open-file', async (e, path) => { e.preventDefault(); const projectWindows = await this.getProjectWindows(); const projectWindow = projectWindows.find(({ project }) => project.getPath() === path); if (projectWindow) { projectWindow.window.show(); projectWindow.window.focus(); } else { this.server.sender.send({ type: MT.OpenFileRequest, id: uuid.v4(), payload: { path, replace: false } }); } }); sender.match<M.ConnectNpmPatternLibraryRequest>( MT.ConnectNpmPatternLibraryRequest, Matchers.connectNpmPatternLibrary(context) ); sender.match<M.ConnectPatternLibraryRequest>( MT.ConnectPatternLibraryRequest, Matchers.connectPatternLibrary(context) ); sender.match<M.UpdatePatternLibraryRequest>( MT.UpdatePatternLibraryRequest, Matchers.updatePatternLibrary(context) ); sender.match<M.UpdateNpmPatternLibraryRequest>( MT.UpdateNpmPatternLibraryRequest, Matchers.updateNpmPatternLibrary(context) ); sender.match<M.Copy>(MT.Copy, Matchers.copy(context)); sender.match<M.Cut>(MT.Cut, Matchers.cut(context)); sender.match<M.CreateNewFileRequest>( MT.CreateNewFileRequest, Matchers.createNewFileRequest(context) ); sender.match<M.ExportHtmlProject>(MT.ExportHtmlProject, Matchers.exportHtmlProject(context)); sender.match<M.OpenExternalURL>(MT.OpenExternalURL, Matchers.openExternalUrl(context)); sender.match<M.OpenFileRequest>( MT.OpenFileRequest, Matchers.openFileRequest(context, async (path: string) => { const projectWindow = await this.getProjectWindowByPath(path); if (projectWindow) { projectWindow.window.show(); projectWindow.window.focus(); return true; } return false; }) ); sender.match<M.OpenRemoteFileRequest>( MT.OpenRemoteFileRequest, Matchers.openRemoteFileRequest(context) ); sender.match<M.OpenWindow>(MT.OpenWindow, Matchers.openWindow(context)); sender.match<M.Paste>(MT.Paste, Matchers.paste(context)); sender.match<M.Save>(MT.Save, Matchers.save(context, { passive: false })); sender.match<M.SaveAs>(MT.SaveAs, Matchers.saveAs(context, { passive: false })); sender.match<M.ShowError>(MT.ShowError, Matchers.showError(context)); sender.match<M.ShowMessage>(MT.ShowMessage, Matchers.showMessage(context)); sender.match<M.UseFileRequest>(MT.UseFileRequest, Matchers.useFileRequest(context)); sender.match<M.ContextMenuRequest>(MT.ContextMenuRequest, Matchers.showContextMenu(context)); sender.match<M.ChangeApp>(MT.ChangeApp, Matchers.addApp(context)); sender.match<M.AssetReadRequest>(MT.AssetReadRequest, Matchers.openAsset(context)); sender.match<M.ShowUpdateDetails>(MT.ShowUpdateDetails, Matchers.showUpdateDetails(context)); server.sender.match<M.CheckForUpdatesRequest>( M.MessageType.CheckForUpdatesRequest, throat(1, async () => { const check = await this.updater.check({ eager: false }); if (check.status === Types.UpdateCheckStatus.Available) { const result = await this.updater.download(); if (result.status === 'error') { host.log( `Error while downloading update ${check.info.version}: ${result.error.message}` ); host.log(result.error); return; } this.server.sender.send({ id: uuid.v4(), type: M.MessageType.UpdateDownloaded, payload: check.info }); } }) ); server.sender.match<M.UpdateDownloaded>(M.MessageType.UpdateDownloaded, async m => { await dataHost.setUpdate(m.payload); }); server.sender.match<M.InstallUpdate>(M.MessageType.InstallUpdate, async m => { await dataHost.removeUpdate(); this.updater.install(); }); server.sender.match<M.ToggleDevTools>(M.MessageType.ToggleDevTools, async () => { await host.toggleDevTools(); }); server.sender.match<M.ContextMenuRequest>(M.MessageType.ContextMenuRequest, async m => { if (m.payload.menu === Types.ContextMenuType.ElementMenu) { const project = await server.dataHost.getProject(m.payload.projectId); if (!project) { return; } const element = project.getElementById(m.payload.data.element.id); if (!element) { return; } const app = await this.getApp(); if (!app) { return; } await host.showContextMenu({ position: m.payload.position, items: ContextMenu.elementContextMenu({ app, project, element }) }); } }); server.sender.match<M.Undo>(M.MessageType.Undo, async () => { const app = await this.getApp(); if (app && app.getHasFocusedInput()) { Electron.Menu.sendActionToFirstResponder('undo:'); } }); server.sender.match<M.Redo>(M.MessageType.Redo, async () => { const app = await this.getApp(); if (app && app.getHasFocusedInput()) { Electron.Menu.sendActionToFirstResponder('redo:'); } }); server.sender.match<M.Cut>(M.MessageType.Cut, async () => { const app = await this.getApp(); if (app && app.getHasFocusedInput()) { Electron.Menu.sendActionToFirstResponder('cut:'); } }); server.sender.match<M.Copy>(M.MessageType.Copy, async () => { const app = await this.getApp(); if (app && app.getHasFocusedInput()) { Electron.Menu.sendActionToFirstResponder('copy:'); } }); server.sender.match<M.Paste>(M.MessageType.Paste, async m => { const app = await host.getApp(m.appId || ''); if (!app) { host.log(`paste: received message without resolveable app: ${m}`); return; } const contents = await host.readClipboard(); if (!contents) { host.log(`paste: no contents`); return; } const message = Serde.deserialize(contents); // Trigger the default behaviour if the clipboard // has no Alva message and an input is focused if (!message && app.getHasFocusedInput()) { host.log(`paste: redirecting to input`); Electron.Menu.sendActionToFirstResponder('paste:'); return; } if (!message || message.type !== M.MessageType.Clipboard) { host.log(`paste: clipboard message is no clipboard message`); return; } }); server.sender.match<M.DeleteSelected>(M.MessageType.DeleteSelected, async () => { const app = await this.getApp(); if (app && app.getHasFocusedInput()) { Electron.Menu.sendActionToFirstResponder('delete:'); } }); const useFileResponse = Matchers.useFileResponse(context); server.sender.match<M.UseFileResponse>(MT.UseFileResponse, async m => { if ( this.windows.size > 0 || m.payload.project.status === Types.ProjectPayloadStatus.Error || !m.payload.replace ) { return useFileResponse(m); } const project = Project.from((m.payload.project as Types.ProjectPayloadSuccess).contents); await host.createWindow({ address: `${server.location.origin}/project/${project.getId()}`, variant: HostWindowVariant.Normal }); }); server.sender.match<M.Maximize>(MT.Maximize, async m => { const win = await this.getAppWindow(m.appId || uuid.v4()); if (win) { win.maximize(); } }); server.sender.match<M.SaveResult>(MT.SaveResult, () => this.server.dataHost.checkProjects()); server.sender.match<M.UseFileResponse>(MT.UseFileResponse, () => this.server.dataHost.checkProjects() ); Mobx.autorun(async () => { server.sender.send({ type: MT.ProjectRecordsChanged, id: uuid.v4(), payload: { projects: await this.server.dataHost.getProjects() } }); }); // Open the splash screen when starting without file if (!opts || !opts.filePath) { await host.createWindow({ address: server.location.origin, variant: HostWindowVariant.Splashscreen }); } else { this.server.sender.send({ type: MT.OpenFileRequest, id: uuid.v4(), payload: { path: opts.filePath, replace: false } }); } this.menu.start(); this.updater.start(); } private async getApp(): Promise<AlvaApp<M.Message> | undefined> { return this.menu.getApp(); } private async getAppWindows(): Promise<Map<string, Electron.BrowserWindow>> { return new Map( Electron.BrowserWindow.getAllWindows() .map(win => { const parsed = Url.parse(win.webContents.getURL()); if (!parsed.hash) { return; } return [parsed.hash.slice(1), win]; }) .filter((win): win is [string, Electron.BrowserWindow] => typeof win !== 'undefined') ); } private async getAppWindow(appId: string): Promise<Electron.BrowserWindow | undefined> { return (await this.getAppWindows()).get(appId); } private async getProjectWindows(): Promise< { project: Project; window: Electron.BrowserWindow }[] > { const projectRoute = new RouteParser('/project/:id(/store)'); return (await Promise.all( Array.from((await this.getAppWindows()).values()).map(async win => { const parsed = Url.parse(win.webContents.getURL()); const match = projectRoute.match(parsed.pathname || ''); if (!match || !match.id) { return; } return { window: win, project: await this.server.dataHost.getProject(match.id) }; }) )).filter( (item): item is { window: Electron.BrowserWindow; project: Project } => typeof item !== 'undefined' && typeof item.project !== 'undefined' ); } private async getProjectWindowByPath( path: string ): Promise<{ project: Project; window: Electron.BrowserWindow } | undefined> { return (await this.getProjectWindows()).find( projectWindow => projectWindow.project.getPath() === path ); } }
the_stack
import VideoTimeContainer from '../video-time-container'; import {useState, useRef} from 'react'; import VideoControlsContainer from '../video-controls-container'; import Preview from './preview'; const PlayBar = () => { const [resizing, setResizing] = useState(false); const [hoverTime, setHoverTime] = useState(0); const progress = useRef<HTMLProgressElement>(); const {play, pause} = VideoControlsContainer.useContainer(); const { currentTime, duration, startTime, endTime, updateTime, updateStartTime, updateEndTime } = VideoTimeContainer.useContainer(); const total = endTime - startTime; const current = currentTime - startTime; const getTimeFromEvent = event => { const cursorX = event.clientX; const {x, width} = progress.current.getBoundingClientRect(); const percent = (cursorX - x) / width; const time = startTime + ((endTime - startTime) * percent); return Math.max(0, time); }; const seek = event => { const time = getTimeFromEvent(event); if (startTime <= time && time <= endTime) { updateTime(time); } }; const updatePreview = event => { setHoverTime(getTimeFromEvent(event)); }; const startResizing = () => { setResizing(true); pause(); }; const stopResizing = () => { setResizing(false); play(); }; const setStartTime = event => { updateStartTime(Number.parseFloat(event.target.value)); }; const setEndTime = event => { updateEndTime(Number.parseFloat(event.target.value)); }; const previewTime = resizing ? currentTime : hoverTime; const previewLabelTime = resizing ? currentTime : (startTime <= hoverTime && hoverTime <= endTime ? hoverTime - startTime : hoverTime); const previewDuration = resizing ? total : (startTime <= hoverTime && hoverTime <= endTime ? total : undefined); return ( <div className="container" onMouseUp={seek} onMouseMove={updatePreview}> <div className="progress-bar-container"> <div className="progress-bar"> <progress ref={progress} max={total} value={current}/> <div className="preview"> <Preview time={previewTime} labelTime={previewLabelTime} duration={previewDuration} hidePreview={resizing}/> </div> <input type="range" className="slider start" value={startTime} min={0} max={duration} step={0.00001} onChange={setStartTime} onMouseDown={startResizing} onMouseUp={stopResizing}/> <input type="range" className="slider end" value={endTime} min={0} max={duration} step={0.00001} onChange={setEndTime} onMouseDown={startResizing} onMouseUp={stopResizing}/> </div> </div> <style jsx>{` .container { flex: 1; display: flex; align-items: center; z-index: 25; overflow: visible; height: 50%; } .progress-bar-container { position: absolute; width: 100%; display: flex; bottom: 30px; left: 50%; transform: translateX(-50%); width: 60%; transition: all 0.12s ease-in-out; } .progress-bar { width: 100%; height: 4px; display: flex; background: rgba(255, 255, 255, 0.2); border-radius: 4px; position: relative; } progress { position: absolute; top: 0; width: ${total * 100 / duration}%; left: ${startTime * 100 / duration}%; -webkit-appearance: none; height: 4px; border-radius: 4px; } progress::-webkit-progress-bar { background-color: rgba(255, 255, 255, 0.4); border-radius: 4px; } progress::-webkit-progress-value { border-radius: 4px; background-image: linear-gradient(90deg, #9300ff 0%, #5272e2 49%, #05e6b5 98%); box-shadow: inset 0 0 0 0.5px rgba(255, 255, 255, 0.1); } .slider { width: 100%; height: 4px; position: absolute; margin: 0; top: 0; -webkit-appearance: none; outline: none; background: transparent; pointer-events: none; } .slider::-ms-track { width: 100%; height: 0; border-color: transparent; color: transparent; background: transparent; pointer-events: none; z-index: -1; } .slider::-webkit-slider-thumb { width: 5px; height: 16px; background: #fff; border-radius: 2px; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1); transition: all 0.16s ease-in-out; -webkit-appearance: none; pointer-events: auto; z-index: 20; } .preview { position: absolute; left: ${hoverTime * 100 / duration}%; transform: translateX(-50%); bottom: 20px; width: 132px; height: 88px; display: none; } .container:hover .preview { display: flex; } `}</style> </div> ); }; export default PlayBar; // Import PropTypes from 'prop-types'; // import React from 'react'; // import classNames from 'classnames'; // import {connect, VideoContainer} from '../../../containers'; // import Preview from './preview'; // class PlayBar extends React.Component { // state = { // hoverTime: 0 // }; // progress = React.createRef(); // getTimeFromEvent = event => { // const {startTime, endTime} = this.props; // const cursorX = event.clientX; // const {x, width} = this.progress.current.getBoundingClientRect(); // const percent = (cursorX - x) / width; // const time = startTime + ((endTime - startTime) * percent); // return Math.max(0, time); // } // seek = event => { // const {startTime, endTime, seek} = this.props; // const time = this.getTimeFromEvent(event); // if (startTime <= time && time <= endTime) { // seek(time); // } // } // updatePreview = event => { // const time = this.getTimeFromEvent(event); // this.setState({hoverTime: time}); // } // startResizing = () => { // const {pause} = this.props; // this.setState({resizing: true}); // pause(); // } // stopResizing = () => { // const {play} = this.props; // this.setState({resizing: false}); // play(); // } // setStartTime = event => this.props.setStartTime(Number.parseFloat(event.target.value)) // setEndTime = event => this.props.setEndTime(Number.parseFloat(event.target.value)) // render() { // const {currentTime = 0, duration, startTime, endTime, hover, src} = this.props; // if (!src) { // return null; // } // const {hoverTime, resizing} = this.state; // const total = endTime - startTime; // const current = currentTime - startTime; // const previewTime = resizing ? currentTime : hoverTime; // const previewLabelTime = resizing ? currentTime : (startTime <= hoverTime && hoverTime <= endTime ? hoverTime - startTime : hoverTime); // const previewDuration = resizing ? total : (startTime <= hoverTime && hoverTime <= endTime ? total : undefined); // const className = classNames('progress-bar-container', {hover}); // return ( // <div className="container" onMouseUp={this.seek} onMouseMove={this.updatePreview}> // <div className={className}> // <div className="progress-bar"> // <progress ref={this.progress} max={total} value={current}/> // <div className="preview"> // <Preview src={src} time={previewTime} labelTime={previewLabelTime} duration={previewDuration} hidePreview={resizing}/> // </div> // <input // type="range" // className="slider start" // value={startTime} // min={0} // max={duration} // step={0.00001} // onChange={this.setStartTime} // onMouseDown={this.startResizing} // onMouseUp={this.stopResizing}/> // <input // type="range" // className="slider end" // value={endTime} // min={0} // max={duration} // step={0.00001} // onChange={this.setEndTime} // onMouseDown={this.startResizing} // onMouseUp={this.stopResizing}/> // </div> // </div> // <style jsx>{` // .container { // flex: 1; // display: flex; // align-items: center; // z-index: 25; // overflow: visible; // height: 50%; // } // .progress-bar-container { // position: absolute; // width: 100%; // display: flex; // bottom: 30px; // left: 50%; // transform: translateX(-50%); // width: 60%; // transition: all 0.12s ease-in-out; // } // .progress-bar-container:not(.hover) { // bottom: 64px; // width: 100% // } // .progress-bar-container:not(.hover) .progress-bar { // border-radius: 0; // } // .progress-bar { // width: 100%; // height: 4px; // display: flex; // background: rgba(255, 255, 255, 0.2); // border-radius: 4px; // position: relative; // } // progress { // position: absolute; // top: 0; // width: ${total * 100 / duration}%; // left: ${startTime * 100 / duration}%; // -webkit-appearance: none; // height: 4px; // border-radius: 4px; // } // progress::-webkit-progress-bar { // background-color: rgba(255, 255, 255, 0.4); // border-radius: 4px; // } // progress::-webkit-progress-value { // border-radius: 4px; // background-image: linear-gradient(90deg, #9300ff 0%, #5272e2 49%, #05e6b5 98%); // box-shadow: inset 0 0 0 0.5px rgba(255, 255, 255, 0.1); // } // .slider { // width: 100%; // height: 4px; // position: absolute; // margin: 0; // top: 0; // -webkit-appearance: none; // outline: none; // background: transparent; // pointer-events: none; // ${hover ? '' : 'display: none;'} // } // .slider::-ms-track { // width: 100%; // height: 0; // border-color: transparent; // color: transparent; // background: transparent; // pointer-events: none; // z-index: -1; // } // .slider::-webkit-slider-thumb { // width: 5px; // height: 16px; // background: #fff; // border-radius: 2px; // box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1); // transition: all 0.16s ease-in-out; // -webkit-appearance: none; // pointer-events: auto; // z-index: 20; // } // .preview { // position: absolute; // left: ${hoverTime * 100 / duration}%; // transform: translateX(-50%); // bottom: 20px; // width: 132px; // height: 88px; // display: none; // } // .container:hover .preview { // display: flex; // } // `}</style> // </div> // ); // } // } // PlayBar.propTypes = { // startTime: PropTypes.number, // endTime: PropTypes.number, // seek: PropTypes.elementType, // currentTime: PropTypes.number, // duration: PropTypes.number, // src: PropTypes.string, // setStartTime: PropTypes.elementType, // setEndTime: PropTypes.elementType, // pause: PropTypes.elementType, // play: PropTypes.elementType, // hover: PropTypes.bool // }; // export default connect( // [VideoContainer], // ({currentTime, duration, startTime, endTime, src}) => ({currentTime, duration, startTime, endTime, src}), // ({seek, setStartTime, setEndTime, pause, play}) => ({seek, setStartTime, setEndTime, pause, play}) // )(PlayBar);
the_stack
import { Component, OnInit, OnDestroy, ViewChild, trigger, state, style, transition, animate } from '@angular/core'; import { environment } from './../../../../../../environments/environment'; import { Router } from '@angular/router'; import { Subscription } from 'rxjs/Subscription'; import * as _ from 'lodash'; import { UtilsService } from '../../../../../shared/services/utils.service'; import { LoggerService } from '../../../../../shared/services/logger.service'; import { ErrorHandlingService } from '../../../../../shared/services/error-handling.service'; import 'rxjs/add/operator/filter'; import 'rxjs/add/operator/pairwise'; import { WorkflowService } from '../../../../../core/services/workflow.service'; import { RouterUtilityService } from '../../../../../shared/services/router-utility.service'; import { AdminService } from '../../../../services/all-admin.service'; import { SelectComponent } from 'ng2-select'; import { UploadFileService } from '../../../../services/upload-file-service'; @Component({ selector: 'app-admin-create-asset-groups', templateUrl: './create-asset-groups.component.html', styleUrls: ['./create-asset-groups.component.css'], animations: [ trigger('slideInOut', [ state('in', style({ transform: 'translate3d(0, 0, 0)' })), state('out', style({ transform: 'translate3d(100%, 0, 0)' })), transition('in => out', animate('400ms ease-in-out')), transition('out => in', animate('400ms ease-in-out')) ]), trigger('fadeInOut', [ state('open', style({ 'z-index': 2, opacity: 1 })), state('closed', style({ 'z-index': -1, opacity: 0 })), transition('open <=> closed', animate('500ms')), ]) ], providers: [ LoggerService, ErrorHandlingService, UploadFileService, AdminService ] }) export class CreateAssetGroupsComponent implements OnInit, OnDestroy { @ViewChild('attributeValueElement') attributeValueElement: SelectComponent; @ViewChild('targetType') targetTypeElement: SelectComponent; pageTitle = 'Create Asset Group'; breadcrumbArray = ['Admin', 'Asset Groups']; breadcrumbLinks = ['policies', 'asset-groups']; breadcrumbPresent; highlightedText; progressText; outerArr = []; filters = []; isGroupNameValid = -1; targetTypeValue = []; assetForm = { dataSourceName: 'aws', groupName: '', displayName: '', type: '', createdBy: '', description: '', visible: true, targetTypes: [] }; isCreate = false; highlightName = ''; groupName = ''; assetLoaderTitle = ''; assetLoader = false; assetLoaderFailure = false; attributeName = []; attributeValue; targetTypeSelectedValue = ''; selectedAttributes = []; allOptionalRuleParams = []; isAssetGroupFailed = false; isAssetGroupSuccess = false; ruleContentLoader = true; assetGroupLoader = false; invocationId = ''; paginatorSize = 25; isLastPage; assetGroupNames; isFirstPage; totalPages; pageNumber = 0; showLoader = true; showWidget = true; remainingTargetTypes; remainingTargetTypesFullDetails; targetTypeAttributeValues = []; errorMessage; searchTerm = ''; hideContent = false; pageContent = [ { title: 'Enter Group Details', hide: false, isChanged: false }, { title: 'Select Domains', hide: true, isChanged: false }, { title: 'Select Targets', hide: true, isChanged: false }, { title: 'Configure Attributes', hide: true, isChanged: false } ]; availChoosedItems = {}; availChoosedSelectedItems = {}; availChoosedItemsCount = 0; selectChoosedItems = {}; selectChoosedSelectedItems = {}; selectChoosedItemsCount = 0; availableItems = []; selectedItems = []; availableItemsBackUp = []; selectedItemsBackUp = []; availableItemsCopy = []; selectedItemsCopy = []; searchSelectedDomainTerms = ''; searchAvailableDomainTerms = ''; // Target Details // availTdChoosedItems = {}; availTdChoosedSelectedItems = {}; availTdChoosedItemsCount = 0; state = 'closed'; menuState = 'out'; selectedIndex = -1; selectedAttributeDetails= []; selectedAttributeIndex = ''; selectTdChoosedItems = {}; selectTdChoosedSelectedItems = {}; selectTdChoosedItemsCount = 0; availableTdItems = []; selectedTdItems = []; selectedTdItemsCopyForPrevNext = []; availableTdItemsBackUp = []; selectedTdItemsBackUp = []; availableTdItemsCopy = []; selectedTdItemsCopy = []; searchSelectedTargetTerms = ''; searchAvailableTargetTerms = ''; stepIndex = 0; stepTitle = this.pageContent[this.stepIndex].title; allAttributeDetails = []; allAttributeDetailsCopy = []; allAttributeDetailsCopyForPrevNext = []; allSelectedAttributeDetailsCopy = []; filterText = {}; errorValue = 0; urlID = ''; groupId = ''; successTitleStart = ''; successTitleEnd = ''; failedTitleStart = ''; isAttributeAlreadyAdded = -1; failedTitleEnd = ''; FullQueryParams; queryParamsWithoutFilter; urlToRedirect = ''; mandatory; public labels; private previousUrl = ''; private routeSubscription: Subscription; private getKeywords: Subscription; private previousUrlSubscription: Subscription; private downloadSubscription: Subscription; constructor( private router: Router, private utils: UtilsService, private logger: LoggerService, private errorHandling: ErrorHandlingService, private workflowService: WorkflowService, private routerUtilityService: RouterUtilityService, private adminService: AdminService ) { this.routerParam(); this.updateComponent(); } ngOnInit() { this.urlToRedirect = this.router.routerState.snapshot.url; } closeAttributeConfigure() { this.state = 'closed'; this.menuState = 'out'; this.selectedIndex = -1; } openAttributeConfigure(attributeDetail, index) { if (!attributeDetail.includeAll) { this.attributeValue = ''; this.attributeName = []; this.state = 'open'; this.menuState = 'in'; this.selectedIndex = index; console.log('attributeDetail==============>', attributeDetail); this.selectedAttributeDetails = attributeDetail.allAttributesName; this.selectedAttributes = attributeDetail.attributes; this.selectedAttributeIndex = '/aws_' +attributeDetail.targetName+ '/_search?filter_path=aggregations.alldata.buckets.key'; } } includeAllAttributes(attributeDetail, index) { this.allAttributeDetails[index].includeAll = !this.allAttributeDetails[index].includeAll; } isGroupNameAvailable(alexaKeyword) { if (alexaKeyword.length === 0) { this.isGroupNameValid = -1; } else { const isKeywordExits = this.assetGroupNames.findIndex(item => alexaKeyword.toLowerCase() === item.toLowerCase()); if (isKeywordExits === -1) { this.isGroupNameValid = 1; } else { this.isGroupNameValid = 0; } } } getAllAssetGroupNames() { this.hideContent = true; this.assetGroupLoader = true; this.progressText = 'Loading details'; this.isAssetGroupFailed = false; this.isAssetGroupSuccess = false; const url = environment.assetGroupNames.url; const method = environment.assetGroupNames.method; this.adminService.executeHttpAction(url, method, {}, {}).subscribe(reponse => { this.hideContent = false; this.assetGroupLoader = false; this.showLoader = false; this.assetGroupNames = reponse[0]; }, error => { this.assetGroupNames = []; this.errorMessage = 'apiResponseError'; this.showLoader = false; }); } public selectAttributes(value: any): void { this.checkAttributeAlreadyTaken(value.text); } public typedAttributes(value: any): void { this.attributeValue = [{ text: value, id: value }]; this.checkAttributeAlreadyTaken(value); } checkAttributeAlreadyTaken(attributeValue) { const attributeSearchedResult = _.find(this.allAttributeDetails[this.selectedIndex].attributes, { name: this.attributeName[0].text, value: attributeValue }); if (attributeSearchedResult === undefined) { this.isAttributeAlreadyAdded = -1; } else { this.isAttributeAlreadyAdded = 0; } } public getAttributeValues(value: any): void { this.attributeValue = [{ text: value, id: value }]; } getTargetTypeAttributeValues(attributeName) { const attrNameObj: any = {}; attrNameObj.size = 0; attrNameObj.aggs = {}; attrNameObj.aggs.alldata = {}; attrNameObj.aggs.alldata.terms = {}; attrNameObj.aggs.alldata.terms.field = attributeName + '.keyword'; attrNameObj.aggs.alldata.terms.size = 10000; this.isAttributeAlreadyAdded = -1; this.attributeValueElement.disabled = true; this.attributeValueElement.placeholder = 'Loading Values...'; this.attributeValue = []; this.targetTypeAttributeValues = []; const url = environment.listTargetTypeAttributeValues.url; const method = environment.listTargetTypeAttributeValues.method; let queryParams = { index: this.selectedAttributeIndex, payload: JSON.stringify(attrNameObj) }; console.log('queryParams=============>', queryParams); this.adminService.executeHttpAction(url, method, queryParams, {}).subscribe(attributeValues => { if (attributeValues.length > 0) { if (attributeValues[0].hasOwnProperty('data')) { if (attributeValues[0].data.hasOwnProperty('aggregations')) { if (attributeValues[0].data.aggregations.alldata.hasOwnProperty('buckets')) { const allAttributeValues = attributeValues[0].data.aggregations.alldata.buckets; allAttributeValues.forEach((attrValue) => { const allCurrentAttributeValues = {}; allCurrentAttributeValues['text'] = attrValue.key; allCurrentAttributeValues['id'] = attrValue.key; this.targetTypeAttributeValues.push(allCurrentAttributeValues); }); this.attributeValueElement.items = this.targetTypeAttributeValues; } } } this.attributeValueElement.disabled = false; this.attributeValueElement.placeholder = 'Select Value'; } else { this.attributeValueElement.disabled = false; this.attributeValueElement.placeholder = ''; } }, error => { this.targetTypeAttributeValues = []; this.attributeValueElement.disabled = false; this.attributeValueElement.placeholder = 'Select Value'; }); } addTagetType(targetTypeValue) { const targetTypeName = targetTypeValue[0].text; const targetTypeDetails1 = _.find(this.remainingTargetTypesFullDetails, { targetName: targetTypeName }); const targetTypeDetails2 = _.find(this.remainingTargetTypes, { id: targetTypeName }); this.allAttributeDetails.push(targetTypeDetails1); const itemIndex2 = this.remainingTargetTypes.indexOf(targetTypeDetails2); this.remainingTargetTypes.splice(itemIndex2, 1); this.targetTypeElement.items = this.remainingTargetTypes; this.targetTypeValue = []; } addAttributes(attributeName, attributeValue) { this.allAttributeDetails[this.selectedIndex].attributes.push({ name: attributeName[0].text, value: attributeValue[0].text }); this.attributeValue = []; this.attributeName = []; } deleteAttributes(attributeName, itemIndex) { this.allAttributeDetails[this.selectedIndex].attributes.splice(itemIndex, 1); } nextPage() { try { if (!this.isLastPage) { this.pageNumber++; this.showLoader = true; } } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } prevPage() { try { if (!this.isFirstPage) { this.pageNumber--; this.showLoader = true; } } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } nextStep() { if (!this.isCreate) { this.goToNextStep(); } else { if (this.stepIndex + 1 === 1) { if (!this.pageContent[this.stepIndex].isChanged) { this.assetLoaderFailure = false; this.assetLoader = true; this.assetLoaderTitle = 'Domain'; this.pageContent[0].hide = true; const url = environment.domains.url; const method = environment.domains.method; this.adminService.executeHttpAction(url, method, {}, {}).subscribe(reponse => { this.assetLoader = false; this.showLoader = false; if (reponse !== undefined) { this.availableItems = reponse[0]; this.selectedItems = []; this.availableItemsBackUp = _.cloneDeep(this.availableItems); this.selectedItemsBackUp = _.cloneDeep(this.selectedItems); this.availableItemsCopy = _.cloneDeep(this.availableItems); this.selectedItemsCopy = _.cloneDeep(this.selectedItems); this.searchAvailableDomains(); this.searchSelectedDomains(); this.goToNextStep(); } }, error => { this.assetLoader = false; this.assetLoaderFailure = true; this.errorValue = -1; this.outerArr = []; this.errorMessage = 'apiResponseError'; this.showLoader = false; }); } else { this.searchAvailableDomains(); this.searchSelectedDomains(); this.goToNextStep(); } } else if (this.stepIndex + 1 === 2) { if (!this.pageContent[this.stepIndex].isChanged) { this.assetLoaderTitle = 'Target'; this.assetLoaderFailure = false; this.assetLoader = true; this.pageContent[1].hide = true; const url = environment.targetTypesByDomains.url; const method = environment.targetTypesByDomains.method; const domainList = this.selectedItems.map(domain => domain.domainName); this.adminService.executeHttpAction(url, method, domainList, {}).subscribe(reponse => { this.assetLoader = false; this.showLoader = false; if (reponse !== undefined) { this.availableTdItems = reponse[0].data; this.selectedTdItems = []; if (this.selectedTdItemsCopyForPrevNext.length > 0) { this.selectedTdItemsCopyForPrevNext.forEach(tdItem => { const availableTdSearchedResult = _.find(this.availableTdItems, { targetName: tdItem.targetName }); const itemIndex = this.availableTdItems.indexOf(availableTdSearchedResult); if (itemIndex !== -1) { this.availableTdItems.splice(itemIndex, 1); this.selectedTdItems.push(availableTdSearchedResult); } }); } this.availableTdItemsBackUp = _.cloneDeep(this.availableTdItems); this.selectedTdItemsBackUp = _.cloneDeep(this.selectedTdItems); this.availableTdItemsCopy = _.cloneDeep(this.availableTdItems); this.selectedTdItemsCopy = _.cloneDeep(this.selectedTdItems); this.searchAvailableTargets(); this.searchSelectedTargets(); this.goToNextStep(); } }, error => { this.assetLoader = false; this.assetLoaderFailure = true; this.errorValue = -1; this.outerArr = []; this.errorMessage = 'apiResponseError'; this.showLoader = false; }); } else { this.searchAvailableDomains(); this.searchSelectedDomains(); this.goToNextStep(); } } else if (this.stepIndex + 1 === 3) { if (!this.pageContent[this.stepIndex].isChanged) { this.assetLoaderTitle = 'Target Attributes'; this.assetLoaderFailure = false; this.assetLoader = true; this.pageContent[2].hide = true; const url = environment.targetTypesAttributes.url; const method = environment.targetTypesAttributes.method; this.adminService.executeHttpAction(url, method, this.selectedTdItems, {}).subscribe(reponse => { this.assetLoader = false; this.showLoader = false; if (reponse !== undefined) { this.allAttributeDetails = reponse[0].data; if (this.allAttributeDetailsCopyForPrevNext.length > 0) { this.allAttributeDetailsCopyForPrevNext.forEach(attrElement => { const attributeSearchedResult = _.find(this.allAttributeDetails, { targetName: attrElement.targetName }); const itemIndex = this.allAttributeDetails.indexOf(attributeSearchedResult); if (itemIndex !== -1) { this.allAttributeDetails[itemIndex] = attrElement; } }); } this.allSelectedAttributeDetailsCopy = _.cloneDeep(this.allAttributeDetails); this.goToNextStep(); } }, error => { this.assetLoader = false; this.assetLoaderFailure = true; this.errorValue = -1; this.outerArr = []; this.errorMessage = 'apiResponseError'; this.showLoader = false; }); } else { this.goToNextStep(); } } else { this.goToNextStep(); } } } goToNextStep() { this.pageContent[this.stepIndex].hide = true; this.pageContent[this.stepIndex].isChanged = true; if (this.isCreate) { this.stepIndex++; } else { this.stepIndex += 3; } this.stepTitle = this.pageContent[this.stepIndex].title; this.pageContent[this.stepIndex].hide = false; } prevStep() { this.assetLoaderFailure = false; this.assetLoader = false; this.pageContent[this.stepIndex].hide = true; if (this.isCreate) { this.stepIndex--; } else { this.stepIndex -= 3; } this.stepTitle = this.pageContent[this.stepIndex].title; this.pageContent[this.stepIndex].hide = false; if (this.stepIndex + 1 === 3) { this.allAttributeDetailsCopyForPrevNext = _.cloneDeep(this.allAttributeDetails); } if (this.stepIndex + 1 === 2) { this.selectedTdItemsCopyForPrevNext = _.cloneDeep(this.selectedTdItems); } } closeAssetErrorMessage() { this.assetLoaderFailure = false; this.assetLoader = false; this.pageContent[this.stepIndex].hide = false; } update(newAssetGroupDetails) { this.showWidget = false; newAssetGroupDetails.targetTypes = this.allAttributeDetails; this.highlightedText = newAssetGroupDetails.groupName; this.progressText = 'Updating Asset Group'; this.hideContent = true; this.assetGroupLoader = true; this.isAssetGroupFailed = false; this.isAssetGroupSuccess = false; const url = environment.updateAssetGroups.url; const method = environment.updateAssetGroups.method; this.adminService.executeHttpAction(url, method, newAssetGroupDetails, {}).subscribe(reponse => { this.assetGroupLoader = false; this.isAssetGroupSuccess = true; this.successTitleStart = 'Asset Group'; this.successTitleEnd = 'has been successfully updated !!!'; }, error => { this.assetGroupLoader = false; this.isAssetGroupFailed = true; this.failedTitleStart = 'Failed in updating Asset Group'; this.failedTitleEnd = '!!!'; }); } create(newAssetGroupDetails) { this.showWidget = false; newAssetGroupDetails.targetTypes = this.allAttributeDetails; this.highlightedText = newAssetGroupDetails.groupName; this.progressText = 'Creating Asset Group'; this.hideContent = true; this.assetGroupLoader = true; this.isAssetGroupFailed = false; this.isAssetGroupSuccess = false; const url = environment.createAssetGroups.url; const method = environment.createAssetGroups.method; this.adminService.executeHttpAction(url, method, newAssetGroupDetails, {}).subscribe(reponse => { this.assetGroupLoader = false; this.isAssetGroupSuccess = true; this.successTitleStart = 'Asset Group'; this.successTitleEnd = 'has been successfully created !!!'; }, error => { this.assetGroupLoader = false; this.isAssetGroupFailed = true; this.failedTitleStart = 'Failed in creating Asset Group !!!'; this.failedTitleEnd = '!!!'; }); } isStepDisabled(stepIndex) { if (stepIndex === 0) { if (this.assetForm.groupName !== '' && this.assetForm.displayName !== '' && this.assetForm.type !== '' && this.assetForm.createdBy !== '' && this.isGroupNameValid === 1) { return false; } } else if (stepIndex === 1) { return (this.selectedItems.length === 0); } else if (stepIndex === 2) { return (this.selectedTdItems.length === 0); } return true; } closeErrorMessage() { this.showWidget = true; this.isAssetGroupFailed = false; this.hideContent = false; } searchAttribute() { const term = this.searchTerm; this.allAttributeDetails = this.allSelectedAttributeDetailsCopy.filter(function (tag) { return tag.targetName.indexOf(term) >= 0; }); } onClickAvailableItem(index, availableItem, key) { if (this.availChoosedItems.hasOwnProperty(index)) { this.availChoosedItems[index] = !this.availChoosedItems[index]; if (this.availChoosedItems[index]) { this.availChoosedSelectedItems[key] = availableItem; } else { delete this.availChoosedSelectedItems[key]; } } else { this.availChoosedItems[index] = true; this.availChoosedSelectedItems[key] = availableItem; } this.availChoosedItemsCount = Object.keys(this.availChoosedSelectedItems).length; } onClickSelectedItem(index, selectedItem, key) { if (this.selectChoosedItems.hasOwnProperty(index)) { this.selectChoosedItems[index] = !this.selectChoosedItems[index]; if (this.selectChoosedItems[index]) { this.selectChoosedSelectedItems[key] = selectedItem; } else { delete this.selectChoosedSelectedItems[key]; } } else { this.selectChoosedItems[index] = true; this.selectChoosedSelectedItems[key] = selectedItem; } this.selectChoosedItemsCount = Object.keys(this.selectChoosedSelectedItems).length; } moveAllItemsToLeft() { this.pageContent[this.stepIndex].isChanged = false; this.pageContent[2].isChanged = false; if (this.searchSelectedDomainTerms.length === 0) { this.availableItems = _.cloneDeep(this.availableItemsBackUp); this.availableItemsCopy = _.cloneDeep(this.availableItemsBackUp); this.selectedItems = []; this.selectedItemsCopy = []; this.selectChoosedItems = {}; this.selectChoosedSelectedItems = {}; this.selectChoosedItemsCount = 0; this.searchAvailableDomains(); this.searchSelectedDomains(); } else { this.selectChoosedSelectedItems = {}; this.selectedItems.forEach((element) => { this.selectChoosedSelectedItems[element.domainName] = element; }); this.moveItemToLeft(); } } moveAllItemsToRight() { this.pageContent[this.stepIndex].isChanged = false; this.pageContent[2].isChanged = false; if (this.searchAvailableDomainTerms.length === 0) { this.selectedItems = _.cloneDeep(this.availableItemsBackUp); this.selectedItemsCopy = _.cloneDeep(this.availableItemsBackUp); this.availableItemsCopy = []; this.availableItems = []; this.availChoosedItems = {}; this.availChoosedSelectedItems = {}; this.availChoosedItemsCount = 0; this.searchAvailableDomains(); this.searchSelectedDomains(); } else { this.availChoosedSelectedItems = {}; this.availableItems.forEach((element) => { this.availChoosedSelectedItems[element.domainName] = element; }); this.moveItemToRight(); } } moveItemToRight() { this.pageContent[this.stepIndex].isChanged = false; this.pageContent[2].isChanged = false; const selectedItemsCopy = this.selectedItemsCopy; const availableItemsCopy = this.availableItemsCopy; for (const choosedSelectedKey in this.availChoosedSelectedItems) { if (this.availChoosedSelectedItems.hasOwnProperty(choosedSelectedKey)) { selectedItemsCopy.push(this.availChoosedSelectedItems[choosedSelectedKey]); const filterIndex = availableItemsCopy.indexOf(this.availChoosedSelectedItems[choosedSelectedKey]); availableItemsCopy.splice(filterIndex, 1); } } this.availableItems = availableItemsCopy; if (this.searchAvailableDomainTerms.length !== 0) { this.searchAvailableDomains(); } this.selectedItems = selectedItemsCopy; if (this.searchSelectedDomainTerms.length !== 0) { this.searchSelectedDomains(); } this.availChoosedItems = {}; this.availChoosedSelectedItems = {}; this.availChoosedItemsCount = 0; } moveItemToLeft() { this.pageContent[this.stepIndex].isChanged = false; this.pageContent[2].isChanged = false; const selectedItemsCopy = this.selectedItemsCopy; const availableItemsCopy = this.availableItemsCopy; for (const choosedSelectedKey in this.selectChoosedSelectedItems) { if (this.selectChoosedSelectedItems.hasOwnProperty(choosedSelectedKey)) { availableItemsCopy.push(this.selectChoosedSelectedItems[choosedSelectedKey]); const filterIndex = selectedItemsCopy.indexOf(this.selectChoosedSelectedItems[choosedSelectedKey]); selectedItemsCopy.splice(filterIndex, 1); } } this.availableItems = availableItemsCopy; if (this.searchAvailableDomainTerms.length !== 0) { this.searchAvailableDomains(); } this.selectedItems = selectedItemsCopy; if (this.searchSelectedDomainTerms.length !== 0) { this.searchSelectedDomains(); } this.selectChoosedItems = {}; this.selectChoosedSelectedItems = {}; this.selectChoosedItemsCount = 0; } searchAvailableDomains() { const term = this.searchAvailableDomainTerms; this.availableItems = this.availableItemsCopy.filter(function (tag) { return tag.domainName.toLowerCase().indexOf(term.toLowerCase()) >= 0; }); } searchSelectedDomains() { const term = this.searchSelectedDomainTerms; this.selectedItems = this.selectedItemsCopy.filter(function (tag) { return tag.domainName.toLowerCase().indexOf(term.toLowerCase()) >= 0; }); } /* * TARGET DETAILS * */ onClickAvailableTdItem(index, availableItem, key) { if (this.availTdChoosedItems.hasOwnProperty(index)) { this.availTdChoosedItems[index] = !this.availTdChoosedItems[index]; if (this.availTdChoosedItems[index]) { this.availTdChoosedSelectedItems[key] = availableItem; } else { delete this.availTdChoosedSelectedItems[key]; } } else { this.availTdChoosedItems[index] = true; this.availTdChoosedSelectedItems[key] = availableItem; } this.availTdChoosedItemsCount = Object.keys(this.availTdChoosedSelectedItems).length; } onClickSelectedTdItem(index, selectedItem, key) { if (this.selectTdChoosedItems.hasOwnProperty(index)) { this.selectTdChoosedItems[index] = !this.selectTdChoosedItems[index]; if (this.selectTdChoosedItems[index]) { this.selectTdChoosedSelectedItems[key] = selectedItem; } else { delete this.selectTdChoosedSelectedItems[key]; } } else { this.selectTdChoosedItems[index] = true; this.selectTdChoosedSelectedItems[key] = selectedItem; } this.selectTdChoosedItemsCount = Object.keys(this.selectTdChoosedSelectedItems).length; } moveTdAllItemsToLeft() { this.pageContent[this.stepIndex].isChanged = false; if (this.searchSelectedTargetTerms.length === 0) { this.availableTdItems = _.cloneDeep(this.availableTdItemsBackUp); this.availableTdItemsCopy = _.cloneDeep(this.availableTdItemsBackUp); this.selectedTdItems = []; this.selectedTdItemsCopy = []; this.selectTdChoosedItems = {}; this.selectTdChoosedSelectedItems = {}; this.selectTdChoosedItemsCount = 0; this.searchAvailableTargets(); this.searchSelectedTargets(); } else { this.selectTdChoosedSelectedItems = {}; this.selectedTdItems.forEach((element) => { this.selectTdChoosedSelectedItems[element.targetName] = element; }); this.moveTdItemToLeft(); } } moveTdAllItemsToRight() { this.pageContent[this.stepIndex].isChanged = false; if (this.searchAvailableTargetTerms.length === 0) { this.selectedTdItems = _.cloneDeep(this.availableTdItemsBackUp); this.selectedTdItemsCopy = _.cloneDeep(this.availableTdItemsBackUp); this.availableTdItemsCopy = []; this.availableTdItems = []; this.availTdChoosedItems = {}; this.availTdChoosedSelectedItems = {}; this.availTdChoosedItemsCount = 0; this.searchAvailableTargets(); this.searchSelectedTargets(); } else { this.availTdChoosedSelectedItems = {}; this.availableTdItems.forEach((element) => { this.availTdChoosedSelectedItems[element.targetName] = element; }); this.moveTdItemToRight(); } } moveTdItemToRight() { this.pageContent[this.stepIndex].isChanged = false; const selectedTdItemsCopy = this.selectedTdItemsCopy; const availableTdItemsCopy = this.availableTdItemsCopy; for (const choosedTdSelectedKey in this.availTdChoosedSelectedItems) { if (this.availTdChoosedSelectedItems.hasOwnProperty(choosedTdSelectedKey)) { selectedTdItemsCopy.push(this.availTdChoosedSelectedItems[choosedTdSelectedKey]); const filterIndex = availableTdItemsCopy.indexOf(this.availTdChoosedSelectedItems[choosedTdSelectedKey]); availableTdItemsCopy.splice(filterIndex, 1); } } this.availableTdItems = availableTdItemsCopy; if (this.searchAvailableTargetTerms.length !== 0) { this.searchAvailableTargets(); } this.selectedTdItems = selectedTdItemsCopy; if (this.searchSelectedTargetTerms.length !== 0) { this.searchSelectedTargets(); } this.availTdChoosedItems = {}; this.availTdChoosedSelectedItems = {}; this.availTdChoosedItemsCount = 0; } moveTdItemToLeft() { this.pageContent[this.stepIndex].isChanged = false; const selectedTdItemsCopy = this.selectedTdItemsCopy; const availableTdItemsCopy = this.availableTdItemsCopy; for (const choosedTdSelectedKey in this.selectTdChoosedSelectedItems) { if (this.selectTdChoosedSelectedItems.hasOwnProperty(choosedTdSelectedKey)) { availableTdItemsCopy.push(this.selectTdChoosedSelectedItems[choosedTdSelectedKey]); const filterIndex = selectedTdItemsCopy.indexOf(this.selectTdChoosedSelectedItems[choosedTdSelectedKey]); selectedTdItemsCopy.splice(filterIndex, 1); } } this.availableTdItems = availableTdItemsCopy; if (this.searchAvailableTargetTerms.length !== 0) { this.searchAvailableTargets(); } this.selectedTdItems = selectedTdItemsCopy; if (this.searchSelectedTargetTerms.length !== 0) { this.searchSelectedTargets(); } this.selectTdChoosedItems = {}; this.selectTdChoosedSelectedItems = {}; this.selectTdChoosedItemsCount = 0; } searchAvailableTargets() { const term = this.searchAvailableTargetTerms; this.availableTdItems = this.availableTdItemsCopy.filter(function (tag) { return tag.targetName.toLowerCase().indexOf(term.toLowerCase()) >= 0; }); } searchSelectedTargets() { const term = this.searchSelectedTargetTerms; this.selectedTdItems = this.selectedTdItemsCopy.filter(function (tag) { return tag.targetName.toLowerCase().indexOf(term.toLowerCase()) >= 0; }); } getAssetGroupDetails() { this.hideContent = true; this.assetGroupLoader = true; this.progressText = 'Loading'; this.isAssetGroupFailed = false; this.isAssetGroupSuccess = false; this.isGroupNameValid = 1; const url = environment.assetGroupDetailsById.url; const method = environment.assetGroupDetailsById.method; this.adminService.executeHttpAction(url, method, {}, { assetGroupId: this.groupId, dataSource: 'aws' }).subscribe(assetGroupReponse => { this.hideContent = false; this.assetGroupLoader = false; this.isAssetGroupSuccess = false; this.allAttributeDetails = assetGroupReponse[0]; this.allSelectedAttributeDetailsCopy = assetGroupReponse[0]; this.assetForm = { dataSourceName: 'aws', groupName: assetGroupReponse[0].groupName, displayName: assetGroupReponse[0].displayName, type: assetGroupReponse[0].type, createdBy: assetGroupReponse[0].createdBy, description: assetGroupReponse[0].description, visible: assetGroupReponse[0].visible, targetTypes: assetGroupReponse[0].targetTypes }; this.allAttributeDetails = assetGroupReponse[0].targetTypes; this.allSelectedAttributeDetailsCopy = assetGroupReponse[0].targetTypes; this.remainingTargetTypes = assetGroupReponse[0].remainingTargetTypes; this.remainingTargetTypesFullDetails = assetGroupReponse[0].remainingTargetTypesFullDetails; }, error => { this.assetGroupLoader = false; this.isAssetGroupFailed = true; this.failedTitleStart = 'Failed in loading Asset Group'; this.failedTitleEnd = '!!!'; }); } /* * This function gets the urlparameter and queryObj *based on that different apis are being hit with different queryparams */ routerParam() { try { // this.filterText saves the queryparam const currentQueryParams = this.routerUtilityService.getQueryParametersFromSnapshot(this.router.routerState.snapshot.root); if (currentQueryParams) { this.FullQueryParams = currentQueryParams; this.groupId = this.FullQueryParams.groupId; this.groupName = this.FullQueryParams.groupName; this.queryParamsWithoutFilter = JSON.parse(JSON.stringify(this.FullQueryParams)); delete this.queryParamsWithoutFilter['filter']; if (this.groupId) { this.pageTitle = 'Edit Asset Group'; this.breadcrumbPresent = 'Edit Asset Group'; this.isCreate = false; this.highlightName = this.groupName; this.highlightedText = this.groupName; this.getAssetGroupDetails(); this.stepIndex = 0; this.pageContent[0].hide = true; this.pageContent[1].hide = true; this.pageContent[2].hide = true; this.pageContent[this.stepIndex].hide = false; this.stepTitle = 'Update Group Details - ' + this.groupName; } else { this.getAllAssetGroupNames(); this.pageTitle = 'Create Asset Group'; this.breadcrumbPresent = 'Create Asset Group'; this.isCreate = true; } /** * The below code is added to get URLparameter and queryparameter * when the page loads ,only then this function runs and hits the api with the * filterText obj processed through processFilterObj function */ this.filterText = this.utils.processFilterObj( this.FullQueryParams ); this.urlID = this.FullQueryParams.TypeAsset; // check for mandatory filters. if (this.FullQueryParams.mandatory) { this.mandatory = this.FullQueryParams.mandatory; } } } catch (error) { this.errorMessage = this.errorHandling.handleJavascriptError(error); this.logger.log('error', error); } } /** * This function get calls the keyword service before initializing * the filter array ,so that filter keynames are changed */ updateComponent() { this.outerArr = []; this.showLoader = true; this.errorValue = 0; } navigateBack() { try { this.workflowService.goBackToLastOpenedPageAndUpdateLevel(this.router.routerState.snapshot.root); } catch (error) { this.logger.log('error', error); } } ngOnDestroy() { try { if (this.routeSubscription) { this.routeSubscription.unsubscribe(); } if (this.previousUrlSubscription) { this.previousUrlSubscription.unsubscribe(); } } catch (error) { this.logger.log('error', '--- Error while unsubscribing ---'); } } }
the_stack
export interface JeelizFaceFilterInitVideoSettings { /** * not set by default. <video> element used WARN: If you specify this parameter, 1. all other settings will be useless 2. it means that you fully handle the video aspect 3. in case of using web-camera device make sure that initialization goes after `loadeddata` event of the `videoElement`, otherwise face detector will yield very low `detectState.detected` values (to be more sure also await first `timeupdate` event) */ videoElement?: HTMLVideoElement; /** not set by default */ deviceId?: string; /** to use the rear camera, set to 'environment' */ facingMode?: string; /** ideal video width in pixels */ idealWidth?: number; /** ideal video height in pixels */ idealHeight?: number; /** min video width in pixels */ minWidth?: number; /** max video width in pixels */ maxWidth?: number; /** min video height in pixels */ minHeight?: number; /** max video height in pixels, */ maxHeight?: number; /** rotation in degrees possible values: 0,90,-90,180 */ rotate?: number; /** if we should flip horizontally the video. Default: false */ flipX?: boolean; } export interface IJeelizFaceFilterScanSettings { minScale: number; maxScale: number; borderwidth: number; borderHeight: number; nStepsX: number; nStepsY: number; nStepsScale: number; nDetectsPerLoop: number; } export interface IJeelizFaceFilterStabilizationSettings { translationFactorRange: [number, number]; rotationFactorRange: [number, number]; qualityFactorRange: [number, number]; alphaRange: [number, number]; } export interface IJeelizFaceFilterDetectState { /** the face detection probability, between 0 and 1, */ detected: 0 | 1; /** : The 2D coordinates of the center of the detection frame in the viewport (each between -1 and 1, x from left to right and y from bottom to top), */ x: number; /** : The 2D coordinates of the center of the detection frame in the viewport (each between -1 and 1, x from left to right and y from bottom to top), */ y: number; /** the scale along the horizontal axis of the detection frame, between 0 and 1 (1 for the full width). The detection frame is always square, */ s: number; /** the Euler angles of the head rotation in radians. */ rx: number; /** the Euler angles of the head rotation in radians. */ ry: number; /** the Euler angles of the head rotation in radians. */ rz: number; /** array listing the facial expression coefficients: expressions[0]: mouth opening coefficient (0 → mouth closed, 1 → mouth fully opened) */ expressions: Float32Array; } export interface IJeelizFaceFilterInitParams { callbackReady?: (err: string | false, spec: IJeelizFaceFilterInitResult) => void; callbackTrack?: (detectState: IJeelizFaceFilterDetectState) => void; /** * It is used only in normal rendering mode (not in slow rendering mode). With this statement you can set accurately the number of milliseconds during which the browser wait at the end of the rendering loop before starting another detection. If you use the canvas of this API as a secondary element (for example in PACMAN or EARTH NAVIGATION demos) you should set a small animateDelay value (for example 2 milliseconds) in order to avoid rendering lags. */ animateDelay?: number; NNCPath?: string; NNC?: string; /** * Only for multiple face detection - maximum number of faces which can be detected and tracked. Should be between 1 (no multiple detection) and 8, */ maxFacesDetected?: number; /** * Allow full rotation around depth axis. Default value: false. See Issue 42 for more details, */ followZRot?: boolean; canvasId?: string; canvas?: HTMLCanvasElement; scanSettings?: IJeelizFaceFilterScanSettings; stabilizationSettings?: IJeelizFaceFilterStabilizationSettings; videoSettings?: JeelizFaceFilterInitVideoSettings; /** * Function launched just before asking for the user to allow its webcam sharing, */ onWebcamAsk?: () => void; onWebcamGet?: (videoElement: HTMLVideoElement, stream?: MediaStream, videoTrackInfo?: any) => void; } export interface IJeelizFaceFilterInitResult { /** the <canvas> element, */ canvasElement:HTMLCanvasElement; /** the WebGL context. The rendering 3D engine should use this WebGL context, */ GL:WebGL2RenderingContext; /** a WebGL texture displaying the camera video. It has the same resolution as the camera video, */ videoTexture:WebGLTexture; /** the video used as source for the webgl texture videoTexture, */ videoElement:HTMLVideoElement; /** flatten 2x2 matrix encoding a scaling and a rotation. We should apply this matrix to viewport coordinates to render videoTexture in the viewport, */ videoTransformMat2:number[]; /** the maximum number of detected faces. */ maxFacesDetected: number; } export interface IJeelizFaceFilter { init(params: IJeelizFaceFilterInitParams): boolean; /** Should be called before the init method. 2 arguments are provided to the callback function: <array> mediaDevices: an array with all the devices founds. Each device is a javascript object having a deviceId string attribute. This value can be provided to the init method to use a specific webcam. If an error happens, this value is set to false, <string> errorLabel: if an error happens, the label of the error. It can be: NOTSUPPORTED, NODEVICESFOUND or PROMISEREJECTED. */ get_videoDevices(callback: (mediaDevices: Array<{deviceId: string}> | false, errorLabel?: string) => void): any; /** Change the video input by a WebGL Texture instance. The dimensions of the texture, in pixels, should be provided, Come back to the user's video as input texture, */ reset_inputTexture(): void; /** should be called after resizing the <canvas> element to adapt the cut of the video. * It should also be called if the device orientation is changed to take account of new video dimensions, */ resize(): boolean; /** Change the animateDelay (see init() arguments), */ set_animateDelay(delay: number): void; set_inputTexture(tex: WebGLTexture, width: number, height: number): void; /** Override scan settings. scanSettings is a dictionnary with the following properties: <float> scale0Factor: Relative width (1 -> full width) of the searching window at the largest scale level. Default value is 0.8, <int> nScaleLevels: Number of scale levels. Default is 3, [<float>, <float>, <float>] overlapFactors: relative overlap according to X,Y and scale axis between 2 searching window positions. Higher values make scan faster but it may miss some positions. Set to [1, 1, 1] for no overlap. Default value is [2, 2, 3], <int> nDetectsPerLoop: specify the number of detection per drawing loop. -1 for adaptative value. Default: -1 */ set_scanSettings(settings: IJeelizFaceFilterScanSettings): void; /** Override detection stabilization settings. The output of the neural network is always noisy, so we need to stabilize it using a floatting average to avoid shaking artifacts. The internal algorithm computes first a stabilization factor k between 0 and 1. If k==0.0, the detection is bad and we favor responsivity against stabilization. It happens when the user is moving quickly, rotating the head or when the detection is bad. On the contrary, if k is close to 1, the detection is nice and the user does not move a lot so we can stabilize a lot. stabilizationSettings is a dictionnary with the following properties: [<float> minValue, <float> maxValue] translationFactorRange: multiply k by a factor kTranslation depending on the translation speed of the head (relative to the viewport). kTranslation=0 if translationSpeed<minValue and kTranslation=1 if translationSpeed>maxValue. The regression is linear. Default value: [0.0015, 0.005], [<float> minValue, <float> maxValue] rotationFactorRange: analogous to translationFactorRange but for rotation speed. Default value: [0.003, 0.02], [<float> minValue, <float> maxValue] qualityFactorRange: analogous to translationFactorRange but for the head detection coefficient. Default value: [0.9, 0.98], [<float> minValue, <float> maxValue] alphaRange: it specify how to apply k. Between 2 successive detections, we blend the previous detectState values with the current detection values using a mixing factor alpha. alpha=<minValue> if k<0.0 and alpha=<maxValue> if k>1.0. Between the 2 values, the variation is quadratic. Default value: [0.05, 1]. */ set_stabilizationSettings(settings: IJeelizFaceFilterStabilizationSettings): void; /** pause/resume. This method will completely stop the rendering/detection loop. If isShutOffVideo is set to true, the media stream track will be */ toggle_pause(isPause?: boolean, isShutOffVideo?: boolean): any; /** : toggle the slow rendering mode: because this API consumes a lot of GPU resources, it may slow down other elements of the application. * If the user opens a CSS menu for example, the CSS transitions and the DOM update can be slow. With this function you can * slow down the rendering in order to relieve the GPU. Unfortunately the tracking and the 3D rendering will also be slower * but this is not a problem is the user is focusing on other elements of the application. We encourage to enable the slow mode * as soon as a the user's attention is focused on a different part of the canvas, */ toggle_slow(isSlow?: boolean): any; /** change the video element used for the face detection (which can be provided via VIDEOSETTINGS.videoElement) by another video element. * A callback function can be called when it is done. */ update_videoElement(video: HTMLVideoElement, callback: () => void): void; /** Dynamically change the video settings (see Optional init arguments for the properties of videoSettings). It is useful to change the camera from * the selfie camera (user) to the back (environment) camera. A Promise is returned. */ update_videoSettings(videoSettings: JeelizFaceFilterInitVideoSettings): Promise<void>; /** Dynamically change videoSettings.rotate and videoSettings.flipX. This method should be called after initialization. * The default values are 0 and false. The angle should be chosen among these values: 0, 90, 180, -90, */ set_videoOrientation(angle: number, flipX: boolean); /** Clean both graphic memory and JavaScript memory, uninit the library. After that you need to init the library again. A Promise is returned, */ destroy(): Promise<void>; /** reset the WebGL context */ reset_GLState(); /** render the video on the <canvas> element. */ render_video(); }
the_stack
import {Server as HTTPServer} from 'http'; import BLeak from '../src/lib/bleak'; import createHTTPServer from './util/http_server'; import ChromeDriver from '../src/lib/chrome_driver'; import {readFileSync} from 'fs'; import {equal as assertEqual} from 'assert'; import NopProgressBar from '../src/lib/nop_progress_bar'; import NopLog from '../src/common/nop_log'; const HTTP_PORT = 8875; const DEBUG = false; interface TestFile { mimeType: string; data: Buffer; } function getHTMLDoc(docStr: string): { mimeType: string, data: Buffer } { return { mimeType: 'text/html', data: Buffer.from(docStr, 'utf8') }; } function getHTMLConfig(name: string): { mimeType: string, data: Buffer } { return getHTMLDoc(`<!DOCTYPE html><html><head><title>${name}</title></head><body><button id="btn">Click Me</button><script type="text/javascript" src="/${name}.js"></script></body></html>`); } // 'Files' present in the test HTTP server const FILES: {[name: string]: TestFile} = { '/test.html': getHTMLConfig('test'), '/test.js': { mimeType: 'text/javascript', data: Buffer.from(`var obj = {}; var i = 0; var power = 2; document.getElementById('btn').addEventListener('click', function() { var top = Math.pow(2, power); power++; for (var j = 0; j < top; j++) { obj[Math.random()] = Math.random(); } }); `, 'utf8') }, '/closure_test.html': getHTMLConfig('closure_test'), '/closure_test.js': { mimeType: 'text/javascript', data: Buffer.from(`(function() { var obj = {}; var i = 0; var power = 2; window.objfcn = function() { var top = Math.pow(2, power); power++; for (var j = 0; j < top; j++) { obj[Math.random()] = Math.random(); } }; })(); document.getElementById('btn').addEventListener('click', function() { window.objfcn(); });`) }, '/closure_test_dom.html': getHTMLConfig('closure_test_dom'), '/closure_test_dom.js': { mimeType: 'text/javascript', data: Buffer.from(`(function() { var obj = {}; var i = 0; var power = 2; document.getElementById('btn').addEventListener('click', function() { var top = Math.pow(2, power); power++; for (var j = 0; j < top; j++) { obj[Math.random()] = Math.random(); } }); })(); `, 'utf8') }, '/closure_test_dom_on_property.html': getHTMLConfig('closure_test_dom_on_property'), '/closure_test_dom_on_property.js': { mimeType: 'text/javascript', data: Buffer.from(`(function() { var obj = {}; var i = 0; var power = 2; document.getElementById('btn').onclick = function() { var top = Math.pow(2, power); power++; for (var j = 0; j < top; j++) { obj[Math.random()] = Math.random(); } }; })(); `, 'utf8') }, '/closure_test_irrelevant_dom.html': getHTMLDoc(`<!DOCTYPE html><html><head><title>Closure test irrelevant dom</title></head><body><button id="btn2">Don't click me</button><button id="btn">Click Me</button><button id="btn3">Don't click me, either</button><script type="text/javascript" src="/closure_test_irrelevant_dom.js"></script></body></html>`), '/closure_test_irrelevant_dom.js': { mimeType: 'text/javascript', data: Buffer.from(`(function() { var obj = {}; var i = 0; var power = 2; document.getElementById('btn').addEventListener('click', function() { var top = Math.pow(2, power); power++; for (var j = 0; j < top; j++) { obj[Math.random()] = Math.random(); } }); })(); `, 'utf8') }, '/closure_test_disconnected_dom.html': getHTMLDoc(`<!DOCTYPE html><html><head><title>Closure test disconnected dom</title></head><body><button id="btn">Click Me</button><script type="text/javascript" src="/closure_test_disconnected_dom.js"></script></body></html>`), '/closure_test_disconnected_dom.js': { mimeType: 'text/javascript', data: Buffer.from(`(function() { var obj = {}; var i = 0; var power = 2; var btn = document.createElement('button'); btn.addEventListener('click', function() { var top = Math.pow(2, power); power++; for (var j = 0; j < top; j++) { obj[Math.random()] = Math.random(); } }); window.$$btn = btn; })(); (function() { document.getElementById('btn').addEventListener('click', function() { window.$$btn.click(); }); })(); `, 'utf8') }, /*'/closure_test_disconnected_dom_collection.html': getHTMLDoc(`<!DOCTYPE html><html><head><title>Closure test disconnected dom collection</title></head><body><button id="btn">Click Me</button><script type="text/javascript" src="/closure_test_disconnected_dom_collection.js"></script></body></html>`), '/closure_test_disconnected_dom_collection.js': { mimeType: 'text/javascript', data: Buffer.from(`(function() { var obj = {}; var i = 0; var power = 2; document.body.appendChild(document.createElement('button')); var buttons = document.getElementsByTagName('button'); buttons[1].addEventListener('click', function() { var top = Math.pow(2, power); power++; for (var j = 0; j < top; j++) { obj[Math.random()] = Math.random(); } }); document.body.removeChild(buttons[1]); window.$$btns = buttons; })(); (function() { document.getElementById('btn').addEventListener('click', function() { window.$$btns[1].click(); }); })(); `, 'utf8') },*/ '/reassignment_test.html': getHTMLConfig('reassignment_test'), '/reassignment_test.js': { mimeType: 'text/javascript', data: Buffer.from(` (function() { var obj = []; var i = 0; var power = 2; document.getElementById('btn').addEventListener('click', function() { var top = Math.pow(2, power); power++; for (var j = 0; j < top; j++) { obj = obj.concat({ val: Math.random() }); } }); })(); `, 'utf8') }, '/multiple_paths_test.html': getHTMLConfig('multiple_paths_test'), '/multiple_paths_test.js': { mimeType: 'text/javascript', data: Buffer.from(`(function() { var obj = {}; var obj2 = obj; var i = 0; var power = 2; document.getElementById('btn').addEventListener('click', function() { var top = Math.pow(2, power); power++; for (var j = 0; j < top; j++) { if (obj === obj2) { var target = Math.random() > 0.5 ? obj : obj2; target[Math.random()] = Math.random(); } } }); })(); `, 'utf8') }, '/irrelevant_paths_test.html': getHTMLConfig('irrelevant_paths_test'), '/irrelevant_paths_test.js': { mimeType: 'text/javascript', data: Buffer.from(`var obj = {}; var i = 0; var power = 2; document.getElementById('btn').addEventListener('click', function() { var top = Math.pow(2, power); power++; for (var j = 0; j < top; j++) { obj[Math.random()] = Math.random(); } // Adds more properties, but properly deletes them. // Not a leak. var second = Math.random(); obj[second] = second; delete obj[second]; });`, 'utf8') }, '/event_listener_leak.html': getHTMLConfig('event_listener_leak'), '/event_listener_leak.js': { mimeType: 'text/javascript', data: Buffer.from(` // Make unique functions so we can register many listeners. function getAddListener() { return function() { document.getElementById('btn').addEventListener('click', getAddListener()); document.getElementById('btn').addEventListener('click', getAddListener()); document.getElementById('btn').addEventListener('click', getAddListener()); document.getElementById('btn').addEventListener('click', getAddListener()); }; } getAddListener()();`, 'utf8') }, '/event_listener_removal.html': getHTMLConfig('event_listener_removal'), '/event_listener_removal.js': { mimeType: 'text/javascript', data: Buffer.from(` // Make unique functions so we can register many listeners. function getAddListener() { return function() { document.getElementById('btn').addEventListener('click', getAddListener()); document.getElementById('btn').addEventListener('click', getAddListener()); document.getElementById('btn').addEventListener('click', getAddListener()); document.getElementById('btn').addEventListener('click', getAddListener()); }; } getAddListener()(); // Responsible function document.getElementById('btn').addEventListener('click', function() { var b = document.getElementById('btn'); var l = getAddListener(); b.addEventListener('click', l); b.removeEventListener('click', l); });`, 'utf8') }, '/dom_growth_test.html': getHTMLConfig('dom_growth_test'), '/dom_growth_test.js': { mimeType: 'text/javascript', data: Buffer.from(`var body = document.getElementsByTagName('body')[0]; document.getElementById('btn').addEventListener('click', function() { body.appendChild(document.createElement('div')); });`, 'utf8') }, '/bleak_agent.js': { mimeType: 'text/javascript', data: readFileSync(require.resolve('../src/lib/bleak_agent')) } }; describe('End-to-end Tests', function() { // 10 minute timeout. this.timeout(600000); let httpServer: HTTPServer; let driver: ChromeDriver; before(async function() { httpServer = await createHTTPServer(FILES, HTTP_PORT); if (!DEBUG) { // Silence debug messages. console.debug = () => {}; } driver = await ChromeDriver.Launch(NopLog, true, 1920, 1080); }); function createStandardLeakTest(description: string, rootFilename: string, expected_line: number): void { it(description, async function() { // let i = 0; const result = await BLeak.FindLeaks(` exports.url = 'http://localhost:${HTTP_PORT}/${rootFilename}.html'; // Due to throttling (esp. when browser is in background), it may take longer // than anticipated for the click we fire to actually run. We want to make // sure all snapshots occur after the click processes. var startedClickCount = 0; var completedClickCount = 0; exports.loop = [ { name: 'Click Button', check: function() { return document.readyState === "complete" && startedClickCount === completedClickCount; }, next: function() { startedClickCount++; if (completedClickCount === 0) { document.getElementById('btn').addEventListener('click', function() { completedClickCount++; }); } document.getElementById('btn').click(); } } ]; exports.timeout = 30000; exports.iterations = 3; exports.postCheckSleep = 100; `, new NopProgressBar(), driver, (results) => {}/*, (ss) => { const stream = createWriteStream(`${rootFilename}${i}.heapsnapshot`); ss.onSnapshotChunk = function(chunk, end) { stream.write(chunk); if (end) { stream.end(); } }; i++; return Promise.resolve(); }*/); assertEqual(result.leaks.length > 0, true); result.leaks.forEach((leak) => { const stacks = leak.stacks; assertEqual(stacks.length > 0, true); stacks.forEach((s) => { assertEqual(s.length > 0, true); const topFrame = result.stackFrames[s[0]]; //console.log(topFrame.toString()); assertEqual(topFrame[1], expected_line); assertEqual(topFrame[0].indexOf(`${rootFilename}.js`) !== -1, true); }); }); }); } createStandardLeakTest('Catches leaks', 'test', 8); createStandardLeakTest('Catches leaks in closures', 'closure_test', 9); createStandardLeakTest('Catches leaks in closures on dom', 'closure_test_dom', 9); createStandardLeakTest('Catches leaks in closures when event listener is assigned on a property', 'closure_test_dom_on_property', 9); createStandardLeakTest('Catches leaks in closures, even with irrelevant DOM objects', 'closure_test_irrelevant_dom', 9); createStandardLeakTest('Catches leaks in closures, even with disconnected DOM fragments', 'closure_test_disconnected_dom', 10); // Not supported. // createStandardLeakTest('Catches leaks in closures, even with disconnected DOM collections', 'closure_test_disconnected_dom_collection', 11); createStandardLeakTest('Catches leaks when object is copied and reassigned', 'reassignment_test', 10); createStandardLeakTest('Catches leaks when object stored in multiple paths', 'multiple_paths_test', 12); createStandardLeakTest('Ignores code that does not grow objects', 'irrelevant_paths_test', 8); createStandardLeakTest('Catches event listener leaks', 'event_listener_leak', 5); createStandardLeakTest('Ignores responsible event listener removal', 'event_listener_removal', 5); createStandardLeakTest('Catches leaks that grow DOM unboundedly', 'dom_growth_test', 3); after(function(done) { //setTimeout(function() { // Shutdown both HTTP server and proxy. let e: any = null; function wrappedDone() { done(e); } function shutdownProxy() { if (driver) { driver.shutdown().then(wrappedDone, (localE) => { e = localE; wrappedDone(); }); } else { wrappedDone(); } } function shutdownHTTPServer() { if (httpServer) { httpServer.close((localE: any) => { e = localE; shutdownProxy(); }); } else { shutdownProxy(); } } DEBUG ? setTimeout(shutdownHTTPServer, 99999999) : shutdownHTTPServer(); //}, 99999999); }); });
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement, Operator } from "../shared"; /** * Statement provider for service [dms](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsdatabasemigrationservice.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Dms extends PolicyStatement { public servicePrefix = 'dms'; /** * Statement provider for service [dms](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsdatabasemigrationservice.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Grants permission to add metadata tags to DMS resources, including replication instances, endpoints, security groups, and migration tasks * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifReqTag() * * https://docs.aws.amazon.com/dms/latest/APIReference/API_AddTagsToResource.html */ public toAddTagsToResource() { return this.to('AddTagsToResource'); } /** * Grants permission to apply a pending maintenance action to a resource (for example, to a replication instance) * * Access Level: Write * * https://docs.aws.amazon.com/dms/latest/APIReference/API_ApplyPendingMaintenanceAction.html */ public toApplyPendingMaintenanceAction() { return this.to('ApplyPendingMaintenanceAction'); } /** * Grants permission to cancel a single premigration assessment run * * Access Level: Write * * https://docs.aws.amazon.com/dms/latest/APIReference/API_CancelReplicationTaskAssessmentRun.html */ public toCancelReplicationTaskAssessmentRun() { return this.to('CancelReplicationTaskAssessmentRun'); } /** * Grants permission to create an endpoint using the provided settings * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifReqTag() * * https://docs.aws.amazon.com/dms/latest/APIReference/API_CreateEndpoint.html */ public toCreateEndpoint() { return this.to('CreateEndpoint'); } /** * Grants permission to create an AWS DMS event notification subscription * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifReqTag() * * https://docs.aws.amazon.com/dms/latest/APIReference/API_CreateEventSubscription.html */ public toCreateEventSubscription() { return this.to('CreateEventSubscription'); } /** * Grants permission to create a replication instance using the specified parameters * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifReqTag() * * https://docs.aws.amazon.com/dms/latest/APIReference/API_CreateReplicationInstance.html */ public toCreateReplicationInstance() { return this.to('CreateReplicationInstance'); } /** * Grants permission to create a replication subnet group given a list of the subnet IDs in a VPC * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifReqTag() * * https://docs.aws.amazon.com/dms/latest/APIReference/API_CreateReplicationSubnetGroup.html */ public toCreateReplicationSubnetGroup() { return this.to('CreateReplicationSubnetGroup'); } /** * Grants permission to create a replication task using the specified parameters * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifReqTag() * * https://docs.aws.amazon.com/dms/latest/APIReference/API_CreateReplicationTask.html */ public toCreateReplicationTask() { return this.to('CreateReplicationTask'); } /** * Grants permission to delete the specified certificate * * Access Level: Write * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DeleteCertificate.html */ public toDeleteCertificate() { return this.to('DeleteCertificate'); } /** * Grants permission to delete the specified connection between a replication instance and an endpoint * * Access Level: Write * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DeleteConnection.html */ public toDeleteConnection() { return this.to('DeleteConnection'); } /** * Grants permission to delete the specified endpoint * * Access Level: Write * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DeleteEndpoint.html */ public toDeleteEndpoint() { return this.to('DeleteEndpoint'); } /** * Grants permission to delete an AWS DMS event subscription * * Access Level: Write * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DeleteEventSubscription.html */ public toDeleteEventSubscription() { return this.to('DeleteEventSubscription'); } /** * Grants permission to delete the specified replication instance * * Access Level: Write * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DeleteReplicationInstance.html */ public toDeleteReplicationInstance() { return this.to('DeleteReplicationInstance'); } /** * Grants permission to deletes a subnet group * * Access Level: Write * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DeleteReplicationSubnetGroup.html */ public toDeleteReplicationSubnetGroup() { return this.to('DeleteReplicationSubnetGroup'); } /** * Grants permission to delete the specified replication task * * Access Level: Write * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DeleteReplicationTask.html */ public toDeleteReplicationTask() { return this.to('DeleteReplicationTask'); } /** * Grants permission to delete the record of a single premigration assessment run * * Access Level: Write * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DeleteReplicationTaskAssessmentRun.html */ public toDeleteReplicationTaskAssessmentRun() { return this.to('DeleteReplicationTaskAssessmentRun'); } /** * Grants permission to list all of the AWS DMS attributes for a customer account * * Access Level: Read * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DescribeAccountAttributes.html */ public toDescribeAccountAttributes() { return this.to('DescribeAccountAttributes'); } /** * Grants permission to list individual assessments that you can specify for a new premigration assessment run * * Access Level: Read * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DescribeApplicableIndividualAssessments.html */ public toDescribeApplicableIndividualAssessments() { return this.to('DescribeApplicableIndividualAssessments'); } /** * Grants permission to provide a description of the certificate * * Access Level: Read * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DescribeCertificates.html */ public toDescribeCertificates() { return this.to('DescribeCertificates'); } /** * Grants permission to describe the status of the connections that have been made between the replication instance and an endpoint * * Access Level: Read * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DescribeConnections.html */ public toDescribeConnections() { return this.to('DescribeConnections'); } /** * Grants permission to return the possible endpoint settings available when you create an endpoint for a specific database engine * * Access Level: Read * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DescribeEndpointSettings.html */ public toDescribeEndpointSettings() { return this.to('DescribeEndpointSettings'); } /** * Grants permission to return information about the type of endpoints available * * Access Level: Read * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DescribeEndpointTypes.html */ public toDescribeEndpointTypes() { return this.to('DescribeEndpointTypes'); } /** * Grants permission to return information about the endpoints for your account in the current region * * Access Level: Read * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DescribeEndpoints.html */ public toDescribeEndpoints() { return this.to('DescribeEndpoints'); } /** * Grants permission to list categories for all event source types, or, if specified, for a specified source type * * Access Level: Read * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DescribeEventCategories.html */ public toDescribeEventCategories() { return this.to('DescribeEventCategories'); } /** * Grants permission to list all the event subscriptions for a customer account * * Access Level: Read * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DescribeEventSubscriptions.html */ public toDescribeEventSubscriptions() { return this.to('DescribeEventSubscriptions'); } /** * Grants permission to list events for a given source identifier and source type * * Access Level: Read * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DescribeEvents.html */ public toDescribeEvents() { return this.to('DescribeEvents'); } /** * Grants permission to return information about the replication instance types that can be created in the specified region * * Access Level: Read * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DescribeOrderableReplicationInstances.html */ public toDescribeOrderableReplicationInstances() { return this.to('DescribeOrderableReplicationInstances'); } /** * Grants permission to returns the status of the RefreshSchemas operation * * Access Level: Read * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DescribeRefreshSchemasStatus.html */ public toDescribeRefreshSchemasStatus() { return this.to('DescribeRefreshSchemasStatus'); } /** * Grants permission to return information about the task logs for the specified task * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DescribeReplicationInstanceTaskLogs.html */ public toDescribeReplicationInstanceTaskLogs() { return this.to('DescribeReplicationInstanceTaskLogs'); } /** * Grants permission to return information about replication instances for your account in the current region * * Access Level: Read * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DescribeReplicationInstances.html */ public toDescribeReplicationInstances() { return this.to('DescribeReplicationInstances'); } /** * Grants permission to return information about the replication subnet groups * * Access Level: Read * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DescribeReplicationSubnetGroups.html */ public toDescribeReplicationSubnetGroups() { return this.to('DescribeReplicationSubnetGroups'); } /** * Grants permission to return the latest task assessment results from Amazon S3 * * Access Level: Read * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DescribeReplicationTaskAssessmentResults.html */ public toDescribeReplicationTaskAssessmentResults() { return this.to('DescribeReplicationTaskAssessmentResults'); } /** * Grants permission to return a paginated list of premigration assessment runs based on filter settings * * Access Level: Read * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DescribeReplicationTaskAssessmentRuns.html */ public toDescribeReplicationTaskAssessmentRuns() { return this.to('DescribeReplicationTaskAssessmentRuns'); } /** * Grants permission to return a paginated list of individual assessments based on filter settings * * Access Level: Read * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DescribeReplicationTaskIndividualAssessments.html */ public toDescribeReplicationTaskIndividualAssessments() { return this.to('DescribeReplicationTaskIndividualAssessments'); } /** * Grants permission to return information about replication tasks for your account in the current region * * Access Level: Read * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DescribeReplicationTasks.html */ public toDescribeReplicationTasks() { return this.to('DescribeReplicationTasks'); } /** * Grants permission to return information about the schema for the specified endpoint * * Access Level: Read * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DescribeSchemas.html */ public toDescribeSchemas() { return this.to('DescribeSchemas'); } /** * Grants permission to return table statistics on the database migration task, including table name, rows inserted, rows updated, and rows deleted * * Access Level: Read * * https://docs.aws.amazon.com/dms/latest/APIReference/API_DescribeTableStatistics.html */ public toDescribeTableStatistics() { return this.to('DescribeTableStatistics'); } /** * Grants permission to upload the specified certificate * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/dms/latest/APIReference/API_ImportCertificate.html */ public toImportCertificate() { return this.to('ImportCertificate'); } /** * Grants permission to list all tags for an AWS DMS resource * * Access Level: Read * * https://docs.aws.amazon.com/dms/latest/APIReference/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to modify the specified endpoint * * Access Level: Write * * https://docs.aws.amazon.com/dms/latest/APIReference/API_ModifyEndpoint.html */ public toModifyEndpoint() { return this.to('ModifyEndpoint'); } /** * Grants permission to modify an existing AWS DMS event notification subscription * * Access Level: Write * * https://docs.aws.amazon.com/dms/latest/APIReference/API_ModifyEventSubscription.html */ public toModifyEventSubscription() { return this.to('ModifyEventSubscription'); } /** * Grants permission to modify the replication instance to apply new settings * * Access Level: Write * * https://docs.aws.amazon.com/dms/latest/APIReference/API_ModifyReplicationInstance.html */ public toModifyReplicationInstance() { return this.to('ModifyReplicationInstance'); } /** * Grants permission to modify the settings for the specified replication subnet group * * Access Level: Write * * https://docs.aws.amazon.com/dms/latest/APIReference/API_ModifyReplicationSubnetGroup.html */ public toModifyReplicationSubnetGroup() { return this.to('ModifyReplicationSubnetGroup'); } /** * Grants permission to modify the specified replication task * * Access Level: Write * * https://docs.aws.amazon.com/dms/latest/APIReference/API_ModifyReplicationTask.html */ public toModifyReplicationTask() { return this.to('ModifyReplicationTask'); } /** * Grants permission to move the specified replication task to a different replication instance * * Access Level: Write * * https://docs.aws.amazon.com/dms/latest/APIReference/API_MoveReplicationTask.html */ public toMoveReplicationTask() { return this.to('MoveReplicationTask'); } /** * Grants permission to reboot a replication instance. Rebooting results in a momentary outage, until the replication instance becomes available again * * Access Level: Write * * https://docs.aws.amazon.com/dms/latest/APIReference/API_RebootReplicationInstance.html */ public toRebootReplicationInstance() { return this.to('RebootReplicationInstance'); } /** * Grants permission to populate the schema for the specified endpoint * * Access Level: Write * * https://docs.aws.amazon.com/dms/latest/APIReference/API_RefreshSchemas.html */ public toRefreshSchemas() { return this.to('RefreshSchemas'); } /** * Grants permission to reload the target database table with the source data * * Access Level: Write * * https://docs.aws.amazon.com/dms/latest/APIReference/API_ReloadTables.html */ public toReloadTables() { return this.to('ReloadTables'); } /** * Grants permission to remove metadata tags from a DMS resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/dms/latest/APIReference/API_RemoveTagsFromResource.html */ public toRemoveTagsFromResource() { return this.to('RemoveTagsFromResource'); } /** * Grants permission to start the replication task * * Access Level: Write * * https://docs.aws.amazon.com/dms/latest/APIReference/API_StartReplicationTask.html */ public toStartReplicationTask() { return this.to('StartReplicationTask'); } /** * Grants permission to start the replication task assessment for unsupported data types in the source database * * Access Level: Write * * https://docs.aws.amazon.com/dms/latest/APIReference/API_StartReplicationTaskAssessment.html */ public toStartReplicationTaskAssessment() { return this.to('StartReplicationTaskAssessment'); } /** * Grants permission to start a new premigration assessment run for one or more individual assessments of a migration task * * Access Level: Write * * https://docs.aws.amazon.com/dms/latest/APIReference/API_StartReplicationTaskAssessmentRun.html */ public toStartReplicationTaskAssessmentRun() { return this.to('StartReplicationTaskAssessmentRun'); } /** * Grants permission to stop the replication task * * Access Level: Write * * https://docs.aws.amazon.com/dms/latest/APIReference/API_StopReplicationTask.html */ public toStopReplicationTask() { return this.to('StopReplicationTask'); } /** * Grants permission to test the connection between the replication instance and the endpoint * * Access Level: Read * * https://docs.aws.amazon.com/dms/latest/APIReference/API_TestConnection.html */ public toTestConnection() { return this.to('TestConnection'); } protected accessLevelList: AccessLevelList = { "Tagging": [ "AddTagsToResource", "RemoveTagsFromResource" ], "Write": [ "ApplyPendingMaintenanceAction", "CancelReplicationTaskAssessmentRun", "CreateEndpoint", "CreateEventSubscription", "CreateReplicationInstance", "CreateReplicationSubnetGroup", "CreateReplicationTask", "DeleteCertificate", "DeleteConnection", "DeleteEndpoint", "DeleteEventSubscription", "DeleteReplicationInstance", "DeleteReplicationSubnetGroup", "DeleteReplicationTask", "DeleteReplicationTaskAssessmentRun", "ImportCertificate", "ModifyEndpoint", "ModifyEventSubscription", "ModifyReplicationInstance", "ModifyReplicationSubnetGroup", "ModifyReplicationTask", "MoveReplicationTask", "RebootReplicationInstance", "RefreshSchemas", "ReloadTables", "StartReplicationTask", "StartReplicationTaskAssessment", "StartReplicationTaskAssessmentRun", "StopReplicationTask" ], "Read": [ "DescribeAccountAttributes", "DescribeApplicableIndividualAssessments", "DescribeCertificates", "DescribeConnections", "DescribeEndpointSettings", "DescribeEndpointTypes", "DescribeEndpoints", "DescribeEventCategories", "DescribeEventSubscriptions", "DescribeEvents", "DescribeOrderableReplicationInstances", "DescribeRefreshSchemasStatus", "DescribeReplicationInstanceTaskLogs", "DescribeReplicationInstances", "DescribeReplicationSubnetGroups", "DescribeReplicationTaskAssessmentResults", "DescribeReplicationTaskAssessmentRuns", "DescribeReplicationTaskIndividualAssessments", "DescribeReplicationTasks", "DescribeSchemas", "DescribeTableStatistics", "ListTagsForResource", "TestConnection" ] }; /** * Adds a resource of type Certificate to the statement * * https://docs.aws.amazon.com/dms/latest/APIReference/API_Certificate.html * * @param resourceName - Identifier for the resourceName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() * - .ifCertTag() */ public onCertificate(resourceName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:dms:${Region}:${Account}:cert:${ResourceName}'; arn = arn.replace('${ResourceName}', resourceName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type Endpoint to the statement * * https://docs.aws.amazon.com/dms/latest/APIReference/API_Endpoint.html * * @param resourceName - Identifier for the resourceName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() * - .ifEndpointTag() */ public onEndpoint(resourceName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:dms:${Region}:${Account}:endpoint:${ResourceName}'; arn = arn.replace('${ResourceName}', resourceName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type EventSubscription to the statement * * https://docs.aws.amazon.com/dms/latest/APIReference/API_EventSubscription.html * * @param resourceName - Identifier for the resourceName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() * - .ifEsTag() */ public onEventSubscription(resourceName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:dms:${Region}:${Account}:es:${ResourceName}'; arn = arn.replace('${ResourceName}', resourceName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type ReplicationInstance to the statement * * https://docs.aws.amazon.com/dms/latest/APIReference/API_ReplicationInstance.html * * @param resourceName - Identifier for the resourceName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() * - .ifRepTag() */ public onReplicationInstance(resourceName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:dms:${Region}:${Account}:rep:${ResourceName}'; arn = arn.replace('${ResourceName}', resourceName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type ReplicationSubnetGroup to the statement * * https://docs.aws.amazon.com/dms/latest/APIReference/API_ReplicationSubnetGroup.html * * @param resourceName - Identifier for the resourceName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() * - .ifSubgrpTag() */ public onReplicationSubnetGroup(resourceName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:dms:${Region}:${Account}:subgrp:${ResourceName}'; arn = arn.replace('${ResourceName}', resourceName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type ReplicationTask to the statement * * https://docs.aws.amazon.com/dms/latest/APIReference/API_ReplicationTask.html * * @param resourceName - Identifier for the resourceName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() * - .ifTaskTag() */ public onReplicationTask(resourceName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:dms:${Region}:${Account}:task:${ResourceName}'; arn = arn.replace('${ResourceName}', resourceName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type ReplicationTaskAssessmentRun to the statement * * https://docs.aws.amazon.com/dms/latest/APIReference/API_ReplicationTaskAssessmentRun.html * * @param resourceName - Identifier for the resourceName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onReplicationTaskAssessmentRun(resourceName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:dms:${Region}:${Account}:assessment-run:${ResourceName}'; arn = arn.replace('${ResourceName}', resourceName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type ReplicationTaskIndividualAssessment to the statement * * https://docs.aws.amazon.com/dms/latest/APIReference/API_ReplicationTaskIndividualAssessment.html * * @param resourceName - Identifier for the resourceName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onReplicationTaskIndividualAssessment(resourceName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:dms:${Region}:${Account}:individual-assessment:${ResourceName}'; arn = arn.replace('${ResourceName}', resourceName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Filters access based on the presence of tag keys in the request for Certificate * * https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsdatabasemigrationservice.html#awsdatabasemigrationservice--dms_cert-tag___TagKey_ * * Applies to resource types: * - Certificate * * @param tagKey The tag key to check * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifCertTag(tagKey: string, value: string | string[], operator?: Operator | string) { return this.if(`cert-tag/${ tagKey }`, value, operator || 'StringLike'); } /** * Filters access based on the presence of tag keys in the request for Endpoint * * https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsdatabasemigrationservice.html#awsdatabasemigrationservice-dms_endpoint-tag___TagKey_ * * Applies to resource types: * - Endpoint * * @param tagKey The tag key to check * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifEndpointTag(tagKey: string, value: string | string[], operator?: Operator | string) { return this.if(`endpoint-tag/${ tagKey }`, value, operator || 'StringLike'); } /** * Filters access based on the presence of tag keys in the request for EventSubscription * * https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsdatabasemigrationservice.html#awsdatabasemigrationservice-dms_es-tag___TagKey_ * * Applies to resource types: * - EventSubscription * * @param tagKey The tag key to check * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifEsTag(tagKey: string, value: string | string[], operator?: Operator | string) { return this.if(`es-tag/${ tagKey }`, value, operator || 'StringLike'); } /** * Filters access based on the presence of tag keys in the request for ReplicationInstance * * https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsdatabasemigrationservice.html#awsdatabasemigrationservice-dms_rep-tag___TagKey_ * * Applies to resource types: * - ReplicationInstance * * @param tagKey The tag key to check * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifRepTag(tagKey: string, value: string | string[], operator?: Operator | string) { return this.if(`rep-tag/${ tagKey }`, value, operator || 'StringLike'); } /** * Filters access based on the presence of tag key-value pairs in the request * * https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsdatabasemigrationservice.html#awsdatabasemigrationservice-dms_req-tag___TagKey_ * * Applies to actions: * - .toAddTagsToResource() * - .toCreateEndpoint() * - .toCreateEventSubscription() * - .toCreateReplicationInstance() * - .toCreateReplicationSubnetGroup() * - .toCreateReplicationTask() * * @param tagKey The tag key to check * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifReqTag(tagKey: string, value: string | string[], operator?: Operator | string) { return this.if(`req-tag/${ tagKey }`, value, operator || 'StringLike'); } /** * Filters access based on the presence of tag keys in the request for ReplicationSubnetGroup * * https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsdatabasemigrationservice.html#awsdatabasemigrationservice-dms_subgrp-tag___TagKey_ * * Applies to resource types: * - ReplicationSubnetGroup * * @param tagKey The tag key to check * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifSubgrpTag(tagKey: string, value: string | string[], operator?: Operator | string) { return this.if(`subgrp-tag/${ tagKey }`, value, operator || 'StringLike'); } /** * Filters access based on the presence of tag keys in the request for ReplicationTask * * https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsdatabasemigrationservice.html#awsdatabasemigrationservice-dms_task-tag___TagKey_ * * Applies to resource types: * - ReplicationTask * * @param tagKey The tag key to check * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifTaskTag(tagKey: string, value: string | string[], operator?: Operator | string) { return this.if(`task-tag/${ tagKey }`, value, operator || 'StringLike'); } }
the_stack
import { Auth } from '@aws-amplify/auth'; import { Credentials, Logger, Signer } from '@aws-amplify/core'; import { GraphQLError, isCompositeType } from 'graphql'; import Observable from 'zen-observable-ts'; import { AWSAppSyncRealTimeProvider } from '../src/Providers/AWSAppSyncRealTimeProvider'; import Cache from '@aws-amplify/cache'; import { MESSAGE_TYPES } from '../src/Providers/AWSAppSyncRealTimeProvider/constants'; import { FakeWebSocketInterface, delay, replaceConstant } from './helpers'; describe('AWSAppSyncRealTimeProvider', () => { describe('isCustomDomain()', () => { test('Custom domain returns `true`', () => { const provider = new AWSAppSyncRealTimeProvider(); const result = (provider as any).isCustomDomain( 'https://unit-test.testurl.com/graphql' ); expect(result).toBe(true); }); test('Non-custom domain returns `false`', () => { const provider = new AWSAppSyncRealTimeProvider(); const result = (provider as any).isCustomDomain( 'https://12345678901234567890123456.appsync-api.us-west-2.amazonaws.com/graphql' ); expect(result).toBe(false); }); }); describe('newClient()', () => { test('throws an error', () => { const provider = new AWSAppSyncRealTimeProvider(); expect(provider.newClient).toThrow(Error('Not used here')); }); }); describe('getProviderName()', () => { test('returns the provider name', () => { const provider = new AWSAppSyncRealTimeProvider(); expect(provider.getProviderName()).toEqual('AWSAppSyncRealTimeProvider'); }); }); describe('publish()', () => { test("rejects raising an error indicating publish isn't supported", async () => { const provider = new AWSAppSyncRealTimeProvider(); await expect(provider.publish('test', 'test')).rejects.toThrow( Error('Operation not supported') ); }); }); describe('subscribe()', () => { test('returns an observable', () => { const provider = new AWSAppSyncRealTimeProvider(); expect(provider.subscribe('test', {})).toBeInstanceOf(Observable); }); describe('returned observer', () => { describe('connection logic with mocked websocket', () => { let fakeWebSocketInterface: FakeWebSocketInterface; const loggerSpy: jest.SpyInstance = jest.spyOn( Logger.prototype, '_log' ); let provider: AWSAppSyncRealTimeProvider; beforeEach(async () => { fakeWebSocketInterface = new FakeWebSocketInterface(); provider = new AWSAppSyncRealTimeProvider(); // Saving this spy and resetting it by hand causes badness // Saving it causes new websockets to be reachable across past tests that have not fully closed // Resetting it proactively causes those same past tests to be dealing with null while they reach a settled state jest.spyOn(provider, 'getNewWebSocket').mockImplementation(() => { fakeWebSocketInterface.newWebSocket(); return fakeWebSocketInterface.webSocket; }); }); afterEach(async () => { await fakeWebSocketInterface?.closeInterface(); loggerSpy.mockClear(); }); test('returns error when no appSyncGraphqlEndpoint is provided', async () => { expect.assertions(2); const mockError = jest.fn(); const provider = new AWSAppSyncRealTimeProvider(); await Promise.resolve( provider.subscribe('test', {}).subscribe({ error(err) { expect(err.errors[0].message).toEqual( 'Subscribe only available for AWS AppSync endpoint' ); mockError(); }, }) ); expect(mockError).toBeCalled(); }); test('subscription waiting for onopen with ws://localhost:8080 goes untranslated', async () => { expect.assertions(1); const newSocketSpy = jest .spyOn(provider, 'getNewWebSocket') .mockImplementation(() => { fakeWebSocketInterface.newWebSocket(); return fakeWebSocketInterface.webSocket; }); provider .subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', }) .subscribe({}); // Wait for the socket to be initialize await fakeWebSocketInterface.readyForUse; expect(newSocketSpy).toHaveBeenNthCalledWith( 1, 'ws://localhost:8080/realtime?header=IiI=&payload=e30=', 'graphql-ws' ); }); test('subscription waiting for onopen with http://localhost:8080 translates to wss', async () => { expect.assertions(1); const newSocketSpy = jest .spyOn(provider, 'getNewWebSocket') .mockImplementation(() => { fakeWebSocketInterface.newWebSocket(); return fakeWebSocketInterface.webSocket; }); provider .subscribe('test', { appSyncGraphqlEndpoint: 'http://localhost:8080', }) .subscribe({}); // Wait for the socket to be initialize await fakeWebSocketInterface.readyForUse; expect(newSocketSpy).toHaveBeenNthCalledWith( 1, 'wss://localhost:8080/realtime?header=IiI=&payload=e30=', 'graphql-ws' ); }); test('subscription waiting for onopen with https://testaccounturl123456789123.appsync-api.us-east-1.amazonaws.com/graphql" translates to wss', async () => { expect.assertions(1); const newSocketSpy = jest .spyOn(provider, 'getNewWebSocket') .mockImplementation(() => { fakeWebSocketInterface.newWebSocket(); return fakeWebSocketInterface.webSocket; }); provider .subscribe('test', { appSyncGraphqlEndpoint: 'https://testaccounturl123456789123.appsync-api.us-east-1.amazonaws.com/graphql', }) .subscribe({}); // Wait for the socket to be initialize await fakeWebSocketInterface.readyForUse; expect(newSocketSpy).toHaveBeenNthCalledWith( 1, 'wss://testaccounturl123456789123.appsync-realtime-api.us-east-1.amazonaws.com/graphql?header=IiI=&payload=e30=', 'graphql-ws' ); }); test('subscription fails when onerror triggered while waiting for onopen', async () => { expect.assertions(1); provider .subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', }) .subscribe({}); await fakeWebSocketInterface?.readyForUse; await fakeWebSocketInterface?.triggerError(); expect(loggerSpy).toHaveBeenCalledWith( 'DEBUG', 'WebSocket connection error' ); }); test('subscription fails when onclose triggered while waiting for onopen', async () => { expect.assertions(1); provider .subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', }) .subscribe({}); await fakeWebSocketInterface?.readyForUse; await fakeWebSocketInterface?.triggerClose(); await delay(50); // Watching for raised exception to be caught and logged expect(loggerSpy).toBeCalledWith( 'DEBUG', 'error on bound ', expect.objectContaining({ message: expect.stringMatching('Connection handshake error'), }) ); }); test('subscription fails when onerror triggered while waiting for handshake', async () => { expect.assertions(1); provider .subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', }) .subscribe({}); await fakeWebSocketInterface?.readyForUse; await fakeWebSocketInterface?.triggerOpen(); await fakeWebSocketInterface?.triggerError(); // When the socket throws an error during handshake expect(loggerSpy).toHaveBeenCalledWith( 'DEBUG', 'WebSocket error {"isTrusted":false}' ); }); test('subscription fails when onclose triggered while waiting for handshake', async () => { expect.assertions(1); provider .subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', }) .subscribe({}); await fakeWebSocketInterface?.readyForUse; await fakeWebSocketInterface?.triggerOpen(); await fakeWebSocketInterface?.triggerClose(); // When the socket is closed during handshake // Watching for raised exception to be caught and logged expect(loggerSpy).toBeCalledWith( 'DEBUG', 'error on bound ', expect.objectContaining({ message: expect.stringMatching('{"isTrusted":false}'), }) ); }); test('subscription observer is triggered when a connection is formed and a data message is received before connection ack', async () => { expect.assertions(1); const mockNext = jest.fn(); const observer = provider.subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', }); const subscription = observer.subscribe({ // Succeed only when the first message comes through next: mockNext, // Closing a hot connection (for cleanup) makes it blow up the test stack error: () => {}, }); await fakeWebSocketInterface?.standardConnectionHandshake(); await fakeWebSocketInterface?.sendDataMessage({ type: MESSAGE_TYPES.GQL_DATA, payload: { data: {} }, }); expect(mockNext).toBeCalled(); }); test('subscription observer is triggered when a connection is formed and a data message is received after connection ack', async () => { expect.assertions(1); const mockNext = jest.fn(); const observer = provider.subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', }); const subscription = observer.subscribe({ // Succeed only when the first message comes through next: mockNext, // Closing a hot connection (for cleanup) makes it blow up the test stack error: () => {}, }); await fakeWebSocketInterface?.standardConnectionHandshake(); await fakeWebSocketInterface?.sendMessage( new MessageEvent('start_ack', { data: JSON.stringify({ type: MESSAGE_TYPES.GQL_START_ACK, payload: { connectionTimeoutMs: 100 }, }), }) ); await fakeWebSocketInterface?.sendDataMessage({ type: MESSAGE_TYPES.GQL_DATA, payload: { data: {} }, }); expect(mockNext).toBeCalled(); }); test('subscription observer is triggered when a connection is formed and a data message is received after connection ack and close triggered', async () => { expect.assertions(1); const mockNext = jest.fn(); const observer = provider.subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', }); const subscription = observer.subscribe({ // Succeed only when the first message comes through next: mockNext, // Closing a hot connection (for cleanup) makes it blow up the test stack error: () => {}, }); await fakeWebSocketInterface?.standardConnectionHandshake(); await fakeWebSocketInterface?.sendMessage( new MessageEvent('start_ack', { data: JSON.stringify({ type: MESSAGE_TYPES.GQL_START_ACK, payload: { connectionTimeoutMs: 100 }, }), }) ); await fakeWebSocketInterface?.sendDataMessage({ type: MESSAGE_TYPES.GQL_DATA, payload: { data: {} }, }); expect(mockNext).toBeCalled(); }); test('subscription observer error is triggered when a connection is formed and a error data message is received', async () => { // Test for error message path message receipt has nothing to assert (only passes when error triggers error subscription method) expect.assertions(1); const mockError = jest.fn(); const observer = provider.subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', }); const subscription = observer.subscribe({ // Succeed only when the first message comes through error: mockError, }); await fakeWebSocketInterface?.standardConnectionHandshake(); await fakeWebSocketInterface?.sendDataMessage({ type: MESSAGE_TYPES.GQL_ERROR, payload: { data: {} }, }); expect(mockError).toBeCalled(); }); test('subscription observer error is triggered when a connection is formed and a non-retriable connection_error data message is received', async () => { expect.assertions(2); const socketCloseSpy = jest.spyOn( fakeWebSocketInterface.webSocket, 'close' ); fakeWebSocketInterface.webSocket.readyState = WebSocket.OPEN; const observer = provider.subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', }); const subscription = observer.subscribe({ error: x => {}, }); await fakeWebSocketInterface?.readyForUse; await fakeWebSocketInterface?.triggerOpen(); // Resolve the message delivery actions await Promise.resolve( fakeWebSocketInterface?.sendDataMessage({ type: MESSAGE_TYPES.GQL_CONNECTION_ERROR, payload: { errors: [ { errorType: 'Non-retriable Test', errorCode: 400, // Not found - non-retriable }, ], }, }) ); // Watching for raised exception to be caught and logged expect(loggerSpy).toBeCalledWith( 'DEBUG', 'error on bound ', expect.objectContaining({ message: expect.stringMatching('Non-retriable Test'), }) ); expect(socketCloseSpy).toHaveBeenNthCalledWith(1, 3001); }); test('subscription observer error is triggered when a connection is formed', async () => { expect.assertions(1); const observer = provider.subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', }); const subscription = observer.subscribe({ error: x => {}, }); await fakeWebSocketInterface?.standardConnectionHandshake(); await fakeWebSocketInterface?.triggerError(); expect(loggerSpy).toBeCalledWith( 'DEBUG', 'Disconnect error: Connection closed' ); }); test('subscription observer error is triggered when a connection is formed and a retriable connection_error data message is received', async () => { expect.assertions(1); const observer = provider.subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', }); const subscription = observer.subscribe({ error: x => {}, }); await fakeWebSocketInterface?.readyForUse; await fakeWebSocketInterface?.triggerOpen(); // Resolve the message delivery actions await Promise.resolve( fakeWebSocketInterface?.sendDataMessage({ type: MESSAGE_TYPES.GQL_CONNECTION_ERROR, payload: { errors: [ { errorType: 'Retriable Test', errorCode: 408, // Request timed out - retriable }, ], }, }) ); // Watching for raised exception to be caught and logged expect(loggerSpy).toBeCalledWith( 'DEBUG', 'error on bound ', expect.objectContaining({ message: expect.stringMatching('Retriable Test'), }) ); }); test('subscription observer error is triggered when a connection is formed and an ack data message is received then ack timeout prompts disconnect', async () => { expect.assertions(1); const observer = provider.subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', }); const subscription = observer.subscribe({ error: () => {}, }); await fakeWebSocketInterface?.readyForUse; await fakeWebSocketInterface?.triggerOpen(); // Resolve the message delivery actions await Promise.resolve( fakeWebSocketInterface?.sendMessage( new MessageEvent('connection_ack', { data: JSON.stringify({ type: MESSAGE_TYPES.GQL_CONNECTION_ACK, payload: { connectionTimeoutMs: 20 }, }), }) ) ); await fakeWebSocketInterface?.sendDataMessage({ type: MESSAGE_TYPES.GQL_CONNECTION_KEEP_ALIVE, payload: { data: {} }, }); // Now wait for the timeout to elapse await delay(100); expect(loggerSpy).toBeCalledWith( 'DEBUG', 'Disconnect error: Timeout disconnect' ); }); test('socket is closed when subscription is closed', async () => { expect.assertions(1); const observer = provider.subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', }); const subscription = observer.subscribe({}); await fakeWebSocketInterface?.standardConnectionHandshake(); await fakeWebSocketInterface?.sendDataMessage({ type: MESSAGE_TYPES.GQL_DATA, payload: { data: {} }, }); await subscription.unsubscribe(); await fakeWebSocketInterface?.triggerClose(); expect(fakeWebSocketInterface.hasClosed).resolves.toBeUndefined(); }); test('failure to ack before timeout', async () => { expect.assertions(1); await replaceConstant('START_ACK_TIMEOUT', 20, async () => { const observer = provider.subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', }); const subscription = observer.subscribe({ error: () => {}, }); await fakeWebSocketInterface?.standardConnectionHandshake(); // Wait long enough that the shortened timeout will elapse await delay(100); expect(loggerSpy).toBeCalledWith( 'DEBUG', 'timeoutStartSubscription', expect.anything() ); }); }); test('connection init timeout', async () => { expect.assertions(1); await replaceConstant('CONNECTION_INIT_TIMEOUT', 20, async () => { const observer = provider.subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', }); const subscription = observer.subscribe({ error: () => {}, }); await fakeWebSocketInterface?.readyForUse; await fakeWebSocketInterface?.triggerOpen(); // Wait long enough that the shortened timeout will elapse await delay(100); // Watching for raised exception to be caught and logged expect(loggerSpy).toBeCalledWith( 'DEBUG', 'error on bound ', expect.objectContaining({ message: expect.stringMatching( 'Connection timeout: ack from AWSRealTime' ), }) ); }); }); describe('constructed against the different auth interfaces', () => { test('authenticating with API_KEY', async () => { expect.assertions(1); const subscription = provider .subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', authenticationType: 'API_KEY', }) .subscribe({}); await fakeWebSocketInterface?.readyForUse; expect(loggerSpy).toBeCalledWith( 'DEBUG', 'Authenticating with API_KEY' ); }); test('authenticating with AWS_IAM', async () => { expect.assertions(1); jest.spyOn(Credentials, 'get').mockResolvedValue({}); jest.spyOn(Signer, 'sign').mockImplementation(() => { return { headers: { accept: 'application/json, text/javascript', 'content-encoding': 'amz-1.0', 'content-type': 'application/json; charset=UTF-8', }, }; }); const subscription = provider .subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', authenticationType: 'AWS_IAM', }) .subscribe({}); await fakeWebSocketInterface?.readyForUse; expect(loggerSpy).toBeCalledWith( 'DEBUG', 'Authenticating with AWS_IAM' ); }); test('authenticating with AWS_IAM without credentials', async () => { expect.assertions(1); jest.spyOn(Credentials, 'get').mockImplementation(() => { return Promise.resolve(); }); jest.spyOn(Signer, 'sign').mockImplementation(() => { return { headers: { accept: 'application/json, text/javascript', 'content-encoding': 'amz-1.0', 'content-type': 'application/json; charset=UTF-8', }, }; }); const subscription = provider .subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', authenticationType: 'AWS_IAM', }) .subscribe({ error: e => { expect(e).toEqual({ errors: [ { message: 'AppSync Realtime subscription init error: Error: No credentials', }, ], }); }, }); }); test('authenticating with AWS_IAM with credentials exception', async () => { expect.assertions(2); jest.spyOn(Credentials, 'get').mockImplementation(() => { return Promise.reject('Errors out'); }); jest.spyOn(Signer, 'sign').mockImplementation(() => { return { headers: { accept: 'application/json, text/javascript', 'content-encoding': 'amz-1.0', 'content-type': 'application/json; charset=UTF-8', }, }; }); const subscription = provider .subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', authenticationType: 'AWS_IAM', }) .subscribe({ error: e => { expect(e).toEqual({ errors: [ { message: 'AppSync Realtime subscription init error: Error: No credentials', }, ], }); }, }); // It takes time for the credentials to resolve await delay(50); expect(loggerSpy).toHaveBeenCalledWith( 'WARN', 'ensure credentials error', 'Errors out' ); }); test('authenticating with OPENID_CONNECT', async () => { expect.assertions(1); const userSpy = jest .spyOn(Auth, 'currentAuthenticatedUser') .mockImplementation(() => { return Promise.resolve({ token: 'test', }); }); const subscription = provider .subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', authenticationType: 'OPENID_CONNECT', }) .subscribe({}); await fakeWebSocketInterface?.readyForUse; expect(loggerSpy).toBeCalledWith( 'DEBUG', 'Authenticating with OPENID_CONNECT' ); }); test('authenticating with OPENID_CONNECT with empty token', async () => { expect.assertions(1); const userSpy = jest .spyOn(Auth, 'currentAuthenticatedUser') .mockImplementation(() => { return Promise.resolve({ token: undefined, }); }); const subscription = provider .subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', authenticationType: 'OPENID_CONNECT', }) .subscribe({ error: e => { expect(e).toEqual({ errors: [ { message: 'AppSync Realtime subscription init error: Error: No federated jwt', }, ], }); }, }); }); test('authenticating with OPENID_CONNECT from cached token', async () => { expect.assertions(1); const userSpy = jest .spyOn(Cache, 'getItem') .mockImplementation(() => { return Promise.resolve({ token: 'test', }); }); const subscription = provider .subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', authenticationType: 'OPENID_CONNECT', }) .subscribe({}); await fakeWebSocketInterface?.readyForUse; expect(loggerSpy).toBeCalledWith( 'DEBUG', 'Authenticating with OPENID_CONNECT' ); }); test('authenticating with AMAZON_COGNITO_USER_POOLS', async () => { expect.assertions(1); const sessionSpy = jest .spyOn(Auth, 'currentSession') .mockImplementation(() => { return Promise.resolve({ getAccessToken: () => { return { getJwtToken: () => {}, }; }, } as any); }); const subscription = provider .subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', authenticationType: 'AMAZON_COGNITO_USER_POOLS', }) .subscribe({}); await fakeWebSocketInterface?.readyForUse; expect(loggerSpy).toBeCalledWith( 'DEBUG', 'Authenticating with AMAZON_COGNITO_USER_POOLS' ); }); test('authenticating with AWS_LAMBDA', async () => { expect.assertions(1); const subscription = provider .subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', authenticationType: 'AWS_LAMBDA', additionalHeaders: { Authorization: 'test', }, }) .subscribe({}); await fakeWebSocketInterface?.readyForUse; expect(loggerSpy).toBeCalledWith( 'DEBUG', 'Authenticating with AWS_LAMBDA' ); }); test('authenticating with AWS_LAMBDA without Authorization', async () => { expect.assertions(1); const subscription = provider .subscribe('test', { appSyncGraphqlEndpoint: 'ws://localhost:8080', authenticationType: 'AWS_LAMBDA', additionalHeaders: { Authorization: undefined, }, }) .subscribe({ error: e => { expect(e).toEqual({ errors: [ { message: 'AppSync Realtime subscription init error: Error: No auth token specified', }, ], }); }, }); }); }); }); }); }); });
the_stack
import React from 'react'; import styles from './bannerSVG.module.less'; interface BannerSVGProps { play: boolean; } const BannerSVG = (props: BannerSVGProps) => { const block6NodeRadius = '2'; const block6CirclePositions = [ { x: 36.8, y: 49.8 }, //A { x: 66.8, y: 29.8 }, //B { x: 84.8, y: 29.8 }, //C { x: 101.8, y: 36.8 }, //D { x: 29.8, y: 66.8 }, //E { x: 49.8, y: 36.8 }, //F { x: 114.8, y: 49.8 }, //G { x: 121.8, y: 66.8 }, //H { x: 29.8, y: 84.8 }, //I { x: 36.8, y: 101.8 }, //J { x: 101.8, y: 114.8 }, //K { x: 121.8, y: 84.8 }, //L { x: 49.8, y: 115.8 }, //M { x: 66.8, y: 121.8 }, //N { x: 84.8, y: 121.8 }, //O { x: 114.8, y: 101.8 }, //P ]; const block6GridPositions = [ { x: 45.5, y: 45.5 }, //A { x: 65.5, y: 45.5 }, //B { x: 85.5, y: 45.5 }, //C { x: 105.5, y: 45.5 }, //D { x: 45.5, y: 65.5 }, //E { x: 65.5, y: 65.5 }, //F { x: 85.5, y: 65.5 }, //G { x: 105.5, y: 65.5 }, //H { x: 45.5, y: 85.5 }, //I { x: 65.5, y: 85.5 }, //J { x: 85.5, y: 85.5 }, //K { x: 105.5, y: 85.5 }, //L { x: 45.5, y: 105.5 }, //M { x: 65.5, y: 105.5 }, //N { x: 85.5, y: 105.5 }, //O { x: 105.5, y: 105.5 }, //P ]; const labels = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', ]; const fills = [ 'rgb(180, 100, 254)', //A 'rgb(163, 89, 254)', //B 'rgb(141, 76, 254)', //C 'rgb(120, 64, 254)', //D 'rgb(205, 114, 254)', //E 'rgb(185, 103, 254)', //F 'rgb(159, 87, 254)', //G 'rgb(140, 78, 254)', //H 'rgb(224, 126, 254)', //I 'rgb(202, 114, 254)', //J 'rgb(179, 100, 254)', //K 'rgb(164, 92, 254)', //L 'rgb(248, 141, 254)', //M 'rgb(223, 126, 254)', //N 'rgb(201, 112, 254)', //O 'rgb(180, 101, 254)', //P ]; const getBlock6Circles = () => { const circles = labels.map((label, i) => { const beginx = block6GridPositions[i].x; const beginy = block6GridPositions[i].y; const classname = `block6Circle${label}`; return ( <circle id={`block6-circle-${label}`} className={props.play ? styles[classname] : 'block6CircleStatic'} key={label} fill={fills[i]} cx={beginx} cy={beginy} r={block6NodeRadius} ></circle> ); }); return circles; }; const hoverAnimate = false; const mouseEnterBlock1 = () => { if (hoverAnimate) { for (let i = 1; i <= 5; i++) { const circleShadow = document.getElementById( `block1-circle${i}-shadow`, ); const circle = document.getElementById(`block1-circle${i}-object`); circleShadow && circleShadow.setAttribute( 'class', styles[`block1Circle${i}Infinite`], ); circle && circle.setAttribute('class', styles[`block1Circle${i}Infinite`]); } } }; const mouseOutBlock1 = () => { if (hoverAnimate) { for (let i = 1; i <= 5; i++) { const circleShadow = document.getElementById( `block1-circle${i}-shadow`, ); const circle = document.getElementById(`block1-circle${i}-object`); circleShadow && circleShadow.setAttribute('class', ''); //styles[`block1Circle${i}`] circle && circle.setAttribute('class', ''); //styles[`block1Circle${i}`] } } }; const mouseEnterBlock2 = () => { if (hoverAnimate) { for (let i = 1; i <= 4; i++) { const bar = document.getElementById(`block2-bar${i}`); bar && bar.setAttribute('class', styles[`block2Bar${i}Infinite`]); } } }; const mouseOutBlock2 = () => { if (hoverAnimate) { for (let i = 1; i <= 4; i++) { const bar = document.getElementById(`block2-bar${i}`); bar && bar.setAttribute('class', ''); // styles[`block2Bar${i}Infinite`] } } }; const mouseEnterBlock3 = () => { if (hoverAnimate) { if (hoverAnimate) { const bigArc = document.getElementById('block3-arc-big'); const smallArc = document.getElementById('block3-arc-small'); bigArc && bigArc.setAttribute('class', styles.block3ArcBigInfinite); smallArc && smallArc.setAttribute('class', styles.block3ArcSmallInfinite); } } }; const mouseOutBlock3 = () => { if (hoverAnimate) { const bigArc = document.getElementById('block3-arc-big'); const smallArc = document.getElementById('block3-arc-small'); bigArc && bigArc.setAttribute('class', ''); smallArc && smallArc.setAttribute('class', ''); } }; const mouseEnterBlock4 = () => { if (hoverAnimate) { const verti = document.getElementById('block4-back-line-verti'); const hori = document.getElementById('block4-back-line-hori'); const circle = document.getElementById('block4-back-circle'); verti && verti.setAttribute('class', styles.block4LineVertiInfinite); hori && hori.setAttribute('class', styles.block4LineHoriInfinite); circle && circle.setAttribute('class', styles.block4CircleInfinite); } }; const mouseOutBlock4 = () => { if (hoverAnimate) { const verti = document.getElementById('block4-back-line-verti'); const hori = document.getElementById('block4-back-line-hori'); const circle = document.getElementById('block4-back-circle'); verti && verti.setAttribute('class', ''); hori && hori.setAttribute('class', ''); circle && circle.setAttribute('class', ''); } }; const mouseEnterBlock5 = () => { if (hoverAnimate) { const fan = document.getElementById('block5-fan'); fan && fan.setAttribute('class', styles.block5FanInfinite); } }; const mouseOutBlock5 = () => { if (hoverAnimate) { const fan = document.getElementById('block5-fan'); fan && fan.setAttribute('class', styles.block5Fan); } }; const mouseEnterBlock6 = () => { if (hoverAnimate) { labels.forEach((label) => { const circle = document.getElementById(`block6-circle-${label}`); circle && circle.setAttribute('class', styles[`block6Circle${label}Infinite`]); }); const container = document.getElementById('block6-nodes'); container && container.setAttribute('class', styles.block6NodesContainerInfinite); } }; const mouseOutBlock6 = () => { if (hoverAnimate) { labels.forEach((label) => { const circle = document.getElementById(`block6-circle-${label}`); circle && circle.setAttribute('class', ''); }); const container = document.getElementById('block6-nodes'); container && container.setAttribute('class', ''); } }; const mouseEnterBlock7 = () => { if (hoverAnimate) { const curve = document.getElementById('block7-curve'); curve && curve.setAttribute('class', styles.block7CurveInfinite); } }; const mouseOutBlock7 = () => { if (hoverAnimate) { const curve = document.getElementById('block7-curve'); curve && curve.setAttribute('class', ''); } }; const mouseEnterBlock8 = () => { if (hoverAnimate) { for (let i = 1; i <= 3; i++) { const bar = document.getElementById(`block8-bar${i}`); bar && bar.setAttribute('class', styles[`block8Bar${i}Infinite`]); } } }; const mouseOutBlock8 = () => { if (hoverAnimate) { for (let i = 1; i <= 3; i++) { const bar = document.getElementById(`block8-bar${i}`); bar && bar.setAttribute('class', ''); } } }; return ( <section className={styles.wrapper}> <svg width="130%" height="130%" viewBox="-50 -50 751 587" version="1.1"> <defs> <linearGradient x1="0%" y1="0%" x2="100%" y2="100%" id="back-rect1-gradient" > <stop stopColor="#F0EFFD" offset="0%"></stop> <stop stopColor="#F9F8FF" offset="100%"></stop> </linearGradient> <rect id="path-5" x="39" y="0" width="24" height="24"></rect> <linearGradient x1="0%" y1="0%" x2="100%" y2="0%" id="linearGradient-27" > <stop stopColor="#3EB0FF" offset="0%"></stop> <stop stopColor="#00FF97" offset="100%"></stop> </linearGradient> <linearGradient x1="0%" y1="0%" x2="100%" y2="0%" id="linearGradient-28" > <stop stopColor="#3EB0FF" offset="0%"></stop> <stop stopColor="#00FF97" offset="100%"></stop> </linearGradient> <linearGradient x1="0%" y1="0%" x2="100%" y2="0%" id="linearGradient-29" > <stop stopColor="#3EB0FF" offset="0%"></stop> <stop stopColor="#00FF97" offset="100%"></stop> </linearGradient> <linearGradient x1="0%" y1="0%" x2="100%" y2="0%" id="linearGradient-30" > <stop stopColor="#3EB0FF" offset="0%"></stop> <stop stopColor="#00FF97" offset="100%"></stop> </linearGradient> <linearGradient x1="100%" y1="98.9231419%" x2="100%" y2="0%" id="linearGradient-35" > <stop stopColor="#79FFEF" offset="0%"></stop> <stop stopColor="#35FFAD" offset="100%"></stop> </linearGradient> <linearGradient x1="100%" y1="98.9231419%" x2="100%" y2="0%" id="linearGradient-36" > <stop stopColor="#79FFEF" offset="0%"></stop> <stop stopColor="#35FFAD" offset="100%"></stop> </linearGradient> <linearGradient x1="100%" y1="98.9231419%" x2="100%" y2="0%" id="linearGradient-37" > <stop stopColor="#79FFEF" offset="0%"></stop> <stop stopColor="#35FFAD" offset="100%"></stop> </linearGradient> <circle id="path-41" cx="65.5" cy="65.5" r="32.5"></circle> <linearGradient x1="50%" y1="3.85364977%" x2="50%" y2="89.6029946%" id="linearGradient-50" > <stop stopColor="rgba(255, 255, 255, 0.12)" offset="0%"></stop> <stop stopColor="rgba(255, 255, 255, 0.12)" offset="100%"></stop> </linearGradient> <linearGradient x1="100%" y1="50%" x2="0%" y2="50%" id="linearGradient-51" > <stop stopColor="rgba(255, 255, 255, 0.12)" offset="0%"></stop> <stop stopColor="rgba(255, 255, 255, 0.12)" offset="100%"></stop> </linearGradient> <linearGradient x1="85.7700904%" y1="92.3103523%" x2="0%" y2="34.9608269%" id="linearGradient-52" > <stop stopColor="rgba(255, 255, 255, 0.12)" offset="0%"></stop> <stop stopColor="rgba(255, 255, 255, 0.12)" offset="100%"></stop> </linearGradient> <linearGradient x1="50%" y1="100%" x2="50%" y2="0%" id="linearGradient-53" > <stop stopColor="#FF41F9" offset="0%"></stop> <stop stopColor="#00FFCA" offset="100%"></stop> </linearGradient> <path d="M63,34 C74.045695,34 83,42.954305 83,54 C83,61.3637967 76.3333333,71.3637967 63,84 C49.6666667,71.3637967 43,61.3637967 43,54 C43,42.954305 51.954305,34 63,34 Z M63,39.8333333 C55.175966,39.8333333 48.8333333,46.1480369 48.8333333,53.9376185 C48.8333333,58.572673 53.4703894,66.0292388 63,75.6666667 L63,75.6666667 L63.4297955,75.230106 C72.669063,65.80393 77.1666667,58.5024449 77.1666667,53.9376185 C77.1666667,46.1480369 70.824034,39.8333333 63,39.8333333 Z M63,47 C66.3137085,47 69,49.6862915 69,53 C69,56.3137085 66.3137085,59 63,59 C59.6862915,59 57,56.3137085 57,53 C57,49.6862915 59.6862915,47 63,47 Z" id="path-54" ></path> <linearGradient id="arc-gradient1" x1="0" x2="0.3" y1="0" y2="1" gradientTransform="rotate(-90)" > <stop offset="0%" stopColor="rgb(154, 104, 255)" stopOpacity="1" />\ <stop offset="100%" stopColor="rgb(255, 145, 253)" stopOpacity="1" /> </linearGradient> <linearGradient id="arc-gradient2" x1="0" x2="0" y1="0" y2="1" gradientTransform="rotate(30)" > <stop offset="0%" stopColor="rgb(68, 17, 215)" stopOpacity="0.16" /> <stop offset="100%" stopColor="rgb(230, 54, 255)" stopOpacity="1" /> </linearGradient> <filter id="arc-filter1" x="-100%" y="-100%" width="400%" height="400%" > <feOffset result="offOut" in="SourceGraphic" dx="-5" dy="-5" /> <feColorMatrix result="matrixOut" in="offOut" type="matrix" values="0.463 0 0 0 0 0 0.110 0 0 0 0 0 0.922 0 0 0 0 0 0.2 0" /> <feGaussianBlur result="blurOut" in="matrixOut" stdDeviation="20" /> <feBlend in="SourceGraphic" in2="blurOut" mode="normal" /> </filter> <filter id="arc-filter2" x="-50%" y="-50%" width="250%" height="250%"> <feOffset result="offOut" in="SourceGraphic" dx="5" dy="5" /> <feGaussianBlur result="blurOut" in="offOut" stdDeviation="10" /> <feBlend in="SourceGraphic" in2="blurOut" mode="normal" /> </filter> <filter x="-300.0%" y="-220.0%" width="700.0%" height="700.0%" filterUnits="objectBoundingBox" id="filter-81" > <feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1" ></feMorphology> <feOffset dx="0" dy="4" in="shadowSpreadOuter1" result="shadowOffsetOuter1" ></feOffset> <feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1" ></feGaussianBlur> <feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1" ></feComposite> <feColorMatrix values="0 0 0 0 0.538230561 0 0 0 0 0.163202963 0 0 0 0 0.817963089 0 0 0 0.229758523 0" type="matrix" in="shadowBlurOuter1" ></feColorMatrix> </filter> <filter x="-300.0%" y="-220.0%" width="700.0%" height="700.0%" filterUnits="objectBoundingBox" id="filter-83" > <feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1" ></feMorphology> <feOffset dx="0" dy="4" in="shadowSpreadOuter1" result="shadowOffsetOuter1" ></feOffset> <feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1" ></feGaussianBlur> <feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1" ></feComposite> <feColorMatrix values="0 0 0 0 0.538230561 0 0 0 0 0.163202963 0 0 0 0 0.817963089 0 0 0 0.229758523 0" type="matrix" in="shadowBlurOuter1" ></feColorMatrix> </filter> <filter x="-300.0%" y="-220.0%" width="700.0%" height="700.0%" filterUnits="objectBoundingBox" id="filter-85" > <feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1" ></feMorphology> <feOffset dx="0" dy="4" in="shadowSpreadOuter1" result="shadowOffsetOuter1" ></feOffset> <feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1" ></feGaussianBlur> <feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1" ></feComposite> <feColorMatrix values="0 0 0 0 0.538230561 0 0 0 0 0.163202963 0 0 0 0 0.817963089 0 0 0 0.229758523 0" type="matrix" in="shadowBlurOuter1" ></feColorMatrix> </filter> <filter x="-300.0%" y="-220.0%" width="700.0%" height="700.0%" filterUnits="objectBoundingBox" id="filter-87" > <feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1" ></feMorphology> <feOffset dx="0" dy="4" in="shadowSpreadOuter1" result="shadowOffsetOuter1" ></feOffset> <feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1" ></feGaussianBlur> <feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1" ></feComposite> <feColorMatrix values="0 0 0 0 0.538230561 0 0 0 0 0.163202963 0 0 0 0 0.817963089 0 0 0 0.229758523 0" type="matrix" in="shadowBlurOuter1" ></feColorMatrix> </filter> <filter x="-300.0%" y="-220.0%" width="700.0%" height="700.0%" filterUnits="objectBoundingBox" id="filter-89" > <feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1" ></feMorphology> <feOffset dx="0" dy="4" in="shadowSpreadOuter1" result="shadowOffsetOuter1" ></feOffset> <feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1" ></feGaussianBlur> <feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1" ></feComposite> <feColorMatrix values="0 0 0 0 0.538230561 0 0 0 0 0.163202963 0 0 0 0 0.817963089 0 0 0 0.229758523 0" type="matrix" in="shadowBlurOuter1" ></feColorMatrix> </filter> <radialGradient id="block5-gradient" fx="50%" fy="50%" cx="50%" cy="50%" r="90%" > <stop stopOpacity="1" stopColor="#FFDBB8" offset="0%" /> <stop stopOpacity="1" stopColor="#FFD341" offset="100%" /> </radialGradient> <filter id="rect-shadow" x="-50%" y="-50%" width="300%" height="300%"> <feOffset result="offOut" in="SourceGraphic" dx="10" dy="10" /> <feColorMatrix result="matrixOut" in="offOut" type="matrix" values="0.192 0 0 0 0 0 0.275 0 0 0 0 0 0.349 0 0 0 0 0 0.1 0" /> <feGaussianBlur result="blurOut" in="matrixOut" stdDeviation="10" /> <feBlend in="SourceGraphic" in2="blurOut" mode="normal" /> </filter> </defs> <g id="Ant-V-PC-定稿-1101" transform="translate(-711.000000, -100.000000)" stroke="none" strokeWidth="1" fill="none" fillRule="evenodd" > <g id="banner-svg" transform="translate(779.000000, 127.000000)"> <g id="backs" transform="translate(209.000000, 0.000000)"> <rect id="back-lefttop-small" stroke="#EBE1FB" opacity="0.503348214" x="257.5" y="145.5" width="206" height="172" transform="translate(-90.000000, -150.000000)" ></rect> <rect id="back-righttop" stroke="#EBE1FB" opacity="0.293619792" x="235.5" y="0.5" width="527" height="451" transform="translate(-320.000000, -180.000000)" ></rect> <path id="back-fan" d="M0.500015456,334.512545 L0.507890624,586.5 L252.499521,586.5 C252.235652,448.831454 143.017682,336.763448 7.1430388,334.533878 L3.01314849,334.5 C2.17494966,334.5 1.33723221,334.504183 0.500015456,334.512545 Z" stroke="#EBE1FB" opacity="0.503348214" transform="translate(-285.000000, -172.000000)" ></path> <image xlinkHref="https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*aRK0RKcWMzEAAAAAAAAAAABkARQnAQ" width="120px" height="120px" x="0px" y="350px" /> <rect id="back-rect1" fill="url(#back-rect1-gradient)" x="290" y="424" width="21" height="21" > <animate attributeName="y" from="424" to="424" begin="0s" dur="10s" values="424;440;424" keySplines="0.5 0.8 0.6 1; 0.5 0.8 0.6 1;" keyTimes="0;0.5;1" calcMode="spline" repeatCount="indefinite" /> </rect> <rect id="back-rect2" fill="#ffffff" filter="url(#rect-shadow)" x="312" y="445" width="28" height="28" > <animate attributeName="y" from="445" to="445" begin="0s" dur="10s" values="445;430;445" keySplines="0.5 0.8 0.6 1; 0.5 0.8 0.6 1;" keyTimes="0;0.5;1" calcMode="spline" repeatCount="indefinite" /> </rect> <circle id="back-circle" fill="#EEEBFD" cx="205.5" cy="431.5" r="1.5" ></circle> <rect id="back-rect-top" fill="#ffffff" filter="url(#rect-shadow)" x="39" y="0" width="24" height="24" > <animate attributeName="y" from="0" to="0" begin="0s" dur="8s" values="0;20;0" keySplines="0.5 0.8 0.6 1; 0.5 0.8 0.6 1;" keyTimes="0;0.5;1" calcMode="spline" repeatCount="indefinite" /> </rect> </g> <g id="block6" transform="translate(131.000000, 218.000000)"> <image id="block6Back" xlinkHref="https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*zzQTRZPLhIgAAAAAAAAAAABkARQnAQ" width="265px" height="265px" x="-56px" y="-35px" /> <g id="block6-nodes" className={ props.play ? styles.block6NodesContainer : 'block6NodesContainerStatic' } > {getBlock6Circles()} </g> </g> <g id="block2" transform="translate(185.000000, 118.000000)"> <image id="block2Back" xlinkHref="https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*JikGQZ3gmKsAAAAAAAAAAABkARQnAQ" width="236px" height="236px" x="-69px" y="-30px" /> <g id="block2-bars" transform="translate(25.000000, 27.000000)"> <rect id="block2-bar1" className={ props.play ? styles.block2Bar1 : 'block2Bar1Static' } fill="url(#linearGradient-27)" x="0" y="0" width="27" height="6" ></rect> <rect id="block2-bar2" className={ props.play ? styles.block2Bar2 : 'block2Bar2Static' } fill="url(#linearGradient-28)" x="0" y="12" width="44" height="6" ></rect> <rect id="block2-bar3" className={ props.play ? styles.block2Bar3 : 'block2Bar3Static' } fill="url(#linearGradient-29)" x="0" y="24" width="17" height="6" ></rect> <rect id="block2-bar4" className={ props.play ? styles.block2Bar4 : 'block2Bar4Static' } fill="url(#linearGradient-30)" x="0" y="36" width="34" height="6" ></rect> </g> </g> <g id="block8" transform="translate(385.000000, 218.000000)"> <image id="block8-back" xlinkHref="https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*Vo-SR4jzAy8AAAAAAAAAAABkARQnAQ" width="235px" height="235px" x="-55px" y="-40px" /> <g id="block8-bars" transform="translate(54.000000, 40.000000)"> <rect id="block8-bar2" className={ props.play ? styles.block8Bar2 : 'block8Bar2Static' } fill="url(#linearGradient-35)" x="12" y="0" width="6" height="33.75" ></rect> <rect id="block8-bar1" className={ props.play ? styles.block8Bar1 : 'block8Bar1Static' } fill="url(#linearGradient-36)" x="0" y="10" width="6" height="23.75" ></rect> <rect id="block8-bar3" className={ props.play ? styles.block8Bar3 : 'block8Bar3Static' } fill="url(#linearGradient-37)" x="24" y="17" width="6" height="16.875" ></rect> </g> </g> <g id="block5" transform="translate(0.000000, 218.000000)"> <image id="block5Back" xlinkHref="https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*KpT9QrpQ4ZgAAAAAAAAAAABkARQnAQ" width="268px" height="268px" x="-69px" y="-30px" /> <g id="block5-circle" opacity="0.326241629"> <use fill="#F4E7FF" fillRule="evenodd" xlinkHref="#path-41" ></use> </g> <path id="block5-fan" className={props.play ? styles.block5Fan : 'block5FanStatic'} stroke="url(#block5-gradient)" strokeWidth="32.5" strokeDasharray="207.24" strokeDashoffset="193.5" // d="M65.5,49 C74.336556,49 81.5,56.3873016 81.5,65.5 C81.5,70.0566032 79.7089393,74.1818092 76.8132242,77.1677613" ></path> </g> <g id="block4" transform="translate(439.000000, 92.000000)"> <image id="block4Back" xlinkHref="https://gw.alipayobjects.com/zos/antfincdn/p%24tXf8w8p5/location.png" width="260px" height="260px" x="-68px" y="-29px" /> <g id="block4-front-back" mask="url(#mask-47)"> <g transform="translate(64.994468, 55.918147) rotate(10.000000) translate(-64.994468, -55.918147) translate(-40.505532, -50.081853)"> <rect id="block4-back-line-verti" className={ props.play ? styles.block4LineVerti : 'block4LineVertiStatic' } fill="url(#linearGradient-50)" x="64" y="20" width="4" height="192" ></rect> <rect id="block4-back-line-hori" className={ props.play ? styles.block4LineHori : 'block4LineHoriStatic' } fill="url(#linearGradient-51)" x="-1.36424205e-11" y="151" width="202" height="4" ></rect> <path id="block4-back-circle" className={ props.play ? styles.block4Circle : 'block4CircleStatic' } stroke="url(#linearGradient-52)" opacity="0.545549665" strokeDasharray="132" strokeWidth="5" d="M111.248537,49.2552483 C107.33563,82.1953597 146.587514,105.361957 164.688607,98.6513257" ></path> </g> </g> </g> <g id="blcok7" transform="translate(285.000000, 218.000000)"> <image id="block7-back" xlinkHref="https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*62E-Qa78EmMAAAAAAAAAAABkARQnAQ" width="235px" height="235px" x="-68px" y="-30px" /> <path id="block7-curve" className={ props.play ? styles.block7Curve : 'block7CurveStatic' } strokeDasharray="90" d="M36,65 C52.5685425,65 66,51.5685425 66,35" stroke="#9655FE" ></path> </g> <g id="block3" transform="translate(285.000000, 64.000000)"> <image id="block3Back" xlinkHref="https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*6vbkRapOLegAAAAAAAAAAABkARQnAQ" width="250px" height="250px" x="-48px" y="-22px" /> <g id="block3-arcs" transform="translate(33.000000, 33.000000)"> <circle id="block3-arc-big" className={ props.play ? styles.block3ArcBig : 'block3ArcBigStatic' } fill="none" stroke="url(#arc-gradient1)" filter="url(#arc-filter1)" strokeWidth="18" strokeMiterlimit="1" cx="45" cy="45" r="35" strokeDasharray="201" strokeDashoffset="36" transform="rotate(-180 45 45)" ></circle> <circle id="block3-arc-small" className={ props.play ? styles.block3ArcSmall : 'block3ArcSmallStatic' } fill="none" stroke="url(#arc-gradient2)" filter="url(#arc-filter2)" strokeWidth="13" strokeMiterlimit="1" cx="45" cy="45" r="25" strokeDasharray="123.6 1000" strokeDashoffset="6" transform="rotate(0 45 45)" ></circle> </g> </g> <g id="block1" transform="translate(63.000000, 96.000000)"> <image id="block1Back" xlinkHref="https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*AtjkSai-KUAAAAAAAAAAAABkARQnAQ" width="216px" height="216px" x="-48px" y="-21px" /> <g id="block1-circles" transform="translate(27.000000, 34.000000)" onMouseEnter={mouseEnterBlock1} onMouseOut={mouseOutBlock1} > <circle id="block1-circle1-shadow" className={ props.play ? styles.block1Circle1 : 'block1Circle1Static' } filter="url(#filter-81)" stroke="#8D3FFD" strokeWidth="1" fill="#FFFFFF" fillRule="evenodd" cx="2.5" cy="30" r="3" ></circle> <circle id="block1-circle1-object" className={ props.play ? styles.block1Circle1 : 'block1Circle1Static' } stroke="#8D3FFD" strokeWidth="1" fill="#FFFFFF" fillRule="evenodd" cx="2.5" cy="30" r="3" ></circle> <circle id="block1-circle2-shadow" className={ props.play ? styles.block1Circle2 : 'block1Circle2Static' } filter="url(#filter-83)" stroke="#8D3FFD" strokeWidth="1" fill="#FFFFFF" fillRule="evenodd" cx="18.5" cy="15" r="3" ></circle> <circle id="block1-circle2-object" className={ props.play ? styles.block1Circle2 : 'block1Circle2Static' } stroke="#8D3FFD" strokeWidth="1" fill="#FFFFFF" fillRule="evenodd" cx="18.5" cy="15" r="3" ></circle> <circle id="block1-circle3-shadow" className={ props.play ? styles.block1Circle3 : 'block1Circle3Static' } filter="url(#filter-85)" stroke="#8D3FFD" strokeWidth="1" fill="#FFFFFF" fillRule="evenodd" cx="34.5" cy="30" r="3" ></circle> <circle id="block1-circle3-object" className={ props.play ? styles.block1Circle3 : 'block1Circle3Static' } stroke="#8D3FFD" strokeWidth="1" fill="#FFFFFF" fillRule="evenodd" cx="34.5" cy="30" r="3" ></circle> <circle id="block1-circle4-shadow" className={ props.play ? styles.block1Circle4 : 'block1Circle4Static' } filter="url(#filter-87)" stroke="#8D3FFD" strokeWidth="1" fill="#FFFFFF" fillRule="evenodd" cx="50.5" cy="45" r="3" ></circle> <circle id="block1-circle4-object" className={ props.play ? styles.block1Circle4 : 'block1Circle4Static' } stroke="#8D3FFD" strokeWidth="1" fill="#FFFFFF" fillRule="evenodd" cx="50.5" cy="45" r="3" ></circle> <circle id="block1-circle5-shadow" className={ props.play ? styles.block1Circle5 : 'block1Circle5Static' } filter="url(#filter-89)" stroke="#8D3FFD" strokeWidth="1" fill="#FFFFFF" fillRule="evenodd" cx="66.5" cy="30" r="3" ></circle> <circle id="block1-circle5-object" className={ props.play ? styles.block1Circle5 : 'block1Circle5Static' } stroke="#8D3FFD" strokeWidth="1" fill="#FFFFFF" fillRule="evenodd" cx="66.5" cy="30" r="3" ></circle> </g> </g> </g> </g> {/* <path onMouseEnter={mouseEnterBlock2} onMouseOut={mouseOutBlock2} d="M252,145 L252,245 L352,245 L352,145 Z" opacity="0" id="block2listener" ></path> <path onMouseEnter={mouseEnterBlock3} onMouseOut={mouseOutBlock3} d="M352,90 L352,245 L507,245 L507,90 Z" opacity="0" id="block3listener" ></path> <path onMouseEnter={mouseEnterBlock4} onMouseOut={mouseOutBlock4} d="M507,120 L507,245 L632,245 L632,120 Z" opacity="0" id="block4listener" ></path> <path onMouseEnter={mouseEnterBlock5} onMouseOut={mouseOutBlock5} d="M67,245 L67,378 L199,378 L199,245 Z" opacity="0" id="block5listener" ></path> <path onMouseEnter={mouseEnterBlock6} onMouseOut={mouseOutBlock6} d="M199,245 L199,398 L353,398 L353,245 Z" opacity="0" id="block6listener" ></path> <path onMouseEnter={mouseEnterBlock7} onMouseOut={mouseOutBlock7} d="M353,245 L353,345 L453,345 L453,245 Z" opacity="0" id="block7listener" ></path> <path onMouseEnter={mouseEnterBlock8} onMouseOut={mouseOutBlock8} d="M453,245 L453,380 L583,380 L583,245 Z" opacity="0" id="block8listener" ></path> */} </svg> </section> ); }; export default BannerSVG;
the_stack
import * as React from 'react' import * as ReactDOM from 'react-dom' import {matchesSelectorAndParentsTo, addEvent, removeEvent, addUserSelectStyles, getTouchIdentifier, removeUserSelectStyles, styleHacks} from './utils/domFns' import {createCoreData, getControlPosition, snapToGrid} from './utils/positionFns' import log from './utils/log' import {EventHandler, MouseTouchEvent} from './utils/types' // Simple abstraction for dragging events names. const eventsFor = { touch: { start: 'touchstart', move: 'touchmove', stop: 'touchend' }, mouse: { start: 'mousedown', move: 'mousemove', stop: 'mouseup' } } // Default to mouse events. let dragEventFor = eventsFor.mouse interface IDraggableCoreState { dragging: boolean lastX: number lastY: number touchIdentifier?: number } export interface IDraggableBounds { left: number right: number top: number bottom: number } export interface IDraggableData { node: HTMLElement x: number y: number deltaX: number deltaY: number lastX: number lastY: number } export type DraggableEventHandler = (e: MouseEvent, data: IDraggableData) => void | true | false export interface IControlPosition { x: number y: number } export interface IDraggableCoreProps { allowAnyClick?: boolean, cancel?: string, children?: React.ReactElement<any>, disabled?: boolean, enableUserSelectHack?: boolean, offsetParent?: HTMLElement, grid?: [number, number], scale?: number handle?: string, onStart?: DraggableEventHandler, onDrag?: DraggableEventHandler, onStop?: DraggableEventHandler, onMouseDown?: (e: MouseEvent) => void, } // // Define <DraggableCore>. // // <DraggableCore> is for advanced usage of <Draggable>. It maintains minimal internal state so it can // work well with libraries that require more control over the element. // export default class DraggableCore extends React.Component<IDraggableCoreProps, IDraggableCoreState> { public static displayName = 'DraggableCore' public static defaultProps = { allowAnyClick: false, // by default only accept left click cancel: null, disabled: false, enableUserSelectHack: true, offsetParent: null, handle: null, grid: null, scale: 1, transform: null, onStart: () => void 0, onDrag: () => void 0, onStop: () => void 0, onMouseDown: () => void 0 } public state = { dragging: false, // Used while dragging to determine deltas. lastX: NaN, lastY: NaN, touchIdentifier: null } public componentWillUnmount () { // Remove any leftover event handlers. Remove both touch and mouse handlers in case // some browser quirk caused a touch event to fire during a mouse move, or vice versa. const thisNode = ReactDOM.findDOMNode(this) if (thisNode) { const {ownerDocument} = thisNode removeEvent(ownerDocument, eventsFor.mouse.move, this.handleDrag) removeEvent(ownerDocument, eventsFor.touch.move, this.handleDrag) removeEvent(ownerDocument, eventsFor.mouse.stop, this.handleDragStop) removeEvent(ownerDocument, eventsFor.touch.stop, this.handleDragStop) if (this.props.enableUserSelectHack) { removeUserSelectStyles(ownerDocument) } } } private handleDragStart: EventHandler<MouseTouchEvent> = (e) => { // Make it possible to attach event handlers on top of this one. this.props.onMouseDown(e) // Only accept left-clicks. if (!this.props.allowAnyClick && typeof e.button === 'number' && e.button !== 0) { return false } // Get nodes. Be sure to grab relative document (could be iframed) const thisNode = ReactDOM.findDOMNode(this) if (!thisNode || !thisNode.ownerDocument || !thisNode.ownerDocument.body) { throw new Error('<DraggableCore> not mounted on DragStart!') } const {ownerDocument} = thisNode // Short circuit if handle or cancel prop was provided and selector doesn't match. if (this.props.disabled || (!(e.target instanceof Node)) || // FIXME ownerDocument.defaultView.Node (this.props.handle && !matchesSelectorAndParentsTo(e.target as Node, this.props.handle, thisNode)) || (this.props.cancel && matchesSelectorAndParentsTo(e.target as Node, this.props.cancel, thisNode))) { return } // Set touch identifier in component state if this is a touch event. This allows us to // distinguish between individual touches on multitouch screens by identifying which // touchpoint was set to this element. const touchIdentifier = getTouchIdentifier(e) this.setState({touchIdentifier}) // Get the current drag point from the event. This is used as the offset. const position = getControlPosition(e, touchIdentifier, this) if (position == null) { return // not possible but satisfies flow } const {x, y} = position // Create an event object with all the data parents need to make a decision here. const coreEvent = createCoreData(this, x, y) log('DraggableCore: handleDragStart: %j', coreEvent) // Call event handler. If it returns explicit false, cancel. log('calling', this.props.onStart) const shouldUpdate = this.props.onStart(e, coreEvent) if (shouldUpdate === false) { // FIXME fixed !shouldUpdate return } // Add a style to the body to disable user-select. This prevents text from // being selected all over the page. if (this.props.enableUserSelectHack) { addUserSelectStyles(ownerDocument) } // Initiate dragging. Set the current x and y as offsets // so we know how much we've moved during the drag. This allows us // to drag elements around even if they have been moved, without issue. this.setState({ dragging: true, lastX: x, lastY: y }) // Add events to the document directly so we catch when the user's mouse/touch moves outside of // this element. We use different events depending on whether or not we have detected that this // is a touch-capable device. addEvent(ownerDocument, dragEventFor.move, this.handleDrag) addEvent(ownerDocument, dragEventFor.stop, this.handleDragStop) } private handleDrag: EventHandler<MouseTouchEvent> = (e) => { // Prevent scrolling on mobile devices, like ipad/iphone. if (e.type === 'touchmove') { e.preventDefault() } // Get the current drag point from the event. This is used as the offset. const position = getControlPosition(e, this.state.touchIdentifier, this) if (position == null) { return } let {x, y} = position // Snap to grid if prop has been provided if (Array.isArray(this.props.grid)) { const [deltaX, deltaY] = snapToGrid(this.props.grid, x - this.state.lastX, y - this.state.lastY) if (!deltaX && !deltaY) { return // skip useless drag } x = this.state.lastX + deltaX y = this.state.lastY + deltaY } const coreEvent = createCoreData(this, x, y) log('DraggableCore: handleDrag: %j', coreEvent) // Call event handler. If it returns explicit false, trigger end. const shouldUpdate = this.props.onDrag(e, coreEvent) if (shouldUpdate === false) { try { // $FlowIgnore this.handleDragStop(new MouseEvent('mouseup') as MouseTouchEvent) } catch (err) { // Old browsers const event = document.createEvent('MouseEvents') as MouseTouchEvent // I see why this insanity was deprecated // $FlowIgnore event.initMouseEvent('mouseup', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null) this.handleDragStop(event) } return } this.setState({ lastX: x, lastY: y }) } private handleDragStop: EventHandler<MouseTouchEvent> = (e) => { if (!this.state.dragging) { return } const position = getControlPosition(e, this.state.touchIdentifier, this) if (position == null) { return } const {x, y} = position const coreEvent = createCoreData(this, x, y) const thisNode = ReactDOM.findDOMNode(this) if (thisNode) { // Remove user-select hack if (this.props.enableUserSelectHack) { removeUserSelectStyles(thisNode.ownerDocument) } } log('DraggableCore: handleDragStop: %j', coreEvent) // Reset the el. this.setState({ dragging: false, lastX: NaN, lastY: NaN }) // Call event handler this.props.onStop(e, coreEvent) if (thisNode) { // Remove event handlers log('DraggableCore: Removing handlers') removeEvent(thisNode.ownerDocument, dragEventFor.move, this.handleDrag) removeEvent(thisNode.ownerDocument, dragEventFor.stop, this.handleDragStop) } } private onMouseDown: EventHandler<MouseTouchEvent> = (e) => { dragEventFor = eventsFor.mouse // on touchscreen laptops we could switch back to mouse return this.handleDragStart(e) } private onMouseUp: EventHandler<MouseTouchEvent> = (e) => { dragEventFor = eventsFor.mouse return this.handleDragStop(e) } // Same as onMouseDown (start drag), but now consider this a touch device. private onTouchStart: EventHandler<MouseTouchEvent> = (e) => { // We're on a touch device now, so change the event handlers dragEventFor = eventsFor.touch return this.handleDragStart(e) } private onTouchEnd: EventHandler<MouseTouchEvent> = (e) => { // We're on a touch device now, so change the event handlers dragEventFor = eventsFor.touch return this.handleDragStop(e) } public render () { // Reuse the child provided // This makes it flexible to use whatever element is wanted (div, ul, etc) return React.cloneElement(React.Children.only(this.props.children), { style: styleHacks(this.props.children.props.style), // Note: mouseMove handler is attached to document so it will still function // when the user drags quickly and leaves the bounds of the element. onMouseDown: this.onMouseDown, onTouchStart: this.onTouchStart, onMouseUp: this.onMouseUp, onTouchEnd: this.onTouchEnd }) } }
the_stack
import {Injectable} from '@angular/core'; import { BaseType as D3BaseType, ContainerElement as D3ContainerElement, select as d3Select, selectAll as d3SelectAll, Selection as D3Selection } from 'd3-selection'; import {Transition as D3Transition} from 'd3-transition'; import {TimeSeries} from '../../models/time-series.model'; import {TimeSeriesPoint} from '../../models/time-series-point.model'; import {ScaleLinear as D3ScaleLinear, ScaleTime as D3ScaleTime} from 'd3-scale'; import {getColorScheme} from '../../../../enums/color-scheme.enum'; import {line as d3Line, Line as D3Line} from 'd3-shape'; import {axisBottom as d3AxisBottom, axisLeft as d3AxisLeft, axisRight as d3AxisRight} from 'd3-axis'; import {timeFormat as d3TimeFormat} from 'd3-time-format'; import {PointsSelection} from '../../models/points-selection.model'; @Injectable({ providedIn: 'root' }) export class LineChartDrawService { constructor() { } // Map that holds all points clustered by their x-axis values private _xAxisCluster: any = {}; private _DOT_RADIUS = 3; get DOT_RADIUS(): number { return this._DOT_RADIUS; } get xAxisCluster(): any { return this._xAxisCluster; } set xAxisCluster(value: any) { this._xAxisCluster = value; } /** * Adds one line per data group to the chart */ addDataLinesToChart(chartContentContainer: D3Selection<D3BaseType, {}, D3ContainerElement, {}>, pointsSelection: PointsSelection, xScale: D3ScaleTime<number, number>, yScale: D3ScaleLinear<number, number>, data: TimeSeries[], legendDataMap: { [key: string]: { [key: string]: (boolean | string) } }, index: number): void { if (index === 0) { // Remove after resize chartContentContainer.selectAll('.lines').remove(); // Remove old dots chartContentContainer.selectAll('.single-dots').remove(); // Remove old dots chartContentContainer.selectAll('.dots').remove(); } // Create one group per line / data entry chartContentContainer .append('g') .attr('class', `lines y-axis-${index}`) .selectAll('.line') // Get all lines already drawn .data(data, (timeSeries: TimeSeries) => timeSeries.key) // ... for this data .join(enter => { this.addDataPointsToXAxisCluster(enter); const lineSelection: any = this.drawLine(enter, xScale, yScale, legendDataMap); this.drawSinglePointsDots(chartContentContainer, data, xScale, yScale, legendDataMap); this.addDataPointsToChart(chartContentContainer, pointsSelection, data, xScale, yScale, legendDataMap); return lineSelection; }, update => update, exit => { this.removeDataPointsFromXAxisCluster(exit); exit.transition().duration(200).style('opacity', '0').remove(); } ); } drawAllSelectedPoints(pointsSelection: PointsSelection) { this.drawSelectedPoints(d3SelectAll('.dot'), pointsSelection); } drawSelectedPoints(dotsToCheck: D3Selection<D3BaseType, {}, HTMLElement, any>, pointsSelection: PointsSelection) { dotsToCheck.each((currentDotData: TimeSeriesPoint, index: number, dots: D3BaseType[]) => { const isDotSelected: boolean = pointsSelection.isPointSelected(currentDotData); if (isDotSelected) { d3Select(dots[index]).attr('visibility', 'visible'); } }); } /** * Print the y-axes on the graph */ setYAxesInChart(chart: D3Selection<D3BaseType, {}, D3ContainerElement, {}>, yScales: { [key: string]: D3ScaleLinear<number, number> }): void { const yAxes = d3SelectAll('.y-axis'); if (Object.keys(yScales).length !== yAxes.size()) { yAxes.remove(); Object.keys(yScales).forEach((key: string, index: number) => { let yAxis; if (index === 0) { yAxis = d3AxisLeft(yScales[key]); } else { yAxis = d3AxisRight(yScales[key]); } // Add the Y-Axis to the chart chart.append('g') // new group for the y-axis .attr('class', `axis y-axis y-axis${index}`) // a css class to style it later .call(yAxis) .append('g') .attr('class', `axis-unit axis-unit${index}`); }); } } updateXAxis(transition: D3Transition<SVGGElement, any, HTMLElement, any>, xScale: D3ScaleTime<number, number>): void { // Hide the ticks to avoid ugly transition transition.on('start.hideTicks', (_, index: number, groups: SVGGElement[]) => { d3Select(groups[index]).selectAll('g.tick text').attr('opacity', '0.0'); }); // Redraw the x-axis transition.call( d3AxisBottom(xScale) .tickFormat(d3TimeFormat(this.setTimeFormat(xScale.ticks()))) ); // Include line breaks transition.on('end.linebreak', ((_, index: number, groups: SVGGElement[]) => this.insertLinebreakToLabels(index, groups))); // Show the ticks again as now all manipulation should have been happened transition.on('end.showTicks', (_, index: number, groups: SVGGElement[]) => { d3Select(groups[index]).selectAll('g.tick text') .transition() .delay(100) .duration(500) .attr('opacity', '0.7'); }); } updateYAxes(yScales: { [key: string]: D3ScaleLinear<number, number> }, width: number, yAxisWidth: number): void { Object.keys(yScales).forEach((key: string, index: number) => { d3Select(`.y-axis${index}`) .transition() .call((transition) => this.updateYAxis( transition, yScales[key], this.getDrawingAreaWidth(width, yAxisWidth, Object.keys(yScales).length), yAxisWidth, index) ); }); } getDrawingAreaWidth(width: number, yAxisWidth: number, numberOfYAxes: number): number { if (numberOfYAxes > 1) { width = width - ((numberOfYAxes - 1) * yAxisWidth); } return width; } private addDataPointsToXAxisCluster(enter: D3Selection<D3BaseType, TimeSeries, D3BaseType, {}>): void { enter.each((timeSeries: TimeSeries) => { timeSeries.values.forEach((timeSeriesPoint: TimeSeriesPoint) => { if (!this._xAxisCluster[timeSeriesPoint.date.getTime()]) { this._xAxisCluster[timeSeriesPoint.date.getTime()] = []; } this._xAxisCluster[timeSeriesPoint.date.getTime()].push(timeSeriesPoint); }); }); } private drawLine(selection: D3Selection<D3BaseType, TimeSeries, D3BaseType, {}>, xScale: D3ScaleTime<number, number>, yScale: D3ScaleLinear<number, number>, legendDataMap: { [key: string]: { [key: string]: (boolean | string) } } ): D3Selection<D3BaseType, TimeSeries, D3BaseType, {}> { const resultingSelection = selection .append('g') // Group each line so we can add dots to this group latter .attr('class', (timeSeries: TimeSeries) => `line line-${timeSeries.key}`) .style('opacity', '0') .append('path') // Draw one path for every item in the data set .style('pointer-events', 'none') .attr('fill', 'none') .attr('stroke-width', 1.5) .attr('d', (dataItem: TimeSeries) => { const minDate = xScale.domain()[0]; const maxDate = xScale.domain()[1]; const values = dataItem.values.filter((point) => point.date <= maxDate && point.date >= minDate); return this.getLineGenerator(xScale, yScale)(values); }); d3SelectAll('.line') // colorize (in reverse order as d3 adds new line before the existing ones ... .attr('stroke', (_, strokeIndex: number, nodes: []) => { return getColorScheme()[(nodes.length - strokeIndex - 1) % getColorScheme().length]; }) // fade in .transition().duration(500).style('opacity', (timeSeries: TimeSeries) => { return (legendDataMap[timeSeries.key].show) ? '1' : '0.1'; }); return resultingSelection; } private drawSinglePointsDots(chartContentContainer: D3Selection<D3BaseType, {}, D3ContainerElement, {}>, data: TimeSeries[], xScale: D3ScaleTime<number, number>, yScale: D3ScaleLinear<number, number>, legendDataMap: { [key: string]: { [key: string]: (boolean | string) } }): void { const minDate = xScale.domain()[0]; const maxDate = xScale.domain()[1]; // Find series with only one dot in range const seriesWithOneDot = data .map((d: TimeSeries, index: number) => { return { key: d.key, values: d.values.filter((point) => point.date <= maxDate && point.date >= minDate), index: index }; }) .filter((d: TimeSeries) => { return d.values.length === 1; }); // If there is no series with one dot, end the function if (seriesWithOneDot.length === 0) { return; } const singleDotsContainerSelection = chartContentContainer .append('g') .attr('class', 'single-dots') .selectAll() .data(seriesWithOneDot) .enter() .append('g') .attr('class', s => `single-dot-${s.key}`) .style('fill', d => getColorScheme()[(data.length - d.index - 1) % getColorScheme().length]) .style('opacity', '0'); singleDotsContainerSelection .selectAll() .filter((d: TimeSeries) => legendDataMap[d.key].show as boolean) .data((s: TimeSeries) => s.values) .enter() .append('circle') .attr('r', this._DOT_RADIUS) .attr('cx', (dot: TimeSeriesPoint) => xScale(dot.date)) .attr('cy', (dot: TimeSeriesPoint) => yScale(dot.value)) .style('pointer-events', 'visible'); singleDotsContainerSelection .transition() .duration(500) .style('opacity', (timeSeries: TimeSeries) => { return (legendDataMap[timeSeries.key].show) ? '1' : '0.1'; }); } private addDataPointsToChart(chartContentContainer: D3Selection<D3BaseType, {}, D3ContainerElement, {}>, pointsSelection: PointsSelection, timeSeries: TimeSeries[], xScale: D3ScaleTime<number, number>, yScale: D3ScaleLinear<number, number>, legendDataMap: { [key: string]: { [key: string]: (boolean | string) } }): void { chartContentContainer .append('g') .attr('class', 'dots') .selectAll() .data(timeSeries) .enter() .append('g') .attr('class', (series: TimeSeries) => series.key) .attr('stroke', (_, index: number, nodes: []) => { return getColorScheme()[(nodes.length - index - 1) % getColorScheme().length]; }) .each((d: TimeSeries, i: number, e) => { // Do not render dots from not active lines if (!legendDataMap[d.key].show) { return; } const dotsGroupSelection = d3Select(e[i]); const minDate = xScale.domain()[0]; const maxDate = xScale.domain()[1]; dotsGroupSelection .selectAll() .data((series: TimeSeries) => { return series.values.filter((point) => point.date <= maxDate && point.date >= minDate); }) .enter() .append('circle') .attr('class', (dot: TimeSeriesPoint) => `dot dot-${d.key} dot-x-${xScale(dot.date).toString().replace('.', '_')}`) .attr('visibility', 'hidden') .attr('r', this._DOT_RADIUS) .attr('cx', (dot: TimeSeriesPoint) => xScale(dot.date)) .attr('cy', (dot: TimeSeriesPoint) => yScale(dot.value)) .style('pointer-events', 'visible'); } ); // Redraw selected dots this.drawSelectedPoints(d3SelectAll('.dot'), pointsSelection); } private removeDataPointsFromXAxisCluster(exit: D3Selection<D3BaseType, TimeSeries, D3BaseType, {}>): void { exit.each((timeSeries: TimeSeries, index: number) => { timeSeries.values.forEach((timeSeriesPoint: TimeSeriesPoint) => { this._xAxisCluster[timeSeriesPoint.date.getTime()].splice(index, 1); if (this._xAxisCluster[timeSeriesPoint.date.getTime()].length === 0) { delete this._xAxisCluster[timeSeriesPoint.date.getTime()]; } }); }); } /** * Configuration of the line generator which does print the lines */ private getLineGenerator(xScale: D3ScaleTime<number, number>, yScale: D3ScaleLinear<number, number>): D3Line<TimeSeriesPoint> { return d3Line<TimeSeriesPoint>() // Setup a line generator .x((p: TimeSeriesPoint) => xScale(p.date)) // ... specify the data for the X-Coordinate .y((p: TimeSeriesPoint) => yScale(p.value)); // ... and for the Y-Coordinate // .curve(d3CurveMonotoneX); // smooth the line } private setTimeFormat(ticks: Date[]): string { let onlyDays = true; // Should weekday names instead of hours and minutes should be shown let lastTick: Date = null; // Check if every tick step is at least one day. // If not set onlyDays to false ticks.forEach((tick: Date) => { if (lastTick) { if (tick.getUTCDate() === lastTick.getUTCDate()) { onlyDays = false; } } lastTick = tick; }); return (onlyDays ? '%A' : '%H:%M') + ' \n %Y-%m-%d'; } private insertLinebreakToLabels(index: number, groups: SVGGElement[]): void { d3Select(groups[index]).selectAll('g.tick text').each((_, nodeIndex: number, nodes: SVGTextElement[]) => { const element = d3Select(nodes[nodeIndex]); const lines = element.text().split(' \n '); // Reset the text as we will replace it element.text(''); lines.forEach((line, lineIndex) => { const tspan = element.append('tspan').text(line); if (lineIndex > 0) { tspan.attr('x', 0).attr('dy', '15'); } }); }); } private updateYAxis(transition: any, yScale: any, drawingAreaWidth: number, yAxisWidth: number, index: number): void { let strokeOpacity: number, textPosition: number; if (index === 0) { strokeOpacity = 0.5; textPosition = -5; } else { strokeOpacity = 0; textPosition = (index - 1) * yAxisWidth + drawingAreaWidth + 5; } transition.call( d3AxisRight(yScale) // axis right, because we draw the background line with this .tickSize(drawingAreaWidth) // background line over complete chart width ) .attr('transform', 'translate(0, 0)') // move the axis to the left // make all line dotted, except the one on the bottom as this will indicate the x-axis .call(g => g.selectAll('.tick:not(:first-of-type) line') .attr('stroke-opacity', strokeOpacity) .attr('stroke-dasharray', '1,1')) .call(g => g.selectAll('.tick text') // move the text a little so it does not overlap with the lines .attr('x', textPosition)); } }
the_stack
import * as fs from "fs"; import * as path from "path"; import * as _ from "lodash"; import { app } from "electron"; import { createUuid } from "extraterm-uuid"; import { Logger, getLogger } from "extraterm-logging"; import { ThemeInfo, ThemeType, FALLBACK_TERMINAL_THEME, FALLBACK_SYNTAX_THEME } from "../theme/Theme"; import { GeneralConfig, FontInfo, ConfigCursorStyle, TerminalMarginStyle, FrameRule, TitleBarStyle, WindowBackgroundMode, GENERAL_CONFIG } from "../Config"; import { ThemeManager } from "../theme/ThemeManager"; import { KeybindingsIOManager } from "./KeybindingsIOManager"; import { LogicalKeybindingsName, AllLogicalKeybindingsNames } from "../keybindings/KeybindingsTypes"; import { PersistentConfigDatabase } from "./PersistentConfigDatabase"; import { ConfigChangeEvent, ConfigDatabase } from "../ConfigDatabase"; export const EXTRATERM_CONFIG_DIR = "extraterm"; const PATHS_CONFIG_FILENAME = "application_paths.json"; const PATHS_USER_SETTINGS_KEY = "userSettingsPath"; const USER_KEYBINDINGS_DIR = "keybindings"; const USER_THEMES_DIR = "themes"; const USER_SYNTAX_THEMES_DIR = "syntax"; const USER_TERMINAL_THEMES_DIR = "terminal"; const DEFAULT_TERMINALFONT = "LigaDejaVuSansMono"; export const KEYBINDINGS_OSX: LogicalKeybindingsName = "macos-style"; export const KEYBINDINGS_PC: LogicalKeybindingsName = "pc-style"; const MAIN_CONFIG = "extraterm.json"; const EXTENSION_DIRECTORY = "extensions"; const LOG_FINE = false; const _log = getLogger("MainConfig"); export function setupAppData(): void { const configDir = getUserSettingsDirectory(); if ( ! fs.existsSync(configDir)) { fs.mkdirSync(configDir); } else { const statInfo = fs.statSync(configDir); if ( ! statInfo.isDirectory()) { _log.warn("Extraterm configuration path " + configDir + " is not a directory!"); return; } } const userKeybindingsDir = getUserKeybindingsDirectory(); if ( ! fs.existsSync(userKeybindingsDir)) { fs.mkdirSync(userKeybindingsDir); } else { const statInfo = fs.statSync(userKeybindingsDir); if ( ! statInfo.isDirectory()) { _log.warn("Extraterm user keybindings path " + userKeybindingsDir + " is not a directory!"); return; } } const userThemesDir = getUserThemeDirectory(); if ( ! fs.existsSync(userThemesDir)) { fs.mkdirSync(userThemesDir); } else { const statInfo = fs.statSync(userThemesDir); if ( ! statInfo.isDirectory()) { _log.warn("Extraterm user themes path " + userThemesDir + " is not a directory!"); return; } } const userSyntaxThemesDir = getUserSyntaxThemeDirectory(); if ( ! fs.existsSync(userSyntaxThemesDir)) { fs.mkdirSync(userSyntaxThemesDir); } else { const statInfo = fs.statSync(userSyntaxThemesDir); if ( ! statInfo.isDirectory()) { _log.warn("Extraterm user syntax themes path " + userSyntaxThemesDir + " is not a directory!"); return; } } const userTerminalThemesDir = getUserTerminalThemeDirectory(); if ( ! fs.existsSync(userTerminalThemesDir)) { fs.mkdirSync(userTerminalThemesDir); } else { const statInfo = fs.statSync(userTerminalThemesDir); if ( ! statInfo.isDirectory()) { _log.warn("Extraterm user terminal themes path " + userTerminalThemesDir + " is not a directory!"); return; } } } let userSettingsPath: string = null; export function getUserSettingsDirectory(): string { if (userSettingsPath == null) { const overridePath = getUserSettingsDirectoryFromPathsConfig(); if (overridePath != null) { userSettingsPath = overridePath; } else { userSettingsPath = path.join(app.getPath("appData"), EXTRATERM_CONFIG_DIR); } } return userSettingsPath; } function getUserSettingsDirectoryFromPathsConfig(): string { const exeDir = path.dirname(app.getPath("exe")); const pathsConfigFilename = path.join(exeDir, PATHS_CONFIG_FILENAME); _log.info(`Looking for ${PATHS_CONFIG_FILENAME} at '${pathsConfigFilename}'`); if (fs.existsSync(pathsConfigFilename)) { try { const pathsConfigString = fs.readFileSync(pathsConfigFilename, {encoding: "utf8"}); const pathsConfig = JSON.parse(pathsConfigString); const value = pathsConfig[PATHS_USER_SETTINGS_KEY]; if (value != null) { if (typeof value !== "string") { _log.warn(`Value of key ${PATHS_USER_SETTINGS_KEY} in file ${pathsConfigFilename} isn't a string.`); } else { if (value === "") { _log.info(`Using default location for user settings because ${PATHS_USER_SETTINGS_KEY} in file ${pathsConfigFilename} is empty.`); return null; } const userSettingsPath = path.join(exeDir, value); _log.info(`Using '${userSettingsPath}' for storing user settings.`); return userSettingsPath; } } } catch(ex) { _log.warn(`Unable to parse json file '${pathsConfigFilename}',`, ex); } } return null; } function getUserThemeDirectory(): string { return path.join(getUserSettingsDirectory(), USER_THEMES_DIR); } export function getUserTerminalThemeDirectory(): string { return path.join(getUserThemeDirectory(), USER_TERMINAL_THEMES_DIR); } export function getUserSyntaxThemeDirectory(): string { return path.join(getUserThemeDirectory(), USER_SYNTAX_THEMES_DIR); } export function getUserKeybindingsDirectory(): string { return path.join(getUserSettingsDirectory(), USER_KEYBINDINGS_DIR); } export function getConfigurationFilename(): string { return path.join(getUserSettingsDirectory(), MAIN_CONFIG); } export function getUserExtensionDirectory(): string { return path.join(getUserSettingsDirectory(), EXTENSION_DIRECTORY); } export function isThemeType(themeInfo: ThemeInfo, themeType: ThemeType): boolean { if (themeInfo === null) { return false; } return themeInfo.type === themeType; } export function sanitizeAndIinitializeConfigs(configDatabase: PersistentConfigDatabase, themeManager: ThemeManager, keybindingsIOManager: KeybindingsIOManager, availableFonts: FontInfo[]): void { sanitizeGeneralConfig(configDatabase, themeManager, availableFonts); sanitizeSessionConfig(configDatabase); sanitizeCommandLineActionsConfig(configDatabase); distributeUserStoredConfig(configDatabase, keybindingsIOManager); } const frameRules: FrameRule[] = ["always_frame", "frame_if_lines", "never_frame"]; function sanitizeGeneralConfig(configDatabase: ConfigDatabase, themeManager: ThemeManager, availableFonts: FontInfo[]): void { const generalConfig = configDatabase.getGeneralConfigCopy() ?? {}; const configCursorStyles: ConfigCursorStyle[] = ["block", "underscore", "beam"]; sanitizeField(generalConfig, "autoCopySelectionToClipboard", true); sanitizeField(generalConfig, "blinkingCursor", false); sanitizeStringEnumField(generalConfig, "cursorStyle", configCursorStyles, "block"); sanitizeField(generalConfig, "frameByDefault", true); sanitizeStringEnumField(generalConfig, "frameRule", frameRules, "frame_if_lines"); sanitizeField(generalConfig, "frameRuleLines", 10); sanitizeStringEnumField(generalConfig, "gpuDriverWorkaround", ["none", "no_blend"], "none"); sanitizeField(generalConfig, "isHardwareAccelerated", true); generalConfig.isHardwareAccelerated = true; // Always on since WebGL was introduced. sanitizeField(generalConfig, "keybindingsName", process.platform === "darwin" ? KEYBINDINGS_OSX : KEYBINDINGS_PC); if ( ! AllLogicalKeybindingsNames.includes(generalConfig.keybindingsName)) { generalConfig.keybindingsName = process.platform === "darwin" ? KEYBINDINGS_OSX : KEYBINDINGS_PC; } sanitizeField(generalConfig, "minimizeToTray", false); sanitizeField(generalConfig, "scrollbackMaxFrames", 100); sanitizeField(generalConfig, "scrollbackMaxLines", 500000); sanitizeStringEnumField(generalConfig, "showTips", ["always", "daily", "never"], "always"); sanitizeField(generalConfig, "showTrayIcon", false); sanitizeField(generalConfig, "terminalFont", DEFAULT_TERMINALFONT); if ( ! availableFonts.some( (font) => font.postscriptName === generalConfig.terminalFont)) { generalConfig.terminalFont = DEFAULT_TERMINALFONT; } sanitizeField(generalConfig, "terminalFontSize", 13); generalConfig.terminalFontSize = Math.max(Math.min(1024, generalConfig.terminalFontSize), 4); sanitizeField(generalConfig, "terminalDisplayLigatures", true); const marginStyles: TerminalMarginStyle[] = ["normal", "none", "thick", "thin"]; sanitizeStringEnumField(generalConfig, "terminalMarginStyle", marginStyles, "normal"); sanitizeField(generalConfig, "tipCounter", 0); sanitizeField(generalConfig, "tipTimestamp", 0); const titleBarStyles: TitleBarStyle[] = ["compact", "native", "theme"]; sanitizeStringEnumField(generalConfig, "titleBarStyle", titleBarStyles, "compact"); sanitizeField(generalConfig, "uiScalePercent", 100); generalConfig.uiScalePercent = Math.min(500, Math.max(5, generalConfig.uiScalePercent || 100)); const windowBackgroundModes: WindowBackgroundMode[] = ["opaque", "blur"]; sanitizeStringEnumField(generalConfig, "windowBackgroundMode", windowBackgroundModes, "opaque"); sanitizeField(generalConfig, "windowBackgroundTransparencyPercent", 50); generalConfig.windowBackgroundTransparencyPercent = Math.max(Math.min(100, generalConfig.windowBackgroundTransparencyPercent), 0); sanitizeField(generalConfig, "closeWindowWhenEmpty", true); sanitizeField(generalConfig, "middleMouseButtonAction", "paste"); sanitizeField(generalConfig, "middleMouseButtonShiftAction", "paste"); sanitizeField(generalConfig, "middleMouseButtonControlAction", "paste"); sanitizeField(generalConfig, "rightMouseButtonAction", "context_menu"); sanitizeField(generalConfig, "rightMouseButtonShiftAction", "context_menu"); sanitizeField(generalConfig, "rightMouseButtonControlAction", "context_menu"); sanitizeField(generalConfig, "activeExtensions", {}); sanitizeField(generalConfig, "themeTerminal", FALLBACK_TERMINAL_THEME); if ( ! isThemeType(themeManager.getTheme(generalConfig.themeTerminal), "terminal")) { generalConfig.themeTerminal = FALLBACK_TERMINAL_THEME; } sanitizeField(generalConfig, "themeSyntax", FALLBACK_SYNTAX_THEME); if ( ! isThemeType(themeManager.getTheme(generalConfig.themeSyntax), "syntax")) { generalConfig.themeSyntax = FALLBACK_SYNTAX_THEME; } sanitizeField(generalConfig, "themeGUI", "two-dark-ui"); if (generalConfig.themeGUI === "default" || ! isThemeType(themeManager.getTheme(generalConfig.themeGUI), "gui")) { generalConfig.themeGUI = "two-dark-ui"; } configDatabase.setGeneralConfig(generalConfig); } function sanitizeSessionConfig(configDatabase: ConfigDatabase): void { let sessionConfigs = configDatabase.getSessionConfigCopy(); if (sessionConfigs == null || ! Array.isArray(sessionConfigs)) { sessionConfigs = []; } // Ensure that when reading a config file where args is not defined, we define it as an empty string for (const sessionConfiguration of sessionConfigs) { sanitizeField(sessionConfiguration, "name", ""); sanitizeField(sessionConfiguration, "uuid", createUuid()); if (typeof sessionConfiguration.type !== "string") { sessionConfiguration.type = ""; } if (sessionConfiguration.initialDirectory == null || typeof sessionConfiguration.initialDirectory !== "string") { sessionConfiguration.initialDirectory = null; } sanitizeField(sessionConfiguration, "args", ""); } configDatabase.setSessionConfig(sessionConfigs); } function sanitizeCommandLineActionsConfig(configDatabase: ConfigDatabase): void { let commandLineActions = configDatabase.getCommandLineActionConfigCopy(); if ( ! Array.isArray(commandLineActions)) { commandLineActions = [ { frameRule: "never_frame", frameRuleLines: 5, match: "show", matchType: "name" } ]; } else { for (const action of commandLineActions) { sanitizeStringEnumField(action, "frameRule", frameRules, "never_frame"); sanitizeField(action, "frameRuleLines", 5); sanitizeField(action, "match", ""); sanitizeStringEnumField(action, "matchType", ["name", "regexp"], "name"); } } configDatabase.setCommandLineActionConfig(commandLineActions); } function sanitizeField<T, K extends keyof T>(object: T, key: K, defaultValue: T[K]): void { if (object[key] == null || typeof object[key] !== typeof defaultValue) { object[key] = defaultValue; } } function sanitizeStringEnumField<T, K extends keyof T>(object: T, key: K, availableValues: (T[K])[], defaultValue: T[K]): void { if (object[key] == null) { object[key] = defaultValue; } else if ( ! availableValues.includes(object[key])) { object[key] = defaultValue; } } function distributeUserStoredConfig(configDatabase: PersistentConfigDatabase, keybindingsIOManager: KeybindingsIOManager): void { configDatabase.onChange((event: ConfigChangeEvent): void => { if (event.key === GENERAL_CONFIG) { //Check if the selected keybindings changed. If so update and broadcast the system config. const oldGeneralConfig = <GeneralConfig> event.oldConfig; const newGeneralConfig = <GeneralConfig> event.newConfig; if (newGeneralConfig != null) { if (oldGeneralConfig == null || oldGeneralConfig.keybindingsName !== newGeneralConfig.keybindingsName) { const systemConfig = configDatabase.getSystemConfigCopy(); systemConfig.flatKeybindingsSet = keybindingsIOManager.getFlatKeybindingsSet(newGeneralConfig.keybindingsName); configDatabase.setSystemConfig(systemConfig); } } } }); }
the_stack
import { t } from "../index"; import { replayCore } from "../core"; import { TestGame, getTestPlatform, FullTestGame, TestGameWithSprites, gameProps, NestedSpriteGame, LocalStorageGame, nativeSpriteSettings, NativeSpriteGame, MyWidgetImplementation, widgetState, widgetCallback, MaskGame, CallbackPropGame, NestedSpriteGame2, PureSpriteGame, pureSpriteAlwaysRendersFn, pureSpriteNeverRendersFn, pureSpriteConditionalRendersFn, waitFrame, GetStateGame, AssetsGame, DuplicateSpriteIdsGame, TestContextGame, TestContextErrorGame, DuplicatePureSpriteIdsGame, AssetsUnmountRemountGame, } from "./utils"; import { NativeSpriteUtils } from "../sprite"; import { TextTexture, CircleTexture } from "../t"; test("can render simple game and runNextFrame", () => { const { platform, mutInputs, textures } = getTestPlatform(); const platformSpy = { getInputs: jest.spyOn(platform, "getInputs"), }; mutInputs.ref.buttonPressed.move = true; const { runNextFrame } = replayCore( platform, nativeSpriteSettings, TestGame(gameProps) ); let time = 1; const nextFrame = () => { time += 1000 * (1 / 60); runNextFrame(time, jest.fn()); }; expect(platformSpy.getInputs).toBeCalledTimes(0); expect(textures).toEqual([ { type: "circle", props: { x: 5, y: 50, opacity: 1, rotation: 0, radius: 10, color: "#0095DD", scaleX: 5, scaleY: 1, anchorX: 0, anchorY: 0, mask: null, }, }, ]); nextFrame(); expect(platformSpy.getInputs).toBeCalledTimes(1); expect(textures[0]).toEqual({ type: "circle", props: { x: 6, y: 50, rotation: 0, opacity: 1, radius: 10, color: "#0095DD", scaleX: 5, scaleY: 1, anchorX: 0, anchorY: 0, mask: null, }, }); mutInputs.ref.buttonPressed.move = true; nextFrame(); expect(platformSpy.getInputs).toBeCalledTimes(2); expect(textures[0]).toEqual({ type: "circle", props: { x: 7, y: 50, rotation: 0, opacity: 1, radius: 10, color: "#0095DD", scaleX: 5, scaleY: 1, anchorX: 0, anchorY: 0, mask: null, }, }); }); test("can render simple game with sprites", () => { const { platform, mutInputs, textures } = getTestPlatform(); const platformSpy = { getInputs: jest.spyOn(platform, "getInputs"), }; mutInputs.ref.buttonPressed.move = true; const { runNextFrame } = replayCore( platform, nativeSpriteSettings, TestGameWithSprites(gameProps) ); let time = 1; const nextFrame = () => { time += 1000 * (1 / 60); runNextFrame(time, jest.fn()); }; expect(platformSpy.getInputs).toBeCalledTimes(1); expect(textures[0]).toEqual({ type: "circle", props: { x: 50, y: 50, rotation: 10, color: "#0095DD", radius: 10, opacity: 1, anchorX: 0, anchorY: 0, scaleX: 1, scaleY: 1, mask: null, }, }); nextFrame(); expect(platformSpy.getInputs).toBeCalledTimes(2); expect(textures[0]).toEqual({ type: "circle", props: { x: 51, y: 50, rotation: 10, color: "#0095DD", radius: 10, opacity: 1, anchorX: 0, anchorY: 0, scaleX: 1, scaleY: 1, mask: null, }, }); mutInputs.ref.buttonPressed.show = false; nextFrame(); expect(textures).toEqual([]); mutInputs.ref.buttonPressed.show = true; nextFrame(); // sprite state reset after removed expect(textures[0]).toEqual({ type: "circle", props: { x: 50, y: 50, rotation: 10, color: "#0095DD", radius: 10, opacity: 1, anchorX: 0, anchorY: 0, scaleX: 1, scaleY: 1, mask: null, }, }); }); test("Can render simple game with sprites in landscape", () => { const { platform, textures } = getTestPlatform({ width: 500, height: 300, widthMargin: 0, heightMargin: 0, deviceWidth: 500, deviceHeight: 300, }); replayCore(platform, nativeSpriteSettings, TestGameWithSprites(gameProps)); const { text } = (textures[1] as TextTexture).props; expect(text).toBe("this is landscape"); }); test("Can render simple game with sprites in portrait", () => { const { platform, textures } = getTestPlatform({ width: 300, height: 500, widthMargin: 0, heightMargin: 0, deviceWidth: 300, deviceHeight: 500, }); replayCore(platform, nativeSpriteSettings, TestGameWithSprites(gameProps)); const { text } = (textures[1] as TextTexture).props; expect(text).toBe("this is portrait"); }); test("Can render simple game with sprites in XL landscape", () => { const { platform, textures } = getTestPlatform({ width: 500, height: 300, widthMargin: 0, heightMargin: 0, deviceWidth: 1500, deviceHeight: 900, }); replayCore(platform, nativeSpriteSettings, TestGameWithSprites(gameProps)); const { text } = (textures[1] as TextTexture).props; expect(text).toBe("this is XL landscape"); }); test("Can render simple game with sprites in XL portrait", () => { const { platform, textures } = getTestPlatform({ width: 300, height: 500, widthMargin: 0, heightMargin: 0, deviceWidth: 900, deviceHeight: 1500, }); replayCore(platform, nativeSpriteSettings, TestGameWithSprites(gameProps)); const { text } = (textures[1] as TextTexture).props; expect(text).toBe("this is XL portrait"); }); test("can log", () => { const { platform, mutableTestDevice, mutInputs } = getTestPlatform(); const logSpy = jest.spyOn(mutableTestDevice, "log"); const { runNextFrame } = replayCore( platform, nativeSpriteSettings, FullTestGame(gameProps) ); let time = 1; const nextFrame = () => { time += 1000 * (1 / 60); runNextFrame(time, jest.fn()); }; mutInputs.ref.buttonPressed.log = true; nextFrame(); expect(logSpy).toBeCalledWith("Log Message"); }); test("can provide a random number", () => { const { platform, mutableTestDevice, mutInputs } = getTestPlatform(); const randomSpy = jest.spyOn(mutableTestDevice, "random"); const logSpy = jest.spyOn(mutableTestDevice, "log"); const { runNextFrame } = replayCore( platform, nativeSpriteSettings, FullTestGame(gameProps) ); mutInputs.ref.buttonPressed.setRandom = true; runNextFrame(1000 * (1 / 60) + 1, jest.fn()); expect(logSpy).toBeCalledWith(0.5); expect(randomSpy).toBeCalledTimes(1); }); test("supports timer", async () => { const { platform, mutableTestDevice, mutInputs } = getTestPlatform(); const startSpy = jest.spyOn(mutableTestDevice.timer, "start"); const cancelSpy = jest.spyOn(mutableTestDevice.timer, "cancel"); const pauseSpy = jest.spyOn(mutableTestDevice.timer, "pause"); const resumeSpy = jest.spyOn(mutableTestDevice.timer, "resume"); const logSpy = jest.spyOn(mutableTestDevice, "log"); const { runNextFrame } = replayCore( platform, nativeSpriteSettings, FullTestGame(gameProps) ); let time = 1; const nextFrame = () => { time += 1000 * (1 / 60); runNextFrame(time, jest.fn()); }; mutInputs.ref.buttonPressed.timer.start = true; nextFrame(); await waitFrame(); expect(logSpy).toBeCalledWith("timeout complete"); expect(startSpy).toBeCalledTimes(2); // once in init mutInputs.ref.buttonPressed.timer.start = false; mutInputs.ref.buttonPressed.timer.pause = "abc"; nextFrame(); expect(pauseSpy).toBeCalledTimes(1); expect(pauseSpy).toBeCalledWith("abc"); mutInputs.ref.buttonPressed.timer.pause = ""; mutInputs.ref.buttonPressed.timer.resume = "abc"; nextFrame(); expect(resumeSpy).toBeCalledTimes(1); expect(resumeSpy).toBeCalledWith("abc"); mutInputs.ref.buttonPressed.timer.resume = ""; mutInputs.ref.buttonPressed.timer.cancel = "abc"; nextFrame(); expect(cancelSpy).toBeCalledTimes(1); expect(cancelSpy).toBeCalledWith("abc"); }); test("supports getting date now", () => { const { platform, mutableTestDevice, mutInputs } = getTestPlatform(); const setDateSpy = jest.spyOn(mutableTestDevice, "now"); const logSpy = jest.spyOn(mutableTestDevice, "log"); const { runNextFrame } = replayCore( platform, nativeSpriteSettings, FullTestGame(gameProps) ); mutInputs.ref.buttonPressed.setDate = true; runNextFrame(1000 * (1 / 60) + 1, jest.fn()); expect(logSpy).toBeCalledWith("1996-01-17T03:24:00.000Z"); expect(setDateSpy).toBeCalledTimes(1); }); test("supports updateState", async () => { const { platform, mutableTestDevice, mutInputs } = getTestPlatform(); const logSpy = jest.spyOn(mutableTestDevice, "log"); const { runNextFrame } = replayCore( platform, nativeSpriteSettings, FullTestGame(gameProps) ); let time = 1; const nextFrame = () => { time += 1000 * (1 / 60); runNextFrame(time, jest.fn()); }; await waitFrame(); nextFrame(); expect(logSpy).toBeCalledWith("initialised"); mutInputs.ref.buttonPressed.action = true; nextFrame(); await waitFrame(); nextFrame(); // log called on state change in next loop expect(logSpy).toBeCalledWith("render time: 1996-01-17T03:24:00.000Z"); expect(logSpy).toBeCalledWith("render time 2: 1996-01-17T03:24:00.000Z"); expect(logSpy).toBeCalledWith("updateState from timeout in render"); }); test("updateState in loop will update state in next render", () => { const { platform, mutInputs, textures } = getTestPlatform(); const { runNextFrame } = replayCore( platform, nativeSpriteSettings, FullTestGame(gameProps) ); expect((textures[0] as CircleTexture).props.x).toEqual(5); let time = 1; const nextFrame = () => { time += 1000 * (1 / 60); runNextFrame(time, jest.fn()); }; mutInputs.ref.buttonPressed.move = true; mutInputs.ref.buttonPressed.moveWithUpdateState = true; nextFrame(); // An extra 5 was added in sync expect((textures[0] as CircleTexture).props.x).toEqual(11); }); test("can call updateState within an updateState", async () => { const { platform, mutableTestDevice, mutInputs, textures, } = getTestPlatform(); const logSpy = jest.spyOn(mutableTestDevice, "log"); mutInputs.ref.buttonPressed.action = true; const { runNextFrame } = replayCore( platform, nativeSpriteSettings, FullTestGame(gameProps) ); expect((textures[1] as TextTexture).props.text).toBe( "updateState Counter: 0" ); let time = 1; const nextFrame = () => { time += 1000 * (1 / 60); runNextFrame(time, jest.fn()); }; nextFrame(); expect((textures[1] as TextTexture).props.text).toBe( "updateState Counter: 3" ); expect(logSpy).toBeCalledWith("First updateState counter val: 0"); expect(logSpy).toBeCalledWith("Second updateState counter val: 1"); expect(logSpy).toBeCalledWith("Third updateState counter val: 2"); }); test("supports getState", async () => { const { platform, mutableTestDevice, mutInputs } = getTestPlatform(); const logSpy = jest.spyOn(mutableTestDevice, "log"); const { runNextFrame } = replayCore( platform, nativeSpriteSettings, FullTestGame(gameProps) ); mutInputs.ref.buttonPressed.move = true; let time = 1; const nextFrame = () => { time += 1000 * (1 / 60); runNextFrame(time, jest.fn()); }; nextFrame(); await waitFrame(); expect(logSpy).toBeCalledWith("getState position: 6"); }); test("getState will throw error if called synchronously", () => { const { platform } = getTestPlatform(); expect(() => replayCore(platform, nativeSpriteSettings, GetStateGame(gameProps)) ).toThrowError("Cannot call getState synchronously in init"); }); test("supports playing audio", () => { const { platform, mutableTestDevice, mutInputs } = getTestPlatform(); const logSpy = jest.spyOn(mutableTestDevice, "log"); const audio = mutableTestDevice.audio("filename"); const audioSpy = { play: jest.spyOn(audio, "play"), getPosition: jest.spyOn(audio, "getPosition"), pause: jest.spyOn(audio, "pause"), getVolume: jest.spyOn(audio, "getVolume"), setVolume: jest.spyOn(audio, "setVolume"), getStatus: jest.spyOn(audio, "getStatus"), getDuration: jest.spyOn(audio, "getDuration"), }; const { runNextFrame } = replayCore( platform, nativeSpriteSettings, FullTestGame(gameProps) ); let time = 1; const nextFrame = () => { time += 1000 * (1 / 60); runNextFrame(time, jest.fn()); }; mutInputs.ref.buttonPressed.sound.play = true; nextFrame(); expect(audioSpy.play).toBeCalledWith(); mutInputs.ref.buttonPressed.sound.playFromPosition = true; nextFrame(); expect(audioSpy.play).toBeCalledWith(100); mutInputs.ref.buttonPressed.sound.playLoop = true; nextFrame(); expect(audioSpy.play).toBeCalledWith({ fromPosition: 0, loop: true }); mutInputs.ref.buttonPressed.sound.playOverwrite = true; nextFrame(); expect(audioSpy.play).toBeCalledWith({ overwrite: true }); mutInputs.ref.buttonPressed.sound.pause = true; nextFrame(); expect(audioSpy.pause).toBeCalledWith(); mutInputs.ref.buttonPressed.sound.getPosition = true; nextFrame(); expect(audioSpy.getPosition).toBeCalledWith(); expect(logSpy).toBeCalledWith(50); mutInputs.ref.buttonPressed.sound.getVolume = true; nextFrame(); expect(audioSpy.getVolume).toBeCalledWith(); expect(logSpy).toBeCalledWith(1); mutInputs.ref.buttonPressed.sound.setVolume = true; nextFrame(); expect(audioSpy.setVolume).toBeCalledWith(1); mutInputs.ref.buttonPressed.sound.getStatus = true; nextFrame(); expect(audioSpy.getStatus).toBeCalledWith(); expect(logSpy).toBeCalledWith("playing"); mutInputs.ref.buttonPressed.sound.getDuration = true; nextFrame(); expect(audioSpy.getDuration).toBeCalledWith(); expect(logSpy).toBeCalledWith(100); }); test("supports network calls", () => { const { platform, mutableTestDevice, mutInputs } = getTestPlatform(); const logSpy = jest.spyOn(mutableTestDevice, "log"); const { network } = mutableTestDevice; const networkSpy = { get: jest.spyOn(network, "get"), post: jest.spyOn(network, "post"), put: jest.spyOn(network, "put"), delete: jest.spyOn(network, "delete"), }; const { runNextFrame } = replayCore( platform, nativeSpriteSettings, FullTestGame(gameProps) ); let time = 1; const nextFrame = () => { time += 1000 * (1 / 60); runNextFrame(time, jest.fn()); }; mutInputs.ref.buttonPressed.network.get = true; nextFrame(); expect(networkSpy.get).toBeCalled(); expect(logSpy).toBeCalledWith("GET-/test"); mutInputs.ref.buttonPressed.network.put = true; nextFrame(); expect(networkSpy.put).toBeCalled(); expect(logSpy).toBeCalledWith("PUT-/test-PUT_BODY"); mutInputs.ref.buttonPressed.network.post = true; nextFrame(); expect(networkSpy.post).toBeCalled(); expect(logSpy).toBeCalledWith("POST-/test-POST_BODY"); mutInputs.ref.buttonPressed.network.delete = true; nextFrame(); expect(networkSpy.delete).toBeCalled(); expect(logSpy).toBeCalledWith("DELETE-/test"); }); test("supports local storage", async () => { const { platform, mutableTestDevice, textures } = getTestPlatform(); const { storage } = mutableTestDevice; const storageSpy = { getItem: jest.spyOn(storage, "getItem"), setItem: jest.spyOn(storage, "setItem"), }; const { runNextFrame } = replayCore( platform, nativeSpriteSettings, LocalStorageGame(gameProps) ); expect(storageSpy.getItem).toBeCalledWith("text1"); expect(storageSpy.getItem).toBeCalledWith("text2"); expect(textures).toEqual([]); // Wait for promises to resolve await waitFrame(); runNextFrame(1000 * (1 / 60) + 1, jest.fn()); expect(textures).toEqual([ { type: "text", props: { text: "storage", color: "red", x: 0, y: 0, rotation: 0, opacity: 1, anchorX: 0, anchorY: 0, scaleX: 1, scaleY: 1, mask: null, font: undefined, }, }, { type: "text", props: { text: "storage", color: "blue", x: 0, y: 0, rotation: 0, opacity: 1, anchorX: 0, anchorY: 0, scaleX: 1, scaleY: 1, mask: null, }, }, ]); expect(storageSpy.setItem).toBeCalledWith("text2", "new-val"); }); test("supports alerts", () => { const { platform, mutableTestDevice, mutInputs } = getTestPlatform(); const logSpy = jest.spyOn(mutableTestDevice, "log"); const { alert } = mutableTestDevice; const alertSpy = { ok: jest.spyOn(alert, "ok"), okCancel: jest.spyOn(alert, "okCancel"), }; const { runNextFrame } = replayCore( platform, nativeSpriteSettings, FullTestGame(gameProps) ); let time = 1; const nextFrame = () => { time += 1000 * (1 / 60); runNextFrame(time, jest.fn()); }; mutInputs.ref.buttonPressed.alert.ok = true; nextFrame(); expect(alertSpy.ok).toBeCalled(); expect(logSpy).toBeCalledWith("Hit ok"); mutInputs.ref.buttonPressed.alert.okCancel = true; nextFrame(); expect(alertSpy.okCancel).toBeCalled(); expect(logSpy).toBeCalledWith("Was ok: true"); }); test("can copy to clipboard", () => { const { platform, mutableTestDevice, mutInputs } = getTestPlatform(); const logSpy = jest.spyOn(mutableTestDevice, "log"); const { clipboard } = mutableTestDevice; const clipboardSpy = { copy: jest.spyOn(clipboard, "copy"), }; const { runNextFrame } = replayCore( platform, nativeSpriteSettings, FullTestGame(gameProps) ); let time = 1; const nextFrame = () => { time += 1000 * (1 / 60); runNextFrame(time, jest.fn()); }; expect(clipboardSpy.copy).not.toHaveBeenCalled(); mutInputs.ref.buttonPressed.clipboard.copyMessage = "Hello clipboard"; nextFrame(); expect(clipboardSpy.copy).toBeCalledWith( "Hello clipboard", expect.any(Function) ); expect(logSpy).toBeCalledWith("Copied"); mutInputs.ref.buttonPressed.clipboard.copyMessage = "Error"; nextFrame(); expect(clipboardSpy.copy).toBeCalledWith("Error", expect.any(Function)); expect(logSpy).toBeCalledWith("Error copying: !"); }); test("can define various texture shapes", () => { expect( t.text({ font: { family: "Arial", size: 12 }, text: "Hello", color: "red", }).type ).toBe("text"); expect( t.circle({ radius: 5, color: "red", x: 0, }).type ).toBe("circle"); expect( t.rectangle({ width: 5, height: 5, color: "red", x: 0, y: 0, }).type ).toBe("rectangle"); expect( t.line({ thickness: 5, color: "red", path: [ [10, 10], [15, 10], [20, 20], ], }).type ).toBe("line"); expect( t.image({ fileName: "image.png", width: 20, height: 20, }).type ).toBe("image"); }); test("supports masks on Sprites", () => { const { platform, masks } = getTestPlatform(); replayCore(platform, nativeSpriteSettings, MaskGame(gameProps)); expect(masks[0]).toEqual({ type: "circleMask", x: 5, y: -5, radius: 10, }); const circleMask = masks[1]; const rectMask = masks[2]; const lineMask = masks[3]; expect(circleMask).toEqual({ type: "circleMask", x: 10, y: 0, radius: 5, }); expect(rectMask).toEqual({ type: "rectangleMask", x: 0, y: 10, width: 5, height: 5, }); expect(lineMask).toEqual({ type: "lineMask", path: [ [0, 0], [10, 0], [10, 10], ], }); }); test("deeply nested input position", () => { // Note: deeply nested sprite positions are handled by the platforms (there's // a test case for this in replay-test) const { platform, mutableTestDevice, mutInputs, textures, } = getTestPlatform(); const logSpy = jest.spyOn(mutableTestDevice, "log"); mutInputs.ref.x = 50; mutInputs.ref.y = 50; replayCore(platform, nativeSpriteSettings, NestedSpriteGame(gameProps)); // Sprite positions local const nested = textures[0]; // These props are local to sprite and calculated on platform side expect(nested.props.x).toBe(10); expect(nested.props.y).toBe(20); expect(nested.props.rotation).toBe(180); expect(nested.props.opacity).toBe(0.8); // Pointer positions global expect(logSpy).toBeCalledWith("NestedSpriteGame x: 50, y: 50"); expect(logSpy).toBeCalledWith("NestedFirstSprite x: 30, y: -30"); expect(logSpy).toBeCalledWith("NestedSecondSprite x: -50, y: 20"); }); test("nested sprites and input position with scale", () => { const { platform, mutableTestDevice, mutInputs } = getTestPlatform(); const logSpy = jest.spyOn(mutableTestDevice, "log"); mutInputs.ref.x = 10; mutInputs.ref.y = 10; replayCore(platform, nativeSpriteSettings, NestedSpriteGame2(gameProps)); expect(logSpy).toBeCalledWith("NestedFirstSprite2 x: -20, y: -10"); }); test("loop and render order for callback prop change on low render FPS", () => { const { platform, mutableTestDevice } = getTestPlatform(); const resetInputs = jest.fn(); const { runNextFrame } = replayCore( platform, nativeSpriteSettings, CallbackPropGame(gameProps) ); let time = 1; const nextFrame = () => { // note time skips 3 frames here time += 1000 * (3 / 60); runNextFrame(time, resetInputs); }; expect(mutableTestDevice.log).not.toHaveBeenCalled(); nextFrame(); expect(mutableTestDevice.log).toBeCalledTimes(3); // loop called 3 times expect(mutableTestDevice.log).toHaveBeenNthCalledWith(1, 1); expect(mutableTestDevice.log).toHaveBeenNthCalledWith(2, 2); expect(mutableTestDevice.log).toHaveBeenNthCalledWith(3, 3); expect(resetInputs).toBeCalledTimes(3); nextFrame(); expect(mutableTestDevice.log).toBeCalledTimes(6); expect(mutableTestDevice.log).toHaveBeenNthCalledWith(4, 4); expect(mutableTestDevice.log).toHaveBeenNthCalledWith(5, 5); expect(mutableTestDevice.log).toHaveBeenNthCalledWith(6, 6); expect(resetInputs).toBeCalledTimes(6); nextFrame(); expect(mutableTestDevice.log).toBeCalledTimes(9); expect(mutableTestDevice.log).toHaveBeenNthCalledWith(7, 7); expect(mutableTestDevice.log).toHaveBeenNthCalledWith(8, 8); expect(mutableTestDevice.log).toHaveBeenNthCalledWith(9, 9); expect(resetInputs).toBeCalledTimes(9); }); test("calls cleanup when unmounting Sprites", async () => { const { platform, mutableTestDevice, mutInputs } = getTestPlatform(); const resetInputs = jest.fn(); const { runNextFrame } = replayCore( platform, nativeSpriteSettings, AssetsGame(gameProps) ); let time = 1; const nextFrame = () => { time += 1000 * (1 / 60); runNextFrame(time, resetInputs); }; await waitFrame(); nextFrame(); expect(mutableTestDevice.log).not.toHaveBeenCalledWith("cleanup"); mutInputs.ref.buttonPressed.show = false; nextFrame(); expect(mutableTestDevice.log).toHaveBeenCalledWith("cleanup"); }); test("can preload and clear file assets", async () => { const { platform, mutableTestDevice, mutInputs, textures, } = getTestPlatform(); const resetInputs = jest.fn(); const { runNextFrame } = replayCore( platform, nativeSpriteSettings, AssetsGame(gameProps) ); let time = 1; const nextFrame = () => { time += 1000 * (1 / 60); runNextFrame(time, resetInputs); }; expect(textures.length).toBe(1); expect((textures[0] as TextTexture).props.text).toBe("Loading"); expect(mutableTestDevice.assetUtils.loadAudioFile).toHaveBeenCalledTimes(1); expect(mutableTestDevice.assetUtils.loadAudioFile).toHaveBeenCalledWith( "game.mp3" ); expect(mutableTestDevice.assetUtils.loadImageFile).toHaveBeenCalledTimes(1); expect(mutableTestDevice.assetUtils.loadImageFile).toHaveBeenCalledWith( "game.png" ); expect(mutableTestDevice.assetUtils.audioElements).toEqual({ "game.mp3": { globalSpriteIds: ["Game"], // Loading Promise data: expect.not.stringMatching("audioData"), }, }); expect(mutableTestDevice.assetUtils.imageElements).toEqual({ "game.png": { globalSpriteIds: ["Game"], // Loading Promise data: expect.not.stringMatching("imageData"), }, }); // Wait for callback on next frame await waitFrame(); expect(mutableTestDevice.assetUtils.audioElements).toEqual({ "game.mp3": { globalSpriteIds: ["Game"], data: "audioData", }, }); expect(mutableTestDevice.assetUtils.imageElements).toEqual({ "game.png": { globalSpriteIds: ["Game"], data: "imageData", }, }); nextFrame(); // No longer loading expect( textures[0].type !== "text" || textures[0].props.text !== "Loading" ).toBe(true); // Sprite & nested sprite start loading - but no duplicate parallel loads // (called 2 not 3 times) expect(mutableTestDevice.assetUtils.loadImageFile).toHaveBeenCalledTimes(2); // Wait for sprites to load await waitFrame(); expect(mutableTestDevice.assetUtils.imageElements).toEqual({ "game.png": { globalSpriteIds: ["Game"], data: "imageData", }, "a.png": { globalSpriteIds: ["Game--Sprite1", "Game--Sprite1--NestedSprite"], data: "imageData", }, }); // Unmount Sprites mutInputs.ref.buttonPressed.show = false; nextFrame(); // Need resolved promise to be called await waitFrame(); // a.png removed expect("a.png" in mutableTestDevice.assetUtils.imageElements).toBe(false); expect(mutableTestDevice.assetUtils.cleanupImageFile).toHaveBeenCalledTimes( 1 ); }); test("Sprite unmounted before it loads", async () => { const { platform, mutableTestDevice, mutInputs } = getTestPlatform(); const resetInputs = jest.fn(); const { runNextFrame } = replayCore( platform, nativeSpriteSettings, AssetsGame(gameProps) ); let time = 1; const nextFrame = () => { time += 1000 * (1 / 60); runNextFrame(time, resetInputs); }; // Load initial assets await waitFrame(); nextFrame(); // Sprites have started loading expect(mutableTestDevice.assetUtils.loadImageFile).toHaveBeenCalledTimes(2); // Unmount Sprites before they finish loading mutInputs.ref.buttonPressed.show = false; nextFrame(); // Wait for promises to load await waitFrame(); // Image not in memory expect("a.png" in mutableTestDevice.assetUtils.imageElements).toBe(false); // Was cleaned up expect(mutableTestDevice.assetUtils.cleanupImageFile).toHaveBeenCalledTimes( 1 ); }); test("Sprite unmounted and remounted before it loads", async () => { const { platform, mutableTestDevice, mutInputs } = getTestPlatform(); const resetInputs = jest.fn(); const { runNextFrame } = replayCore( platform, nativeSpriteSettings, AssetsUnmountRemountGame(gameProps) ); let time = 1; const nextFrame = () => { time += 1000 * (1 / 60); runNextFrame(time, resetInputs); }; nextFrame(); // Sprites have started loading expect(mutableTestDevice.assetUtils.loadAudioFile).toHaveBeenCalledTimes(1); expect(mutableTestDevice.log).toBeCalledTimes(1); expect(mutableTestDevice.log).toHaveBeenCalledWith("init"); // Unmount Sprites before they finish loading mutInputs.ref.buttonPressed.show = false; nextFrame(); // No cleanup yet expect(mutableTestDevice.assetUtils.cleanupAudioFile).toHaveBeenCalledTimes( 0 ); // Remount Sprites before they finish loading mutInputs.ref.buttonPressed.show = true; nextFrame(); expect(mutableTestDevice.log).toBeCalledTimes(2); expect(mutableTestDevice.log).toHaveBeenLastCalledWith("init"); // Wait for promises to load await waitFrame(); // Still in memory expect("game.mp3" in mutableTestDevice.assetUtils.audioElements).toBe(true); // Still no cleanup expect(mutableTestDevice.assetUtils.cleanupAudioFile).toHaveBeenCalledTimes( 0 ); }); test("throws error on duplicate Sprites", () => { const { platform } = getTestPlatform(); expect(() => { replayCore( platform, nativeSpriteSettings, DuplicateSpriteIdsGame(gameProps) ); }).toThrowError("Duplicate Sprite id TestSprite"); }); test("throws error on duplicate Pure Sprites", () => { const { platform } = getTestPlatform(); expect(() => { replayCore( platform, nativeSpriteSettings, DuplicatePureSpriteIdsGame(gameProps) ); }).toThrowError("Duplicate Sprite id TestSprite"); }); test("supports Pure Sprites", () => { const { platform, mutInputs } = getTestPlatform(); const { runNextFrame } = replayCore( platform, nativeSpriteSettings, PureSpriteGame(gameProps) ); let time = 1; const nextFrame = () => { time += 1000 * (1 / 60); runNextFrame(time, jest.fn()); }; expect(pureSpriteAlwaysRendersFn).toBeCalledTimes(1); expect(pureSpriteNeverRendersFn).toBeCalledTimes(1); expect(pureSpriteConditionalRendersFn).toBeCalledTimes(1); nextFrame(); expect(pureSpriteAlwaysRendersFn).toBeCalledTimes(2); expect(pureSpriteNeverRendersFn).toBeCalledTimes(1); expect(pureSpriteConditionalRendersFn).toBeCalledTimes(1); mutInputs.ref.buttonPressed.show = false; nextFrame(); expect(pureSpriteAlwaysRendersFn).toBeCalledTimes(3); expect(pureSpriteNeverRendersFn).toBeCalledTimes(1); expect(pureSpriteConditionalRendersFn).toBeCalledTimes(2); }); test("supports Native Sprites", () => { const { platform, mutInputs, textures } = getTestPlatform(); const mutableNativeSpriteUtils: NativeSpriteUtils = { didResize: false, scale: 3, gameXToPlatformX: (x) => x + 10, gameYToPlatformY: (y) => y - 10, }; const { runNextFrame } = replayCore( platform, { nativeSpriteUtils: mutableNativeSpriteUtils, nativeSpriteMap: { MyWidget: MyWidgetImplementation }, }, NativeSpriteGame(gameProps) ); // No Textures rendered expect(textures.length).toBe(0); expect(widgetState).toEqual({ // test props text: "hello", // test gameXToPlatformX x: 10, // test gameYToPlatformY y: -10, // test parentGlobalId globalId: "Game--nested--widget", width: 100, }); let time = 1; const nextFrame = () => { time += 1000 * (1 / 60); runNextFrame(time, jest.fn()); }; nextFrame(); // test loop and didResize doubles width mutableNativeSpriteUtils.didResize = true; nextFrame(); expect(widgetState.width).toBe(300); // scale x3 mutableNativeSpriteUtils.didResize = false; // test getState and updateState in callback widgetCallback(); nextFrame(); expect(widgetState.x).toBe(20); // test cleanup mutInputs.ref.x = 100; nextFrame(); expect(widgetState.text).toBe(""); }); test("supports context", () => { const { platform, mutableTestDevice, mutInputs } = getTestPlatform(); const resetInputs = jest.fn(); const { runNextFrame } = replayCore( platform, nativeSpriteSettings, TestContextGame(gameProps) ); let time = 1; const nextFrame = () => { time += 1000 * (1 / 60); runNextFrame(time, resetInputs); }; expect(mutableTestDevice.log).toBeCalledTimes(1); expect(mutableTestDevice.log).toHaveBeenCalledWith("Count: 0"); nextFrame(); expect(mutableTestDevice.log).toBeCalledTimes(2); expect(mutableTestDevice.log).toHaveBeenCalledWith("Count: 1"); mutInputs.ref.buttonPressed.action = true; // increaseCountBy10 is called this frame nextFrame(); expect(mutableTestDevice.log).toBeCalledTimes(3); expect(mutableTestDevice.log).toHaveBeenCalledWith("Count: 2"); mutInputs.ref.buttonPressed.action = false; // so result is seen this frame nextFrame(); expect(mutableTestDevice.log).toBeCalledTimes(4); expect(mutableTestDevice.log).toHaveBeenCalledWith("Count: 13"); }); test("context will throw error if not passed in", () => { const { platform } = getTestPlatform(); expect(() => replayCore(platform, nativeSpriteSettings, TestContextErrorGame(gameProps)) ).toThrowError("No context setup"); });
the_stack
//support v4 23.1.0 module android.support.v4.view { import View = android.view.View; import Gravity = android.view.Gravity; import MeasureSpec = View.MeasureSpec; import OverScroller = android.widget.OverScroller; import ViewGroup = android.view.ViewGroup; import Interpolator = android.view.animation.Interpolator; import ArrayList = java.util.ArrayList; import Rect = android.graphics.Rect; import PagerAdapter = android.support.v4.view.PagerAdapter; import Observable = android.database.Observable; import DataSetObservable = android.database.DataSetObservable; import DataSetObserver = android.database.DataSetObserver; import Drawable = android.graphics.drawable.Drawable; import VelocityTracker = android.view.VelocityTracker; import ViewConfiguration = android.view.ViewConfiguration; import Runnable = java.lang.Runnable; import Resources = android.content.res.Resources; import Log = android.util.Log; import MotionEvent = android.view.MotionEvent; import KeyEvent = android.view.KeyEvent; const TAG = "ViewPager"; const DEBUG = false; const SymbolDecor = Symbol(); /** * Layout manager that allows the user to flip left and right * through pages of data. You supply an implementation of a * {@link PagerAdapter} to generate the pages that the view shows. * * <p>Note this class is currently under early design and * development. The API will likely change in later updates of * the compatibility library, requiring changes to the source code * of apps when they are compiled against the newer version.</p> * * <p>ViewPager is most often used in conjunction with {@link android.app.Fragment}, * which is a convenient way to supply and manage the lifecycle of each page. * There are standard adapters implemented for using fragments with the ViewPager, * which cover the most common use cases. These are * {@link android.support.v4.app.FragmentPagerAdapter} and * {@link android.support.v4.app.FragmentStatePagerAdapter}; each of these * classes have simple code showing how to build a full user interface * with them. * * <p>Here is a more complicated example of ViewPager, using it in conjuction * with {@link android.app.ActionBar} tabs. You can find other examples of using * ViewPager in the API 4+ Support Demos and API 13+ Support Demos sample code. * * {@sample development/samples/Support13Demos/src/com/example/android/supportv13/app/ActionBarTabsPager.java * complete} */ export class ViewPager extends ViewGroup { /** * Used to track what the expected number of items in the adapter should be. * If the app changes this when we don't expect it, we'll throw a big obnoxious exception. */ private mExpectedAdapterCount = 0; private static COMPARATOR = (lhs:ItemInfo, rhs:ItemInfo):number=> { return lhs.position - rhs.position; }; private static USE_CACHE = false; private static DEFAULT_OFFSCREEN_PAGES = 1; private static MAX_SETTLE_DURATION = 600; // ms private static MIN_DISTANCE_FOR_FLING = 25; // dips private static DEFAULT_GUTTER_SIZE = 16; // dips private static MIN_FLING_VELOCITY = 400; // dips private static sInterpolator:Interpolator = { getInterpolation(t:number):number { t -= 1.0; return t * t * t * t * t + 1.0; } }; private mItems = new ArrayList<ItemInfo>(); private mTempItem = new ItemInfo(); private mTempRect = new Rect(); private mAdapter:PagerAdapter; private mCurItem:number = 0;// Index of currently displayed page. private mRestoredCurItem = -1; private mScroller:OverScroller; private mObserver:PagerObserver; private mPageMargin:number = 0; private mMarginDrawable:Drawable; private mTopPageBounds:number = 0; private mBottomPageBounds:number = 0; // Offsets of the first and last items, if known. // Set during population, used to determine if we are at the beginning // or end of the pager data set during touch scrolling. private mFirstOffset = -Number.MAX_VALUE; private mLastOffset = Number.MAX_VALUE; private mChildWidthMeasureSpec:number = 0; private mChildHeightMeasureSpec:number = 0; private mInLayout = false; private mScrollingCacheEnabled = false; private mPopulatePending = false; private mOffscreenPageLimit = ViewPager.DEFAULT_OFFSCREEN_PAGES; private mIsBeingDragged = false; private mIsUnableToDrag = false; private mDefaultGutterSize:number = 0; private mGutterSize:number = 0; //private mTouchSlop: number = 0; /** * Position of the last motion event. */ private mLastMotionX = 0; private mLastMotionY = 0; private mInitialMotionX = 0; private mInitialMotionY = 0; private static INVALID_POINTER = -1; /** * ID of the active pointer. This is used to retain consistency during * drags/flings if multiple pointers are used. */ private mActivePointerId = ViewPager.INVALID_POINTER; /** * Determines speed during touch scrolling */ private mVelocityTracker:VelocityTracker; private mMinimumVelocity:number = 0; private mMaximumVelocity:number = 0; private mFlingDistance:number = 0; private mCloseEnough:number = 0; // If the pager is at least this close to its final position, complete the scroll // on touch down and let the user interact with the content inside instead of // "catching" the flinging pager. private static CLOSE_ENOUGH = 2; // dp private mFakeDragging = false; private mFakeDragBeginTime = 0; //private mLeftEdge: EdgeEffectCompat; //private mRightEdge: EdgeEffectCompat; private mFirstLayout = true; private mNeedCalculatePageOffsets = false; private mCalledSuper = false; private mDecorChildCount:number = 0; private mOnPageChangeListeners:ArrayList<ViewPager.OnPageChangeListener>; private mOnPageChangeListener:ViewPager.OnPageChangeListener; private mInternalPageChangeListener:ViewPager.OnPageChangeListener; private mAdapterChangeListener:ViewPager.OnAdapterChangeListener; private mPageTransformer:ViewPager.PageTransformer; //private mSetChildrenDrawingOrderEnabled: Method; private static DRAW_ORDER_DEFAULT = 0; private static DRAW_ORDER_FORWARD = 1; private static DRAW_ORDER_REVERSE = 2; private mDrawingOrder:number = 0; private mDrawingOrderedChildren:ArrayList<View>; private static sPositionComparator = (lhs:View, rhs:View):number=> { let llp = <ViewPager.LayoutParams>lhs.getLayoutParams(); let rlp = <ViewPager.LayoutParams>rhs.getLayoutParams(); if (llp.isDecor != rlp.isDecor) { return llp.isDecor ? 1 : -1; } return llp.position - rlp.position }; /** * Indicates that the pager is in an idle, settled state. The current page * is fully in view and no animation is in progress. */ static SCROLL_STATE_IDLE = 0 /** * Indicates that the pager is currently being dragged by the user. */ static SCROLL_STATE_DRAGGING = 1 /** * Indicates that the pager is in the process of settling to a final position. */ static SCROLL_STATE_SETTLING = 2 private mEndScrollRunnable = (()=>{ let ViewPager_this = this; class InnerClass implements Runnable{ run() { (<any>ViewPager_this).setScrollState(ViewPager.SCROLL_STATE_IDLE); (<any>ViewPager_this).populate(); } } return new InnerClass(); })(); private mScrollState = ViewPager.SCROLL_STATE_IDLE; constructor(context:android.content.Context, bindElement?:HTMLElement, defStyle?){ super(context, bindElement, defStyle); this.initViewPager(); } private initViewPager() { this.setWillNotDraw(false) this.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS); this.setFocusable(true); //let context = getContext() this.mScroller = new OverScroller(ViewPager.sInterpolator) //let configuration = ViewConfiguration.get(context) let density = Resources.getDisplayMetrics().density this.mTouchSlop = ViewConfiguration.get().getScaledPagingTouchSlop() this.mMinimumVelocity = Math.floor(ViewPager.MIN_FLING_VELOCITY * density); this.mMaximumVelocity = ViewConfiguration.get().getScaledMaximumFlingVelocity() //this.mLeftEdge = EdgeEffectCompat(context) //this.mRightEdge = EdgeEffectCompat(context) this.mFlingDistance = Math.floor(ViewPager.MIN_DISTANCE_FOR_FLING * density) this.mCloseEnough = Math.floor(ViewPager.CLOSE_ENOUGH * density) this.mDefaultGutterSize = Math.floor(ViewPager.DEFAULT_GUTTER_SIZE * density) //ViewCompat.setAccessibilityDelegate(this, MyAccessibilityDelegate()) //if (ViewCompat.getImportantForAccessibility(this) == ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) { // ViewCompat.setImportantForAccessibility(this, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES) //} } protected onDetachedFromWindow():void { this.removeCallbacks(this.mEndScrollRunnable); super.onDetachedFromWindow(); } private setScrollState(newState:number) { if (this.mScrollState == newState) { return; } this.mScrollState = newState; if (this.mPageTransformer != null) { // PageTransformers can do complex things that benefit from hardware layers. this.enableLayers(newState != ViewPager.SCROLL_STATE_IDLE); } this.dispatchOnScrollStateChanged(newState); } /** * Set a PagerAdapter that will supply views for this pager as needed. * @param adapter Adapter to use */ setAdapter(adapter:PagerAdapter):void { if (this.mAdapter != null) { this.mAdapter.unregisterDataSetObserver(this.mObserver); this.mAdapter.startUpdate(this); for (let i = 0; i < this.mItems.size(); i++) { const ii = this.mItems.get(i); this.mAdapter.destroyItem(this, ii.position, ii.object); } this.mAdapter.finishUpdate(this); this.mItems.clear(); this.removeNonDecorViews(); this.mCurItem = 0; this.scrollTo(0, 0); } const oldAdapter = this.mAdapter; this.mAdapter = adapter; this.mExpectedAdapterCount = 0; if (this.mAdapter != null) { if (this.mObserver == null) { this.mObserver = new PagerObserver(this); } this.mAdapter.registerDataSetObserver(this.mObserver); this.mPopulatePending = false; const wasFirstLayout = this.mFirstLayout; this.mFirstLayout = true; this.mExpectedAdapterCount = this.mAdapter.getCount(); if (this.mRestoredCurItem >= 0) { //this.mAdapter.restoreState(this.mRestoredAdapterState, this.mRestoredClassLoader); this.setCurrentItemInternal(this.mRestoredCurItem, false, true); this.mRestoredCurItem = -1; //this.mRestoredAdapterState = null; //this.mRestoredClassLoader = null; } else if (!wasFirstLayout) { this.populate(); } else { this.requestLayout(); } } if (this.mAdapterChangeListener != null && oldAdapter != adapter) { this.mAdapterChangeListener.onAdapterChanged(oldAdapter, adapter); } } private removeNonDecorViews() { for (let i = 0; i < this.getChildCount(); i++) { const child = this.getChildAt(i); const lp = <ViewPager.LayoutParams>child.getLayoutParams(); if (!lp.isDecor) { this.removeViewAt(i); i--; } } } /** * Retrieve the current adapter supplying pages. * * @return The currently registered PagerAdapter */ public getAdapter():PagerAdapter { return this.mAdapter; } setOnAdapterChangeListener(listener:ViewPager.OnAdapterChangeListener):void { this.mAdapterChangeListener = listener; } private getClientWidth() { return this.getMeasuredWidth() - this.getPaddingLeft() - this.getPaddingRight(); } /** * Set the currently selected page. * * @param item Item index to select * @param smoothScroll True to smoothly scroll to the new item, false to transition immediately */ public setCurrentItem(item:number, smoothScroll = !this.mFirstLayout):void { this.mPopulatePending = false; this.setCurrentItemInternal(item, smoothScroll, false); } getCurrentItem():number { return this.mCurItem; } setCurrentItemInternal(item:number, smoothScroll:boolean, always:boolean, velocity = 0) { if (this.mAdapter == null || this.mAdapter.getCount() <= 0) { this.setScrollingCacheEnabled(false); return; } if (!always && this.mCurItem == item && this.mItems.size() != 0) { this.setScrollingCacheEnabled(false); return; } if (item < 0) { item = 0; } else if (item >= this.mAdapter.getCount()) { item = this.mAdapter.getCount() - 1; } const pageLimit = this.mOffscreenPageLimit; if (item > (this.mCurItem + pageLimit) || item < (this.mCurItem - pageLimit)) { // We are doing a jump by more than one page. To avoid // glitches, we want to keep all current pages in the view // until the scroll ends. for (let i = 0; i < this.mItems.size(); i++) { this.mItems.get(i).scrolling = true; } } const dispatchSelected = this.mCurItem != item; if (this.mFirstLayout) { // We don't have any idea how big we are yet and shouldn't have any pages either. // Just set things up and let the pending layout handle things. this.mCurItem = item; if (dispatchSelected) { this.dispatchOnPageSelected(item); } this.requestLayout(); } else { this.populate(item); this.scrollToItem(item, smoothScroll, velocity, dispatchSelected); } } private scrollToItem(item:number, smoothScroll:boolean, velocity:number, dispatchSelected:boolean) { const curInfo = this.infoForPosition(item); let destX = 0; if (curInfo != null) { const width = this.getClientWidth(); destX = Math.floor(width * Math.max(this.mFirstOffset, Math.min(curInfo.offset, this.mLastOffset))); } if (smoothScroll) { this.smoothScrollTo(destX, 0, velocity); if (dispatchSelected) { this.dispatchOnPageSelected(item); } } else { if (dispatchSelected) { this.dispatchOnPageSelected(item); } this.completeScroll(false); this.scrollTo(destX, 0); this.pageScrolled(destX); } } /** * Set a listener that will be invoked whenever the page changes or is incrementally * scrolled. See {@link OnPageChangeListener}. * * @param listener Listener to set * * @deprecated Use {@link #addOnPageChangeListener(OnPageChangeListener)} * and {@link #removeOnPageChangeListener(OnPageChangeListener)} instead. */ setOnPageChangeListener(listener:ViewPager.OnPageChangeListener) { this.mOnPageChangeListener = listener; } /** * Add a listener that will be invoked whenever the page changes or is incrementally * scrolled. See {@link OnPageChangeListener}. * * <p>Components that add a listener should take care to remove it when finished. * Other components that take ownership of a view may call {@link #clearOnPageChangeListeners()} * to remove all attached listeners.</p> * * @param listener listener to add */ addOnPageChangeListener(listener:ViewPager.OnPageChangeListener) { if (this.mOnPageChangeListeners == null) { this.mOnPageChangeListeners = new ArrayList<ViewPager.OnPageChangeListener>(); } this.mOnPageChangeListeners.add(listener); } /** * Remove a listener that was previously added via * {@link #addOnPageChangeListener(OnPageChangeListener)}. * * @param listener listener to remove */ removeOnPageChangeListener(listener:ViewPager.OnPageChangeListener) { if (this.mOnPageChangeListeners != null) { this.mOnPageChangeListeners.remove(listener); } } /** * Remove all listeners that are notified of any changes in scroll state or position. */ clearOnPageChangeListeners() { if (this.mOnPageChangeListeners != null) { this.mOnPageChangeListeners.clear(); } } /** * Set a {@link PageTransformer} that will be called for each attached page whenever * the scroll position is changed. This allows the application to apply custom property * transformations to each page, overriding the default sliding look and feel. * * <p><em>Note:</em> Prior to Android 3.0 the property animation APIs did not exist. * As a result, setting a PageTransformer prior to Android 3.0 (API 11) will have no effect.</p> * * @param reverseDrawingOrder true if the supplied PageTransformer requires page views * to be drawn from last to first instead of first to last. * @param transformer PageTransformer that will modify each page's animation properties */ setPageTransformer(reverseDrawingOrder:boolean, transformer:ViewPager.PageTransformer) { const hasTransformer = transformer != null; const needsPopulate = hasTransformer != (this.mPageTransformer != null); this.mPageTransformer = transformer; this.setChildrenDrawingOrderEnabledCompat(hasTransformer); if (hasTransformer) { this.mDrawingOrder = reverseDrawingOrder ? ViewPager.DRAW_ORDER_REVERSE : ViewPager.DRAW_ORDER_FORWARD; } else { this.mDrawingOrder = ViewPager.DRAW_ORDER_DEFAULT; } if (needsPopulate) this.populate(); } setChildrenDrawingOrderEnabledCompat(enable=true) { this.setChildrenDrawingOrderEnabled(enable); } getChildDrawingOrder(childCount:number, i:number):number { const index = this.mDrawingOrder == ViewPager.DRAW_ORDER_REVERSE ? childCount - 1 - i : i; const result = (<ViewPager.LayoutParams>this.mDrawingOrderedChildren.get(index).getLayoutParams()).childIndex; return result; } /** * Set a separate OnPageChangeListener for internal use by the support library. * * @param listener Listener to set * @return The old listener that was set, if any. */ setInternalPageChangeListener(listener:ViewPager.OnPageChangeListener):ViewPager.OnPageChangeListener { let oldListener = this.mInternalPageChangeListener; this.mInternalPageChangeListener = listener; return oldListener; } /** * Returns the number of pages that will be retained to either side of the * current page in the view hierarchy in an idle state. Defaults to 1. * * @return How many pages will be kept offscreen on either side * @see #setOffscreenPageLimit(int) */ getOffscreenPageLimit():number { return this.mOffscreenPageLimit; } /** * Set the number of pages that should be retained to either side of the * current page in the view hierarchy in an idle state. Pages beyond this * limit will be recreated from the adapter when needed. * * <p>This is offered as an optimization. If you know in advance the number * of pages you will need to support or have lazy-loading mechanisms in place * on your pages, tweaking this setting can have benefits in perceived smoothness * of paging animations and interaction. If you have a small number of pages (3-4) * that you can keep active all at once, less time will be spent in layout for * newly created view subtrees as the user pages back and forth.</p> * * <p>You should keep this limit low, especially if your pages have complex layouts. * This setting defaults to 1.</p> * * @param limit How many pages will be kept offscreen in an idle state. */ setOffscreenPageLimit(limit:number):void { if (limit < ViewPager.DEFAULT_OFFSCREEN_PAGES) { Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to " + ViewPager.DEFAULT_OFFSCREEN_PAGES); limit = ViewPager.DEFAULT_OFFSCREEN_PAGES; } if (limit != this.mOffscreenPageLimit) { this.mOffscreenPageLimit = limit; this.populate(); } } /** * Set the margin between pages. * * @param marginPixels Distance between adjacent pages in pixels * @see #getPageMargin() * @see #setPageMarginDrawable(Drawable) * @see #setPageMarginDrawable(int) */ setPageMargin(marginPixels:number):void { const oldMargin = this.mPageMargin; this.mPageMargin = marginPixels; const width = this.getWidth(); this.recomputeScrollPosition(width, width, marginPixels, oldMargin); this.requestLayout(); } /** * Return the margin between pages. * * @return The size of the margin in pixels */ getPageMargin():number { return this.mPageMargin; } /** * Set a drawable that will be used to fill the margin between pages. * * @param d Drawable to display between pages */ setPageMarginDrawable(d:Drawable):void { this.mMarginDrawable = d; if (d != null) this.refreshDrawableState(); this.setWillNotDraw(d == null); this.invalidate(); } protected verifyDrawable(who:Drawable):boolean{ return super.verifyDrawable(who) || who == this.mMarginDrawable; } protected drawableStateChanged():void { super.drawableStateChanged(); const d = this.mMarginDrawable; if (d != null && d.isStateful()) { d.setState(this.getDrawableState()); } } // We want the duration of the page snap animation to be influenced by the distance that // the screen has to travel, however, we don't want this duration to be effected in a // purely linear fashion. Instead, we use this method to moderate the effect that the distance // of travel has on the overall snap duration. distanceInfluenceForSnapDuration(f:number):number { f -= 0.5; // center the values about 0. f *= 0.3 * Math.PI / 2.0; return Math.sin(f); } /** * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. * * @param x the number of pixels to scroll by on the X axis * @param y the number of pixels to scroll by on the Y axis */ smoothScrollTo(x:number, y:number, velocity=0):void { if (this.getChildCount() == 0) { // Nothing to do. this.setScrollingCacheEnabled(false); return; } let sx = this.getScrollX(); let sy = this.getScrollY(); let dx = x - sx; let dy = y - sy; if (dx == 0 && dy == 0) { this.completeScroll(false); this.populate(); this.setScrollState(ViewPager.SCROLL_STATE_IDLE); return; } this.setScrollingCacheEnabled(true); this.setScrollState(ViewPager.SCROLL_STATE_SETTLING); const width = this.getClientWidth(); const halfWidth = width / 2; const distanceRatio = Math.min(1, 1.0 * Math.abs(dx) / width); const distance = halfWidth + halfWidth * this.distanceInfluenceForSnapDuration(distanceRatio); let duration = 0; velocity = Math.abs(velocity); if (velocity > 0) { duration = 4 * Math.round(1000 * Math.abs(distance / velocity)); } else { const pageWidth = width * this.mAdapter.getPageWidth(this.mCurItem); const pageDelta = Math.abs(dx) / (pageWidth + this.mPageMargin); duration = Math.floor((pageDelta + 1) * 100); } duration = Math.min(duration, ViewPager.MAX_SETTLE_DURATION); this.mScroller.startScroll(sx, sy, dx, dy, duration); this.postInvalidateOnAnimation(); } private addNewItem(position:number, index:number):ItemInfo { let ii = new ItemInfo(); ii.position = position; ii.object = this.mAdapter.instantiateItem(this, position); ii.widthFactor = this.mAdapter.getPageWidth(position); if (index < 0 || index >= this.mItems.size()) { this.mItems.add(ii); } else { this.mItems.add(index, ii); } return ii; } dataSetChanged() { // This method only gets called if our observer is attached, so mAdapter is non-null. const adapterCount = this.mAdapter.getCount(); this.mExpectedAdapterCount = adapterCount; let needPopulate = this.mItems.size() < this.mOffscreenPageLimit * 2 + 1 && this.mItems.size() < adapterCount; let newCurrItem = this.mCurItem; let isUpdating = false; for (let i = 0; i < this.mItems.size(); i++) { const ii = this.mItems.get(i); const newPos = this.mAdapter.getItemPosition(ii.object); if (newPos == PagerAdapter.POSITION_UNCHANGED) { continue; } if (newPos == PagerAdapter.POSITION_NONE) { this.mItems.remove(i); i--; if (!isUpdating) { this.mAdapter.startUpdate(this); isUpdating = true; } this.mAdapter.destroyItem(this, ii.position, ii.object); needPopulate = true; if (this.mCurItem == ii.position) { // Keep the current item in the valid range newCurrItem = Math.max(0, Math.min(this.mCurItem, adapterCount - 1)); needPopulate = true; } continue; } if (ii.position != newPos) { if (ii.position == this.mCurItem) { // Our current item changed position. Follow it. newCurrItem = newPos; } ii.position = newPos; needPopulate = true; } } if (isUpdating) { this.mAdapter.finishUpdate(this); } this.mItems.sort(ViewPager.COMPARATOR); //Collections.sort(mItems, COMPARATOR); if (needPopulate) { // Reset our known page widths; populate will recompute them. const childCount = this.getChildCount(); for (let i = 0; i < childCount; i++) { const child = this.getChildAt(i); const lp = <ViewPager.LayoutParams>child.getLayoutParams(); if (!lp.isDecor) { lp.widthFactor = 0; } } this.setCurrentItemInternal(newCurrItem, false, true); this.requestLayout(); } } populate(newCurrentItem = this.mCurItem) { let oldCurInfo:ItemInfo = null; let focusDirection = View.FOCUS_FORWARD; if (this.mCurItem != newCurrentItem) { focusDirection = this.mCurItem < newCurrentItem ? View.FOCUS_RIGHT : View.FOCUS_LEFT; oldCurInfo = this.infoForPosition(this.mCurItem); this.mCurItem = newCurrentItem; } if (this.mAdapter == null) { this.sortChildDrawingOrder(); return; } // Bail now if we are waiting to populate. This is to hold off // on creating views from the time the user releases their finger to // fling to a new position until we have finished the scroll to // that position, avoiding glitches from happening at that point. if (this.mPopulatePending) { if (DEBUG) Log.i(TAG, "populate is pending, skipping for now..."); this.sortChildDrawingOrder(); return; } // Also, don't populate until we are attached to a window. This is to // avoid trying to populate before we have restored our view hierarchy // state and conflicting with what is restored. if (!this.isAttachedToWindow()) { return; } this.mAdapter.startUpdate(this); const pageLimit = this.mOffscreenPageLimit; const startPos = Math.max(0, this.mCurItem - pageLimit); const N = this.mAdapter.getCount(); const endPos = Math.min(N-1, this.mCurItem + pageLimit); if (N != this.mExpectedAdapterCount) { throw new Error("The application's PagerAdapter changed the adapter's" + " contents without calling PagerAdapter#notifyDataSetChanged!" + " Expected adapter item count: " + this.mExpectedAdapterCount + ", found: " + N + " Pager id: " + this.getId() + " Pager class: " + this.constructor.name + " Problematic adapter: " + this.mAdapter.constructor.name); } // Locate the currently focused item or add it if needed. let curIndex = -1; let curItem:ItemInfo = null; for (curIndex = 0; curIndex < this.mItems.size(); curIndex++) { const ii = this.mItems.get(curIndex); if (ii.position >= this.mCurItem) { if (ii.position == this.mCurItem) curItem = ii; break; } } if (curItem == null && N > 0) { curItem = this.addNewItem(this.mCurItem, curIndex); } // Fill 3x the available width or up to the number of offscreen // pages requested to either side, whichever is larger. // If we have no current item we have no work to do. if (curItem != null) { let extraWidthLeft = 0; let itemIndex = curIndex - 1; let ii = itemIndex >= 0 ? this.mItems.get(itemIndex) : null; const clientWidth = this.getClientWidth(); const leftWidthNeeded = clientWidth <= 0 ? 0 : 2 - curItem.widthFactor + this.getPaddingLeft() / clientWidth; for (let pos = this.mCurItem - 1; pos >= 0; pos--) { if (extraWidthLeft >= leftWidthNeeded && pos < startPos) { if (ii == null) { break; } if (pos == ii.position && !ii.scrolling) { this.mItems.remove(itemIndex); this.mAdapter.destroyItem(this, pos, ii.object); if (DEBUG) { Log.i(TAG, "populate() - destroyItem() with pos: " + pos + " view: " + (<View>ii.object)); } itemIndex--; curIndex--; ii = itemIndex >= 0 ? this.mItems.get(itemIndex) : null; } } else if (ii != null && pos == ii.position) { extraWidthLeft += ii.widthFactor; itemIndex--; ii = itemIndex >= 0 ? this.mItems.get(itemIndex) : null; } else { ii = this.addNewItem(pos, itemIndex + 1); extraWidthLeft += ii.widthFactor; curIndex++; ii = itemIndex >= 0 ? this.mItems.get(itemIndex) : null; } } let extraWidthRight = curItem.widthFactor; itemIndex = curIndex + 1; if (extraWidthRight < 2) { ii = itemIndex < this.mItems.size() ? this.mItems.get(itemIndex) : null; const rightWidthNeeded = clientWidth <= 0 ? 0 : this.getPaddingRight() / clientWidth + 2; for (let pos = this.mCurItem + 1; pos < N; pos++) { if (extraWidthRight >= rightWidthNeeded && pos > endPos) { if (ii == null) { break; } if (pos == ii.position && !ii.scrolling) { this.mItems.remove(itemIndex); this.mAdapter.destroyItem(this, pos, ii.object); if (DEBUG) { Log.i(TAG, "populate() - destroyItem() with pos: " + pos + " view: " + (<View>ii.object)); } ii = itemIndex < this.mItems.size() ? this.mItems.get(itemIndex) : null; } } else if (ii != null && pos == ii.position) { extraWidthRight += ii.widthFactor; itemIndex++; ii = itemIndex < this.mItems.size() ? this.mItems.get(itemIndex) : null; } else { ii = this.addNewItem(pos, itemIndex); itemIndex++; extraWidthRight += ii.widthFactor; ii = itemIndex < this.mItems.size() ? this.mItems.get(itemIndex) : null; } } } this.calculatePageOffsets(curItem, curIndex, oldCurInfo); } if (DEBUG) { Log.i(TAG, "Current page list:"); for (let i=0; i<this.mItems.size(); i++) { Log.i(TAG, "#" + i + ": page " + this.mItems.get(i).position); } } this.mAdapter.setPrimaryItem(this, this.mCurItem, curItem != null ? curItem.object : null); this.mAdapter.finishUpdate(this); // Check width measurement of current pages and drawing sort order. // Update LayoutParams as needed. const childCount = this.getChildCount(); for (let i = 0; i < childCount; i++) { const child = this.getChildAt(i); const lp = <ViewPager.LayoutParams>child.getLayoutParams(); lp.childIndex = i; if (!lp.isDecor && lp.widthFactor == 0) { // 0 means requery the adapter for this, it doesn't have a valid width. const ii = this.infoForChild(child); if (ii != null) { lp.widthFactor = ii.widthFactor; lp.position = ii.position; } } } this.sortChildDrawingOrder(); if (this.hasFocus()) { let currentFocused = this.findFocus(); let ii = currentFocused != null ? this.infoForAnyChild(currentFocused) : null; if (ii == null || ii.position != this.mCurItem) { for (let i=0; i<this.getChildCount(); i++) { let child = this.getChildAt(i); ii = this.infoForChild(child); if (ii != null && ii.position == this.mCurItem) { if (child.requestFocus(focusDirection)) { break; } } } } } } private sortChildDrawingOrder() { if (this.mDrawingOrder != ViewPager.DRAW_ORDER_DEFAULT) { if (this.mDrawingOrderedChildren == null) { this.mDrawingOrderedChildren = new ArrayList<View>(); } else { this.mDrawingOrderedChildren.clear(); } const childCount = this.getChildCount(); for (let i = 0; i < childCount; i++) { const child = this.getChildAt(i); this.mDrawingOrderedChildren.add(child); } this.mDrawingOrderedChildren.sort(ViewPager.sPositionComparator); //Collections.sort(mDrawingOrderedChildren, sPositionComparator); } } private calculatePageOffsets(curItem:ItemInfo, curIndex:number, oldCurInfo:ItemInfo) { const N = this.mAdapter.getCount(); const width = this.getClientWidth(); const marginOffset = width > 0 ? this.mPageMargin / width : 0; // Fix up offsets for later layout. if (oldCurInfo != null) { const oldCurPosition = oldCurInfo.position; // Base offsets off of oldCurInfo. if (oldCurPosition < curItem.position) { let itemIndex = 0; let ii:ItemInfo = null; let offset = oldCurInfo.offset + oldCurInfo.widthFactor + marginOffset; for (let pos = oldCurPosition + 1; pos <= curItem.position && itemIndex < this.mItems.size(); pos++) { ii = this.mItems.get(itemIndex); while (pos > ii.position && itemIndex < this.mItems.size() - 1) { itemIndex++; ii = this.mItems.get(itemIndex); } while (pos < ii.position) { // We don't have an item populated for this, // ask the adapter for an offset. offset += this.mAdapter.getPageWidth(pos) + marginOffset; pos++; } ii.offset = offset; offset += ii.widthFactor + marginOffset; } } else if (oldCurPosition > curItem.position) { let itemIndex = this.mItems.size() - 1; let ii:ItemInfo = null; let offset = oldCurInfo.offset; for (let pos = oldCurPosition - 1; pos >= curItem.position && itemIndex >= 0; pos--) { ii = this.mItems.get(itemIndex); while (pos < ii.position && itemIndex > 0) { itemIndex--; ii = this.mItems.get(itemIndex); } while (pos > ii.position) { // We don't have an item populated for this, // ask the adapter for an offset. offset -= this.mAdapter.getPageWidth(pos) + marginOffset; pos--; } offset -= ii.widthFactor + marginOffset; ii.offset = offset; } } } // Base all offsets off of curItem. const itemCount = this.mItems.size(); let offset = curItem.offset; let pos = curItem.position - 1; this.mFirstOffset = curItem.position == 0 ? curItem.offset : -Number.MAX_VALUE; this.mLastOffset = curItem.position == N - 1 ? curItem.offset + curItem.widthFactor - 1 : Number.MAX_VALUE; // Previous pages for (let i = curIndex - 1; i >= 0; i--, pos--) { const ii = this.mItems.get(i); while (pos > ii.position) { offset -= this.mAdapter.getPageWidth(pos--) + marginOffset; } offset -= ii.widthFactor + marginOffset; ii.offset = offset; if (ii.position == 0) this.mFirstOffset = offset; } offset = curItem.offset + curItem.widthFactor + marginOffset; pos = curItem.position + 1; // Next pages for (let i = curIndex + 1; i < itemCount; i++, pos++) { const ii = this.mItems.get(i); while (pos < ii.position) { offset += this.mAdapter.getPageWidth(pos++) + marginOffset; } if (ii.position == N - 1) { this.mLastOffset = offset + ii.widthFactor - 1; } ii.offset = offset; offset += ii.widthFactor + marginOffset; } this.mNeedCalculatePageOffsets = false; } addView(view: View): any; addView(view: View, index: number): any; addView(view: View, params: ViewGroup.LayoutParams): any; addView(view: View, index: number, params: ViewGroup.LayoutParams): any; addView(view: View, width: number, height: number): any; addView(...args: any[]){ if(args.length===3 && args[2] instanceof ViewGroup.LayoutParams){ this._addViewOverride(args[0], args[1], args[2]); }else{ super.addView(...args); } } private _addViewOverride(child: View, index: number, params: ViewGroup.LayoutParams): any{ if (!this.checkLayoutParams(params)) { params = this.generateLayoutParams(params); } const lp = <ViewPager.LayoutParams>params; lp.isDecor = lp.isDecor || ViewPager.isImplDecor(child); if (this.mInLayout) { if (lp != null && lp.isDecor) { throw new Error("Cannot add pager decor view during layout"); } lp.needsMeasure = true; this.addViewInLayout(child, index, params); } else { super.addView(child, index, params); } if (ViewPager.USE_CACHE) { if (child.getVisibility() != View.GONE) { child.setDrawingCacheEnabled(this.mScrollingCacheEnabled); } else { child.setDrawingCacheEnabled(false); } } } removeView(view:android.view.View):void { if (this.mInLayout) { this.removeViewInLayout(view); } else { super.removeView(view); } } private infoForChild(child:View):ItemInfo { for (let i=0; i<this.mItems.size(); i++) { let ii = this.mItems.get(i); if (this.mAdapter.isViewFromObject(child, ii.object)) { return ii; } } return null; } private infoForAnyChild(child:View):ItemInfo { let parent; while ((parent=child.getParent()) != this) { if (parent == null || !(parent instanceof View)) { return null; } child = <View>parent; } return this.infoForChild(child); } private infoForPosition(position:number):ItemInfo { for (let i = 0; i < this.mItems.size(); i++) { let ii = this.mItems.get(i); if (ii.position == position) { return ii; } } return null; } protected onAttachedToWindow():void { super.onAttachedToWindow(); this.mFirstLayout = true; } protected onMeasure(widthMeasureSpec, heightMeasureSpec):void { // For simple implementation, our internal size is always 0. // We depend on the container to specify the layout size of // our view. We can't really know what it is since we will be // adding and removing different arbitrary views and do not // want the layout to change as this happens. this.setMeasuredDimension(ViewPager.getDefaultSize(0, widthMeasureSpec), ViewPager.getDefaultSize(0, heightMeasureSpec)); const measuredWidth = this.getMeasuredWidth(); const maxGutterSize = measuredWidth / 10; this.mGutterSize = Math.min(maxGutterSize, this.mDefaultGutterSize); // Children are just made to fill our space. let childWidthSize = measuredWidth - this.getPaddingLeft() - this.getPaddingRight(); let childHeightSize = this.getMeasuredHeight() - this.getPaddingTop() - this.getPaddingBottom(); /* * Make sure all children have been properly measured. Decor views first. * Right now we cheat and make this less complicated by assuming decor * views won't intersect. We will pin to edges based on gravity. */ let size = this.getChildCount(); for (let i = 0; i < size; ++i) { const child = this.getChildAt(i); if (child.getVisibility() != View.GONE) { const lp = <ViewPager.LayoutParams>child.getLayoutParams(); if (lp != null && lp.isDecor) { const hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK; const vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK; let widthMode = MeasureSpec.AT_MOST; let heightMode = MeasureSpec.AT_MOST; let consumeVertical = vgrav == Gravity.TOP || vgrav == Gravity.BOTTOM; let consumeHorizontal = hgrav == Gravity.LEFT || hgrav == Gravity.RIGHT; if (consumeVertical) { widthMode = MeasureSpec.EXACTLY; } else if (consumeHorizontal) { heightMode = MeasureSpec.EXACTLY; } let widthSize = childWidthSize; let heightSize = childHeightSize; if (lp.width != ViewPager.LayoutParams.WRAP_CONTENT) { widthMode = MeasureSpec.EXACTLY; if (lp.width != ViewPager.LayoutParams.FILL_PARENT) { widthSize = lp.width; } } if (lp.height != ViewPager.LayoutParams.WRAP_CONTENT) { heightMode = MeasureSpec.EXACTLY; if (lp.height != ViewPager.LayoutParams.FILL_PARENT) { heightSize = lp.height; } } const widthSpec = MeasureSpec.makeMeasureSpec(widthSize, widthMode); const heightSpec = MeasureSpec.makeMeasureSpec(heightSize, heightMode); child.measure(widthSpec, heightSpec); if (consumeVertical) { childHeightSize -= child.getMeasuredHeight(); } else if (consumeHorizontal) { childWidthSize -= child.getMeasuredWidth(); } } } } this.mChildWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY); this.mChildHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeightSize, MeasureSpec.EXACTLY); // Make sure we have created all fragments that we need to have shown. this.mInLayout = true; this.populate(); this.mInLayout = false; // Page views next. size = this.getChildCount(); for (let i = 0; i < size; ++i) { const child = this.getChildAt(i); if (child.getVisibility() != View.GONE) { if (DEBUG) Log.v(TAG, "Measuring #" + i + " " + child + ": " + this.mChildWidthMeasureSpec); const lp = <ViewPager.LayoutParams>child.getLayoutParams(); if (lp == null || !lp.isDecor) { const widthSpec = MeasureSpec.makeMeasureSpec((childWidthSize * lp.widthFactor), MeasureSpec.EXACTLY); child.measure(widthSpec, this.mChildHeightMeasureSpec); } } } } protected onSizeChanged(w:number, h:number, oldw:number, oldh:number):void { super.onSizeChanged(w, h, oldw, oldh); // Make sure scroll position is set correctly. if (w != oldw) { this.recomputeScrollPosition(w, oldw, this.mPageMargin, this.mPageMargin); } } private recomputeScrollPosition(width:number, oldWidth:number, margin:number, oldMargin:number):void { if (oldWidth > 0 && !this.mItems.isEmpty()) { const widthWithMargin = width - this.getPaddingLeft() - this.getPaddingRight() + margin; const oldWidthWithMargin = oldWidth - this.getPaddingLeft() - this.getPaddingRight() + oldMargin; const xpos = this.getScrollX(); const pageOffset = xpos / oldWidthWithMargin; const newOffsetPixels = Math.floor(pageOffset * widthWithMargin); this.scrollTo(newOffsetPixels, this.getScrollY()); if (!this.mScroller.isFinished()) { // We now return to your regularly scheduled scroll, already in progress. const newDuration = this.mScroller.getDuration() - this.mScroller.timePassed(); let targetInfo = this.infoForPosition(this.mCurItem); this.mScroller.startScroll(newOffsetPixels, 0, Math.floor(targetInfo.offset * width), 0, newDuration); } } else { const ii = this.infoForPosition(this.mCurItem); const scrollOffset = ii != null ? Math.min(ii.offset, this.mLastOffset) : 0; const scrollPos = Math.floor(scrollOffset * (width - this.getPaddingLeft() - this.getPaddingRight())); if (scrollPos != this.getScrollX()) { this.completeScroll(false); this.scrollTo(scrollPos, this.getScrollY()); } } } protected onLayout(changed:boolean, l:number, t:number, r:number, b:number):void { const count = this.getChildCount(); let width = r - l; let height = b - t; let paddingLeft = this.getPaddingLeft(); let paddingTop = this.getPaddingTop(); let paddingRight = this.getPaddingRight(); let paddingBottom = this.getPaddingBottom(); const scrollX = this.getScrollX(); let decorCount = 0; // First pass - decor views. We need to do this in two passes so that // we have the proper offsets for non-decor views later. for (let i = 0; i < count; i++) { const child = this.getChildAt(i); if (child.getVisibility() != View.GONE) { const lp = <ViewPager.LayoutParams>child.getLayoutParams(); let childLeft = 0; let childTop = 0; if (lp.isDecor) { const hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK; const vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK; switch (hgrav) { default: childLeft = paddingLeft; break; case Gravity.LEFT: childLeft = paddingLeft; paddingLeft += child.getMeasuredWidth(); break; case Gravity.CENTER_HORIZONTAL: childLeft = Math.max((width - child.getMeasuredWidth()) / 2, paddingLeft); break; case Gravity.RIGHT: childLeft = width - paddingRight - child.getMeasuredWidth(); paddingRight += child.getMeasuredWidth(); break; } switch (vgrav) { default: childTop = paddingTop; break; case Gravity.TOP: childTop = paddingTop; paddingTop += child.getMeasuredHeight(); break; case Gravity.CENTER_VERTICAL: childTop = Math.max((height - child.getMeasuredHeight()) / 2, paddingTop); break; case Gravity.BOTTOM: childTop = height - paddingBottom - child.getMeasuredHeight(); paddingBottom += child.getMeasuredHeight(); break; } childLeft += scrollX; child.layout(childLeft, childTop, childLeft + child.getMeasuredWidth(), childTop + child.getMeasuredHeight()); decorCount++; } } } const childWidth = width - paddingLeft - paddingRight; // Page views. Do this once we have the right padding offsets from above. for (let i = 0; i < count; i++) { const child = this.getChildAt(i); if (child.getVisibility() != View.GONE) { const lp = <ViewPager.LayoutParams>child.getLayoutParams(); let ii; if (!lp.isDecor && (ii = this.infoForChild(child)) != null) { let loff = Math.floor(childWidth * ii.offset); let childLeft = paddingLeft + loff; let childTop = paddingTop; if (lp.needsMeasure) { // This was added during layout and needs measurement. // Do it now that we know what we're working with. lp.needsMeasure = false; const widthSpec = MeasureSpec.makeMeasureSpec( Math.floor(childWidth * lp.widthFactor), MeasureSpec.EXACTLY); const heightSpec = MeasureSpec.makeMeasureSpec( Math.floor(height - paddingTop - paddingBottom), MeasureSpec.EXACTLY); child.measure(widthSpec, heightSpec); } if (DEBUG) Log.v(TAG, "Positioning #" + i + " " + child + " f=" + ii.object + ":" + childLeft + "," + childTop + " " + child.getMeasuredWidth() + "x" + child.getMeasuredHeight()); child.layout(childLeft, childTop, childLeft + child.getMeasuredWidth(), childTop + child.getMeasuredHeight()); } } } this.mTopPageBounds = paddingTop; this.mBottomPageBounds = height - paddingBottom; this.mDecorChildCount = decorCount; if (this.mFirstLayout) { this.scrollToItem(this.mCurItem, false, 0, false); } this.mFirstLayout = false; } computeScroll() { if (!this.mScroller.isFinished() && this.mScroller.computeScrollOffset()) { let oldX = this.getScrollX(); let oldY = this.getScrollY(); let x = this.mScroller.getCurrX(); let y = this.mScroller.getCurrY(); if (oldX != x || oldY != y) { this.scrollTo(x, y); if (!this.pageScrolled(x)) { this.mScroller.abortAnimation(); this.scrollTo(0, y); } } // Keep on drawing until the animation has finished. this.postInvalidateOnAnimation(); return; } // Done with scroll, clean up state. this.completeScroll(true); } private pageScrolled(xpos:number):boolean { if (this.mItems.size() == 0) { this.mCalledSuper = false; this.onPageScrolled(0, 0, 0); if (!this.mCalledSuper) { throw new Error( "onPageScrolled did not call superclass implementation"); } return false; } const ii = this.infoForCurrentScrollPosition(); const width = this.getClientWidth(); const widthWithMargin = width + this.mPageMargin; const marginOffset = this.mPageMargin / width; const currentPage = ii.position; const pageOffset = ((xpos / width) - ii.offset) / (ii.widthFactor + marginOffset); const offsetPixels = Math.floor(pageOffset * widthWithMargin); this.mCalledSuper = false; this.onPageScrolled(currentPage, pageOffset, offsetPixels); if (!this.mCalledSuper) { throw new Error( "onPageScrolled did not call superclass implementation"); } return true; } /** * This method will be invoked when the current page is scrolled, either as part * of a programmatically initiated smooth scroll or a user initiated touch scroll. * If you override this method you must call through to the superclass implementation * (e.g. super.onPageScrolled(position, offset, offsetPixels)) before onPageScrolled * returns. * * @param position Position index of the first page currently being displayed. * Page position+1 will be visible if positionOffset is nonzero. * @param offset Value from [0, 1) indicating the offset from the page at position. * @param offsetPixels Value in pixels indicating the offset from position. */ onPageScrolled(position:number, offset:number, offsetPixels:number):void { // Offset any decor views if needed - keep them on-screen at all times. if (this.mDecorChildCount > 0) { const scrollX = this.getScrollX(); let paddingLeft = this.getPaddingLeft(); let paddingRight = this.getPaddingRight(); const width = this.getWidth(); const childCount = this.getChildCount(); for (let i = 0; i < childCount; i++) { const child = this.getChildAt(i); const lp = <ViewPager.LayoutParams>child.getLayoutParams(); if (!lp.isDecor) continue; const hgrav = lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK; let childLeft = 0; switch (hgrav) { default: childLeft = paddingLeft; break; case Gravity.LEFT: childLeft = paddingLeft; paddingLeft += child.getWidth(); break; case Gravity.CENTER_HORIZONTAL: childLeft = Math.max((width - child.getMeasuredWidth()) / 2, paddingLeft); break; case Gravity.RIGHT: childLeft = width - paddingRight - child.getMeasuredWidth(); paddingRight += child.getMeasuredWidth(); break; } childLeft += scrollX; const childOffset = childLeft - child.getLeft(); if (childOffset != 0) { child.offsetLeftAndRight(childOffset); } } } this.dispatchOnPageScrolled(position, offset, offsetPixels); if (this.mPageTransformer != null) { const scrollX = this.getScrollX(); const childCount = this.getChildCount(); for (let i = 0; i < childCount; i++) { const child = this.getChildAt(i); const lp = <ViewPager.LayoutParams>child.getLayoutParams(); if (lp.isDecor) continue; const transformPos = (child.getLeft() - scrollX) / this.getClientWidth(); this.mPageTransformer.transformPage(child, transformPos); } } this.mCalledSuper = true; } private dispatchOnPageScrolled(position:number, offset:number, offsetPixels:number) { if (this.mOnPageChangeListener != null) { this.mOnPageChangeListener.onPageScrolled(position, offset, offsetPixels); } if (this.mOnPageChangeListeners != null) { for (let i = 0, z = this.mOnPageChangeListeners.size(); i < z; i++) { let listener = this.mOnPageChangeListeners.get(i); if (listener != null) { listener.onPageScrolled(position, offset, offsetPixels); } } } if (this.mInternalPageChangeListener != null) { this.mInternalPageChangeListener.onPageScrolled(position, offset, offsetPixels); } } private dispatchOnPageSelected(position:number):void { if (this.mOnPageChangeListener != null) { this.mOnPageChangeListener.onPageSelected(position); } if (this.mOnPageChangeListeners != null) { for (let i = 0, z = this.mOnPageChangeListeners.size(); i < z; i++) { let listener = this.mOnPageChangeListeners.get(i); if (listener != null) { listener.onPageSelected(position); } } } if (this.mInternalPageChangeListener != null) { this.mInternalPageChangeListener.onPageSelected(position); } } private dispatchOnScrollStateChanged(state:number):void { if (this.mOnPageChangeListener != null) { this.mOnPageChangeListener.onPageScrollStateChanged(state); } if (this.mOnPageChangeListeners != null) { for (let i = 0, z = this.mOnPageChangeListeners.size(); i < z; i++) { let listener = this.mOnPageChangeListeners.get(i); if (listener != null) { listener.onPageScrollStateChanged(state); } } } if (this.mInternalPageChangeListener != null) { this.mInternalPageChangeListener.onPageScrollStateChanged(state); } } private completeScroll(postEvents:boolean) { let needPopulate = this.mScrollState == ViewPager.SCROLL_STATE_SETTLING; if (needPopulate) { // Done with scroll, no longer want to cache view drawing. this.setScrollingCacheEnabled(false); this.mScroller.abortAnimation(); let oldX = this.getScrollX(); let oldY = this.getScrollY(); let x = this.mScroller.getCurrX(); let y = this.mScroller.getCurrY(); if (oldX != x || oldY != y) { this.scrollTo(x, y); if (x != oldX) { this.pageScrolled(x); } } } this.mPopulatePending = false; for (let i=0; i<this.mItems.size(); i++) { let ii = this.mItems.get(i); if (ii.scrolling) { needPopulate = true; ii.scrolling = false; } } if (needPopulate) { if (postEvents) { this.postOnAnimation(this.mEndScrollRunnable); } else { this.mEndScrollRunnable.run(); } } } private isGutterDrag(x:number, dx:number):boolean { return (x < this.mGutterSize && dx > 0) || (x > this.getWidth() - this.mGutterSize && dx < 0); } private enableLayers(enable:boolean) { //nothing //const childCount = this.getChildCount(); //for (let i = 0; i < childCount; i++) { // const layerType = enable ? // View.LAYER_TYPE_HARDWARE : View.LAYER_TYPE_NONE; // this.getChildAt(i).setLayerType(layerType, null); //} } onInterceptTouchEvent(ev:MotionEvent):boolean { /* * This method JUST determines whether we want to intercept the motion. * If we return true, onMotionEvent will be called and we do the actual * scrolling there. */ const action = ev.getAction() & MotionEvent.ACTION_MASK; // Always take care of the touch gesture being complete. if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { // Release the drag. if (DEBUG) Log.v(TAG, "Intercept done!"); this.resetTouch(); return false; } // Nothing more to do here if we have decided whether or not we // are dragging. if (action != MotionEvent.ACTION_DOWN) { if (this.mIsBeingDragged) { if (DEBUG) Log.v(TAG, "Intercept returning true!"); return true; } if (this.mIsUnableToDrag) { if (DEBUG) Log.v(TAG, "Intercept returning false!"); return false; } } switch (action) { case MotionEvent.ACTION_MOVE: { /* * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check * whether the user has moved far enough from his original down touch. */ /* * Locally do absolute value. mLastMotionY is set to the y value * of the down event. */ const activePointerId = this.mActivePointerId; if (activePointerId == ViewPager.INVALID_POINTER) { // If we don't have a valid id, the touch down wasn't on content. break; } const pointerIndex = ev.findPointerIndex(activePointerId); const x = ev.getX(pointerIndex); const dx = x - this.mLastMotionX; const xDiff = Math.abs(dx); const y = ev.getY(pointerIndex); const yDiff = Math.abs(y - this.mInitialMotionY); if (DEBUG) Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff); if (dx != 0 && !this.isGutterDrag(this.mLastMotionX, dx) && this.canScroll(this, false, Math.floor(dx), Math.floor(x), Math.floor(y))) { // Nested view has scrollable area under this point. Let it be handled there. this.mLastMotionX = x; this.mLastMotionY = y; this.mIsUnableToDrag = true; return false; } if (xDiff > this.mTouchSlop && xDiff * 0.5 > yDiff) { if (DEBUG) Log.v(TAG, "Starting drag!"); this.mIsBeingDragged = true; this.requestParentDisallowInterceptTouchEvent(true); this.setScrollState(ViewPager.SCROLL_STATE_DRAGGING); this.mLastMotionX = dx > 0 ? this.mInitialMotionX + this.mTouchSlop : this.mInitialMotionX - this.mTouchSlop; this.mLastMotionY = y; this.setScrollingCacheEnabled(true); } else if (yDiff > this.mTouchSlop) { // The finger has moved enough in the vertical // direction to be counted as a drag... abort // any attempt to drag horizontally, to work correctly // with children that have scrolling containers. if (DEBUG) Log.v(TAG, "Starting unable to drag!"); this.mIsUnableToDrag = true; } if (this.mIsBeingDragged) { // Scroll to follow the motion event if (this.performDrag(x)) { this.postInvalidateOnAnimation(); } } break; } case MotionEvent.ACTION_DOWN: { /* * Remember location of down touch. * ACTION_DOWN always refers to pointer index 0. */ this.mLastMotionX = this.mInitialMotionX = ev.getX(); this.mLastMotionY = this.mInitialMotionY = ev.getY(); this.mActivePointerId = ev.getPointerId(0); this.mIsUnableToDrag = false; this.mScroller.computeScrollOffset(); if (this.mScrollState == ViewPager.SCROLL_STATE_SETTLING && Math.abs(this.mScroller.getFinalX() - this.mScroller.getCurrX()) > this.mCloseEnough) { // Let the user 'catch' the pager as it animates. this.mScroller.abortAnimation(); this.mPopulatePending = false; this.populate(); this.mIsBeingDragged = true; this.requestParentDisallowInterceptTouchEvent(true); this.setScrollState(ViewPager.SCROLL_STATE_DRAGGING); } else { this.completeScroll(false); this.mIsBeingDragged = false; } if (DEBUG) Log.v(TAG, "Down at " + this.mLastMotionX + "," + this.mLastMotionY + " mIsBeingDragged=" + this.mIsBeingDragged + "mIsUnableToDrag=" + this.mIsUnableToDrag); break; } case MotionEvent.ACTION_POINTER_UP: this.onSecondaryPointerUp(ev); break; } if (this.mVelocityTracker == null) { this.mVelocityTracker = VelocityTracker.obtain(); } this.mVelocityTracker.addMovement(ev); /* * The only time we want to intercept motion events is if we are in the * drag mode. */ return this.mIsBeingDragged; } onTouchEvent(ev:android.view.MotionEvent):boolean { if (this.mFakeDragging) { // A fake drag is in progress already, ignore this real one // but still eat the touch events. // (It is likely that the user is multi-touching the screen.) return true; } if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) { // Don't handle edge touches immediately -- they may actually belong to one of our // descendants. return false; } if (this.mAdapter == null || this.mAdapter.getCount() == 0) { // Nothing to present or scroll; nothing to touch. return false; } if (this.mVelocityTracker == null) { this.mVelocityTracker = VelocityTracker.obtain(); } this.mVelocityTracker.addMovement(ev); const action = ev.getAction(); let needsInvalidate = false; switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: { this.mScroller.abortAnimation(); this.mPopulatePending = false; this.populate(); // Remember where the motion event started this.mLastMotionX = this.mInitialMotionX = ev.getX(); this.mLastMotionY = this.mInitialMotionY = ev.getY(); this.mActivePointerId = ev.getPointerId(0); break; } case MotionEvent.ACTION_MOVE: if (!this.mIsBeingDragged) { const pointerIndex = ev.findPointerIndex(this.mActivePointerId); if (pointerIndex == -1) { // A child has consumed some touch events and put us into an inconsistent state. needsInvalidate = this.resetTouch(); break; } const x = ev.getX(pointerIndex); const xDiff = Math.abs(x - this.mLastMotionX); const y = ev.getY(pointerIndex); const yDiff = Math.abs(y - this.mLastMotionY); if (DEBUG) Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff); if (xDiff > this.mTouchSlop && xDiff > yDiff) { if (DEBUG) Log.v(TAG, "Starting drag!"); this.mIsBeingDragged = true; this.requestParentDisallowInterceptTouchEvent(true); this.mLastMotionX = x - this.mInitialMotionX > 0 ? this.mInitialMotionX + this.mTouchSlop : this.mInitialMotionX - this.mTouchSlop; this.mLastMotionY = y; this.setScrollState(ViewPager.SCROLL_STATE_DRAGGING); this.setScrollingCacheEnabled(true); // Disallow Parent Intercept, just in case let parent = this.getParent(); if (parent != null) { parent.requestDisallowInterceptTouchEvent(true); } } } // Not else! Note that mIsBeingDragged can be set above. if (this.mIsBeingDragged) { // Scroll to follow the motion event const activePointerIndex = ev.findPointerIndex(this.mActivePointerId); const x = ev.getX(activePointerIndex); needsInvalidate = needsInvalidate || this.performDrag(x); } break; case MotionEvent.ACTION_UP: if (this.mIsBeingDragged) { const velocityTracker = this.mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, this.mMaximumVelocity); let initialVelocity = velocityTracker.getXVelocity(this.mActivePointerId); this.mPopulatePending = true; const width = this.getClientWidth(); const scrollX = this.getScrollX(); const ii = this.infoForCurrentScrollPosition(); const currentPage = ii.position; const pageOffset = ((scrollX / width) - ii.offset) / ii.widthFactor; const activePointerIndex = ev.findPointerIndex(this.mActivePointerId); const x = ev.getX(activePointerIndex); const totalDelta = (x - this.mInitialMotionX); let nextPage = this.determineTargetPage(currentPage, pageOffset, initialVelocity, totalDelta); this.setCurrentItemInternal(nextPage, true, true, initialVelocity); needsInvalidate = this.resetTouch(); } break; case MotionEvent.ACTION_CANCEL: if (this.mIsBeingDragged) { this.scrollToItem(this.mCurItem, true, 0, false); needsInvalidate = this.resetTouch(); } break; case MotionEvent.ACTION_POINTER_DOWN: { const index = ev.getActionIndex(); const x = ev.getX(index); this.mLastMotionX = x; this.mActivePointerId = ev.getPointerId(index); break; } case MotionEvent.ACTION_POINTER_UP: this.onSecondaryPointerUp(ev); this.mLastMotionX = ev.getX(ev.findPointerIndex(this.mActivePointerId)); break; } if (needsInvalidate) { this.postInvalidateOnAnimation(); } return true; } private resetTouch():boolean { let needsInvalidate = false; this.mActivePointerId = ViewPager.INVALID_POINTER; this.endDrag(); //needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease(); return needsInvalidate; } private requestParentDisallowInterceptTouchEvent(disallowIntercept:boolean){ const parent = this.getParent(); if (parent != null) { parent.requestDisallowInterceptTouchEvent(disallowIntercept); } } private performDrag(x:number):boolean { let needsInvalidate = false; const deltaX = this.mLastMotionX - x; this.mLastMotionX = x; let oldScrollX = this.getScrollX(); let scrollX = oldScrollX + deltaX; const width = this.getClientWidth(); let leftBound = width * this.mFirstOffset; let rightBound = width * this.mLastOffset; let leftAbsolute = true; let rightAbsolute = true; const firstItem = this.mItems.get(0); const lastItem = this.mItems.get(this.mItems.size() - 1); if (firstItem.position != 0) { leftAbsolute = false; leftBound = firstItem.offset * width; } if (lastItem.position != this.mAdapter.getCount() - 1) { rightAbsolute = false; rightBound = lastItem.offset * width; } if (scrollX < leftBound) { if (leftAbsolute) { let over = leftBound - scrollX; needsInvalidate = false;//this.mLeftEdge.onPull(Math.abs(over) / width); } scrollX -= deltaX/2;//leftBound; } else if (scrollX > rightBound) { if (rightAbsolute) { let over = scrollX - rightBound; needsInvalidate = false;//this.mRightEdge.onPull(Math.abs(over) / width); } scrollX -= deltaX/2;//rightBound; } // Don't lose the rounded component this.mLastMotionX += scrollX - Math.floor(scrollX); this.scrollTo(scrollX, this.getScrollY()); this.pageScrolled(scrollX); return needsInvalidate; } private infoForCurrentScrollPosition():ItemInfo { const width = this.getClientWidth(); const scrollOffset = width > 0 ? this.getScrollX() / width : 0; const marginOffset = width > 0 ? this.mPageMargin / width : 0; let lastPos = -1; let lastOffset = 0; let lastWidth = 0; let first = true; let lastItem = null; for (let i = 0; i < this.mItems.size(); i++) { let ii = this.mItems.get(i); let offset; if (!first && ii.position != lastPos + 1) { // Create a synthetic item for a missing page. ii = this.mTempItem; ii.offset = lastOffset + lastWidth + marginOffset; ii.position = lastPos + 1; ii.widthFactor = this.mAdapter.getPageWidth(ii.position); i--; } offset = ii.offset; const leftBound = offset; const rightBound = offset + ii.widthFactor + marginOffset; if (first || scrollOffset >= leftBound) { if (scrollOffset < rightBound || i == this.mItems.size() - 1) { return ii; } } else { return lastItem; } first = false; lastPos = ii.position; lastOffset = offset; lastWidth = ii.widthFactor; lastItem = ii; } return lastItem; } private determineTargetPage(currentPage:number, pageOffset:number, velocity:number, deltaX:number):number { let targetPage; if (Math.abs(deltaX) > this.mFlingDistance && Math.abs(velocity) > this.mMinimumVelocity) { targetPage = velocity > 0 ? currentPage : currentPage + 1; } else { const truncator = currentPage >= this.mCurItem ? 0.4 : 0.6; targetPage = Math.floor(currentPage + pageOffset + truncator); } if (this.mItems.size() > 0) { const firstItem = this.mItems.get(0); const lastItem = this.mItems.get(this.mItems.size() - 1); // Only let the user target pages we have items for targetPage = Math.max(firstItem.position, Math.min(targetPage, lastItem.position)); } return targetPage; } draw(canvas:android.graphics.Canvas):void { super.draw(canvas); let needsInvalidate = false; //no need draw overscroll Edge //const overScrollMode = this.getOverScrollMode(); //if (overScrollMode == View.OVER_SCROLL_ALWAYS || // (overScrollMode == View.OVER_SCROLL_IF_CONTENT_SCROLLS && // this.mAdapter != null && this.mAdapter.getCount() > 1)) { // if (!mLeftEdge.isFinished()) { // const restoreCount = canvas.save(); // const height = getHeight() - getPaddingTop() - getPaddingBottom(); // const width = getWidth(); // // canvas.rotate(270); // canvas.translate(-height + getPaddingTop(), mFirstOffset * width); // mLeftEdge.setSize(height, width); // needsInvalidate |= mLeftEdge.draw(canvas); // canvas.restoreToCount(restoreCount); // } // if (!mRightEdge.isFinished()) { // const restoreCount = canvas.save(); // const width = getWidth(); // const height = getHeight() - getPaddingTop() - getPaddingBottom(); // // canvas.rotate(90); // canvas.translate(-getPaddingTop(), -(mLastOffset + 1) * width); // mRightEdge.setSize(height, width); // needsInvalidate |= mRightEdge.draw(canvas); // canvas.restoreToCount(restoreCount); // } //} else { // mLeftEdge.finish(); // mRightEdge.finish(); //} if (needsInvalidate) { // Keep animating this.postInvalidateOnAnimation(); } } protected onDraw(canvas:android.graphics.Canvas) { super.onDraw(canvas); // Draw the margin drawable between pages if needed. if (this.mPageMargin > 0 && this.mMarginDrawable != null && this.mItems.size() > 0 && this.mAdapter != null) { const scrollX = this.getScrollX(); const width = this.getWidth(); const marginOffset = this.mPageMargin / width; let itemIndex = 0; let ii = this.mItems.get(0); let offset = ii.offset; const itemCount = this.mItems.size(); const firstPos = ii.position; const lastPos = this.mItems.get(itemCount - 1).position; for (let pos = firstPos; pos < lastPos; pos++) { while (pos > ii.position && itemIndex < itemCount) { ii = this.mItems.get(++itemIndex); } let drawAt; if (pos == ii.position) { drawAt = (ii.offset + ii.widthFactor) * width; offset = ii.offset + ii.widthFactor + marginOffset; } else { let widthFactor = this.mAdapter.getPageWidth(pos); drawAt = (offset + widthFactor) * width; offset += widthFactor + marginOffset; } if (drawAt + this.mPageMargin > scrollX) { this.mMarginDrawable.setBounds(drawAt, this.mTopPageBounds, drawAt + this.mPageMargin, this.mBottomPageBounds); this.mMarginDrawable.draw(canvas); } if (drawAt > scrollX + width) { break; // No more visible, no sense in continuing } } } } /** * Start a fake drag of the pager. * * <p>A fake drag can be useful if you want to synchronize the motion of the ViewPager * with the touch scrolling of another view, while still letting the ViewPager * control the snapping motion and fling behavior. (e.g. parallax-scrolling tabs.) * Call {@link #fakeDragBy(float)} to simulate the actual drag motion. Call * {@link #endFakeDrag()} to complete the fake drag and fling as necessary. * * <p>During a fake drag the ViewPager will ignore all touch events. If a real drag * is already in progress, this method will return false. * * @return true if the fake drag began successfully, false if it could not be started. * * @see #fakeDragBy(float) * @see #endFakeDrag() */ beginFakeDrag():boolean { if (this.mIsBeingDragged) { return false; } this.mFakeDragging = true; this.setScrollState(ViewPager.SCROLL_STATE_DRAGGING); this.mInitialMotionX = this.mLastMotionX = 0; if (this.mVelocityTracker == null) { this.mVelocityTracker = VelocityTracker.obtain(); } else { this.mVelocityTracker.clear(); } const time = android.os.SystemClock.uptimeMillis(); const ev = MotionEvent.obtainWithAction(time, time, MotionEvent.ACTION_DOWN, 0, 0, 0); this.mVelocityTracker.addMovement(ev); ev.recycle(); this.mFakeDragBeginTime = time; return true; } /** * End a fake drag of the pager. * * @see #beginFakeDrag() * @see #fakeDragBy(float) */ endFakeDrag():void { if (!this.mFakeDragging) { throw new Error("No fake drag in progress. Call beginFakeDrag first."); } const velocityTracker = this.mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, this.mMaximumVelocity); let initialVelocity = Math.floor(velocityTracker.getXVelocity(this.mActivePointerId)); this.mPopulatePending = true; const width = this.getClientWidth(); const scrollX = this.getScrollX(); const ii = this.infoForCurrentScrollPosition(); const currentPage = ii.position; const pageOffset = ((scrollX / width) - ii.offset) / ii.widthFactor; const totalDelta = Math.floor(this.mLastMotionX - this.mInitialMotionX); let nextPage = this.determineTargetPage(currentPage, pageOffset, initialVelocity, totalDelta); this.setCurrentItemInternal(nextPage, true, true, initialVelocity); this.endDrag(); this.mFakeDragging = false; } /** * Fake drag by an offset in pixels. You must have called {@link #beginFakeDrag()} first. * * @param xOffset Offset in pixels to drag by. * @see #beginFakeDrag() * @see #endFakeDrag() */ fakeDragBy(xOffset:number):void { if (!this.mFakeDragging) { throw new Error("No fake drag in progress. Call beginFakeDrag first."); } this.mLastMotionX += xOffset; let oldScrollX = this.getScrollX(); let scrollX = oldScrollX - xOffset; const width = this.getClientWidth(); let leftBound = width * this.mFirstOffset; let rightBound = width * this.mLastOffset; const firstItem = this.mItems.get(0); const lastItem = this.mItems.get(this.mItems.size() - 1); if (firstItem.position != 0) { leftBound = firstItem.offset * width; } if (lastItem.position != this.mAdapter.getCount() - 1) { rightBound = lastItem.offset * width; } if (scrollX < leftBound) { scrollX = leftBound; } else if (scrollX > rightBound) { scrollX = rightBound; } // Don't lose the rounded component this.mLastMotionX += scrollX - Math.floor(scrollX); this.scrollTo(Math.floor(scrollX), this.getScrollY()); this.pageScrolled(Math.floor(scrollX)); // Synthesize an event for the VelocityTracker. const time = android.os.SystemClock.uptimeMillis(); const ev = MotionEvent.obtainWithAction(this.mFakeDragBeginTime, time, MotionEvent.ACTION_MOVE, this.mLastMotionX, 0, 0); this.mVelocityTracker.addMovement(ev); ev.recycle(); } /** * Returns true if a fake drag is in progress. * * @return true if currently in a fake drag, false otherwise. * * @see #beginFakeDrag() * @see #fakeDragBy(float) * @see #endFakeDrag() */ isFakeDragging():boolean { return this.mFakeDragging; } private onSecondaryPointerUp(ev:MotionEvent) { const pointerIndex = ev.getActionIndex(); const pointerId = ev.getPointerId(pointerIndex); if (pointerId == this.mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. const newPointerIndex = pointerIndex == 0 ? 1 : 0; this.mLastMotionX = ev.getX(newPointerIndex); this.mActivePointerId = ev.getPointerId(newPointerIndex); if (this.mVelocityTracker != null) { this.mVelocityTracker.clear(); } } } private endDrag() { this.mIsBeingDragged = false; this.mIsUnableToDrag = false; if (this.mVelocityTracker != null) { this.mVelocityTracker.recycle(); this.mVelocityTracker = null; } } private setScrollingCacheEnabled(enabled:boolean) { if (this.mScrollingCacheEnabled != enabled) { this.mScrollingCacheEnabled = enabled; if (ViewPager.USE_CACHE) { const size = this.getChildCount(); for (let i = 0; i < size; ++i) { const child = this.getChildAt(i); if (child.getVisibility() != View.GONE) { child.setDrawingCacheEnabled(enabled); } } } } } canScrollHorizontally(direction:number):boolean { if (this.mAdapter == null) { return false; } const width = this.getClientWidth(); const scrollX = this.getScrollX(); if (direction < 0) { return (scrollX > (width * this.mFirstOffset)); } else if (direction > 0) { return (scrollX < (width * this.mLastOffset)); } else { return false; } } /** * Tests scrollability within child views of v given a delta of dx. * * @param v View to test for horizontal scrollability * @param checkV Whether the view v passed should itself be checked for scrollability (true), * or just its children (false). * @param dx Delta scrolled in pixels * @param x X coordinate of the active touch point * @param y Y coordinate of the active touch point * @return true if child views of v can be scrolled by delta of dx. */ canScroll(v:View, checkV:boolean, dx:number, x:number, y:number):boolean { if (v instanceof ViewGroup) { const group = <ViewGroup>v; const scrollX = v.getScrollX(); const scrollY = v.getScrollY(); const count = group.getChildCount(); // Count backwards - let topmost views consume scroll distance first. for (let i = count - 1; i >= 0; i--) { // TODO: Add versioned support here for transformed views. // This will not work for transformed views in Honeycomb+ const child = group.getChildAt(i); if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() && y + scrollY >= child.getTop() && y + scrollY < child.getBottom() && this.canScroll(child, true, dx, x + scrollX - child.getLeft(), y + scrollY - child.getTop())) { return true; } } } return checkV && v.canScrollHorizontally(-dx); } dispatchKeyEvent(event:android.view.KeyEvent):boolean { // Let the focused view and/or our descendants get the key first return super.dispatchKeyEvent(event) || this.executeKeyEvent(event); } /** * You can call this function yourself to have the scroll view perform * scrolling from a key event, just as if the event had been dispatched to * it by the view hierarchy. * * @param event The key event to execute. * @return Return true if the event was handled, else false. */ executeKeyEvent(event:KeyEvent):boolean { let handled = false; if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_DPAD_LEFT: handled = this.arrowScroll(View.FOCUS_LEFT); break; case KeyEvent.KEYCODE_DPAD_RIGHT: handled = this.arrowScroll(View.FOCUS_RIGHT); break; case KeyEvent.KEYCODE_TAB: // The focus finder had a bug handling FOCUS_FORWARD and FOCUS_BACKWARD // before Android 3.0. Ignore the tab key on those devices. if (event.isShiftPressed()) { handled = this.arrowScroll(View.FOCUS_BACKWARD); }else{ handled = this.arrowScroll(View.FOCUS_FORWARD); } break; } } return handled; } arrowScroll(direction:number):boolean { let currentFocused = this.findFocus(); if (currentFocused == this) { currentFocused = null; } else if (currentFocused != null) { let isChild = false; for (let parent = currentFocused.getParent(); parent instanceof ViewGroup; parent = parent.getParent()) { if (parent == this) { isChild = true; break; } } if (!isChild) { // This would cause the focus search down below to fail in fun ways. const sb = new java.lang.StringBuilder(); sb.append(currentFocused.toString()); for (let parent = currentFocused.getParent(); parent instanceof ViewGroup; parent = parent.getParent()) { sb.append(" => ").append(parent.toString()); } Log.e(TAG, "arrowScroll tried to find focus based on non-child " + "current focused view " + sb.toString()); currentFocused = null; } } let handled = false; let nextFocused = android.view.FocusFinder.getInstance().findNextFocus(this, currentFocused, direction); if (nextFocused != null && nextFocused != currentFocused) { if (direction == View.FOCUS_LEFT) { // If there is nothing to the left, or this is causing us to // jump to the right, then what we really want to do is page left. const nextLeft = this.getChildRectInPagerCoordinates(this.mTempRect, nextFocused).left; const currLeft = this.getChildRectInPagerCoordinates(this.mTempRect, currentFocused).left; if (currentFocused != null && nextLeft >= currLeft) { handled = this.pageLeft(); } else { handled = nextFocused.requestFocus(); } } else if (direction == View.FOCUS_RIGHT) { // If there is nothing to the right, or this is causing us to // jump to the left, then what we really want to do is page right. const nextLeft = this.getChildRectInPagerCoordinates(this.mTempRect, nextFocused).left; const currLeft = this.getChildRectInPagerCoordinates(this.mTempRect, currentFocused).left; if (currentFocused != null && nextLeft <= currLeft) { handled = this.pageRight(); } else { handled = nextFocused.requestFocus(); } } } else if (direction == View.FOCUS_LEFT || direction == View.FOCUS_BACKWARD) { // Trying to move left and nothing there; try to page. handled = this.pageLeft(); } else if (direction == View.FOCUS_RIGHT || direction == View.FOCUS_FORWARD) { // Trying to move right and nothing there; try to page. handled = this.pageRight(); } //if (handled) { // playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction)); //} return handled; } private getChildRectInPagerCoordinates(outRect:Rect, child:View):Rect { if (outRect == null) { outRect = new Rect(); } if (child == null) { outRect.set(0, 0, 0, 0); return outRect; } outRect.left = child.getLeft(); outRect.right = child.getRight(); outRect.top = child.getTop(); outRect.bottom = child.getBottom(); let parent = child.getParent(); while (parent instanceof ViewGroup && parent != this) { const group = <ViewGroup>parent; outRect.left += group.getLeft(); outRect.right += group.getRight(); outRect.top += group.getTop(); outRect.bottom += group.getBottom(); parent = group.getParent(); } return outRect; } pageLeft():boolean { if (this.mCurItem > 0) { this.setCurrentItem(this.mCurItem-1, true); return true; } return false; } pageRight():boolean { if (this.mAdapter != null && this.mCurItem < (this.mAdapter.getCount()-1)) { this.setCurrentItem(this.mCurItem+1, true); return true; } return false; } addFocusables(views:ArrayList<View>, direction:number, focusableMode:number):void { const focusableCount = views.size(); const descendantFocusability = this.getDescendantFocusability(); if (descendantFocusability != ViewGroup.FOCUS_BLOCK_DESCENDANTS) { for (let i = 0; i < this.getChildCount(); i++) { const child = this.getChildAt(i); if (child.getVisibility() == View.VISIBLE) { let ii = this.infoForChild(child); if (ii != null && ii.position == this.mCurItem) { child.addFocusables(views, direction, focusableMode); } } } } // we add ourselves (if focusable) in all cases except for when we are // FOCUS_AFTER_DESCENDANTS and there are some descendants focusable. this is // to avoid the focus search finding layouts when a more precise search // among the focusable children would be more interesting. if ( descendantFocusability != ViewGroup.FOCUS_AFTER_DESCENDANTS || // No focusable descendants (focusableCount == views.size())) { // Note that we can't call the superclass here, because it will // add all views in. So we need to do the same thing View does. if (!this.isFocusable()) { return; } if ((focusableMode & ViewGroup.FOCUSABLES_TOUCH_MODE) == ViewGroup.FOCUSABLES_TOUCH_MODE && this.isInTouchMode() && !this.isFocusableInTouchMode()) { return; } if (views != null) { views.add(this); } } } /** * We only want the current page that is being shown to be touchable. */ addTouchables(views:java.util.ArrayList<android.view.View>):void { // Note that we don't call super.addTouchables(), which means that // we don't call View.addTouchables(). This is okay because a ViewPager // is itself not touchable. for (let i = 0; i < this.getChildCount(); i++) { const child = this.getChildAt(i); if (child.getVisibility() == View.VISIBLE) { let ii = this.infoForChild(child); if (ii != null && ii.position == this.mCurItem) { child.addTouchables(views); } } } } protected onRequestFocusInDescendants(direction:number, previouslyFocusedRect:Rect):boolean { let index; let increment; let end; let count = this.getChildCount(); if ((direction & View.FOCUS_FORWARD) != 0) { index = 0; increment = 1; end = count; } else { index = count - 1; increment = -1; end = -1; } for (let i = index; i != end; i += increment) { let child = this.getChildAt(i); if (child.getVisibility() == View.VISIBLE) { let ii = this.infoForChild(child); if (ii != null && ii.position == this.mCurItem) { if (child.requestFocus(direction, previouslyFocusedRect)) { return true; } } } } return false; } protected generateDefaultLayoutParams():android.view.ViewGroup.LayoutParams { return new ViewPager.LayoutParams(); } protected generateLayoutParams(p:android.view.ViewGroup.LayoutParams):android.view.ViewGroup.LayoutParams { return this.generateDefaultLayoutParams(); } protected checkLayoutParams(p:android.view.ViewGroup.LayoutParams):boolean { return p instanceof ViewPager.LayoutParams && super.checkLayoutParams(p); } public generateLayoutParamsFromAttr(attrs: HTMLElement): android.view.ViewGroup.LayoutParams { return new ViewPager.LayoutParams(this.getContext(), attrs); } private static isImplDecor(view:View):boolean { return view[SymbolDecor] || view.constructor[SymbolDecor]; } static setClassImplDecor(clazz:Function){ clazz[SymbolDecor] = true; } } export module ViewPager { import AttrBinder = androidui.attr.AttrBinder; /** * Callback interface for responding to changing state of the selected page. */ export interface OnPageChangeListener { /** * This method will be invoked when the current page is scrolled, either as part * of a programmatically initiated smooth scroll or a user initiated touch scroll. * @param position Position index of the first page currently being displayed. * * Page position+1 will be visible if positionOffset is nonzero. * * * @param positionOffset Value from [0, 1) indicating the offset from the page at position. * * * @param positionOffsetPixels Value in pixels indicating the offset from position. */ onPageScrolled(position:number, positionOffset:number, positionOffsetPixels:number):void; /** * This method will be invoked when a new page becomes selected. Animation is not * necessarily complete. * @param position Position index of the new selected page. */ onPageSelected(position:number):void; /** * Called when the scroll state changes. Useful for discovering when the user * begins dragging, when the pager is automatically settling to the current page, * or when it is fully stopped/idle. * @param state The new scroll state. * * * @see ViewPager.SCROLL_STATE_IDLE * @see ViewPager.SCROLL_STATE_DRAGGING * @see ViewPager.SCROLL_STATE_SETTLING */ onPageScrollStateChanged(state:number):void; } /** * Simple implementation of the [OnPageChangeListener] interface with stub * implementations of each method. Extend this if you do not intend to override * every method of [OnPageChangeListener]. */ export class SimpleOnPageChangeListener implements OnPageChangeListener { onPageScrolled(position:number, positionOffset:number, positionOffsetPixels:number) { // This space for rent } onPageSelected(position:number) { // This space for rent } onPageScrollStateChanged(state:number) { // This space for rent } } /** * A PageTransformer is invoked whenever a visible/attached page is scrolled. * This offers an opportunity for the application to apply a custom transformation * to the page views using animation properties. * * As property animation is only supported as of Android 3.0 and forward, * setting a PageTransformer on a ViewPager on earlier platform versions will * be ignored. */ export interface PageTransformer { /** * Apply a property transformation to the given page. * @param page Apply the transformation to this page * * * @param position Position of page relative to the current front-and-center * * position of the pager. 0 is front and center. 1 is one full * * page position to the right, and -1 is one page position to the left. */ transformPage(page:View, position:number):void; } /** * Used internally to monitor when adapters are switched. */ export interface OnAdapterChangeListener { onAdapterChanged(oldAdapter:PagerAdapter, newAdapter:PagerAdapter):void; } /** * Layout parameters that should be supplied for views added to a * ViewPager. */ export class LayoutParams extends ViewGroup.LayoutParams{ /** * true if this view is a decoration on the pager itself and not * a view supplied by the adapter. */ isDecor = false; /** * Gravity setting for use on decor views only: * Where to position the view page within the overall ViewPager * container; constants are defined in {@link android.view.Gravity}. */ gravity = 0; /** * Width as a 0-1 multiplier of the measured pager width */ widthFactor = 0; /** * true if this view was added during layout and needs to be measured * before being positioned. */ needsMeasure = false; /** * Adapter position this view is for if !isDecor */ position = 0; /** * Current child index within the ViewPager that this view occupies */ childIndex = 0; constructor(); constructor(context:android.content.Context, attrs:HTMLElement); constructor(...args) { super(...(() => { if (args[0] instanceof android.content.Context && args[1] instanceof HTMLElement) return [args[0], args[1]]; else if (args.length === 0) return [ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT]; })()); if (args[0] instanceof android.content.Context && args[1] instanceof HTMLElement) { const c = <android.content.Context>args[0]; const attrs = <HTMLElement>args[1]; const a = c.obtainStyledAttributes(attrs); this.gravity = Gravity.parseGravity(a.getAttrValue('layout_gravity'), Gravity.TOP); a.recycle(); } else if (args.length === 0) { } } protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap { return super.createClassAttrBinder().set('layout_gravity', { setter(param:LayoutParams, value:any, attrBinder:AttrBinder) { param.gravity = attrBinder.parseGravity(value, param.gravity); }, getter(param:LayoutParams) { return param.gravity; } }); } } } class ItemInfo { object:any; position = 0; scrolling = false; widthFactor = 0; offset = 0; } class PagerObserver extends DataSetObserver { ViewPager_this:ViewPager; constructor(viewPager:ViewPager) { super(); this.ViewPager_this = viewPager; } onChanged() { this.ViewPager_this.dataSetChanged(); } onInvalidated() { this.ViewPager_this.dataSetChanged(); } } }
the_stack
import { Barrier, isThenable, RunOnceScheduler } from 'vs/base/common/async'; import { Emitter } from 'vs/base/common/event'; import { Disposable } from 'vs/base/common/lifecycle'; import { assertNever } from 'vs/base/common/types'; import { applyTestItemUpdate, ITestItem, ITestTag, namespaceTestTag, TestDiffOpType, TestItemExpandState, TestsDiff, TestsDiffOp } from 'vs/workbench/contrib/testing/common/testTypes'; import { TestId } from 'vs/workbench/contrib/testing/common/testId'; /** * @private */ interface CollectionItem<T> { readonly fullId: TestId; readonly parent: TestId | null; actual: T; expand: TestItemExpandState; /** * Number of levels of items below this one that are expanded. May be infinite. */ expandLevels?: number; resolveBarrier?: Barrier; } export const enum TestItemEventOp { Upsert, SetTags, UpdateCanResolveChildren, RemoveChild, SetProp, Bulk, } export interface ITestItemUpsertChild { op: TestItemEventOp.Upsert; item: ITestItemLike; } export interface ITestItemUpdateCanResolveChildren { op: TestItemEventOp.UpdateCanResolveChildren; state: boolean; } export interface ITestItemSetTags { op: TestItemEventOp.SetTags; new: ITestTag[]; old: ITestTag[]; } export interface ITestItemRemoveChild { op: TestItemEventOp.RemoveChild; id: string; } export interface ITestItemSetProp { op: TestItemEventOp.SetProp; update: Partial<ITestItem>; } export interface ITestItemBulkReplace { op: TestItemEventOp.Bulk; ops: (ITestItemUpsertChild | ITestItemRemoveChild)[]; } export type ExtHostTestItemEvent = | ITestItemSetTags | ITestItemUpsertChild | ITestItemRemoveChild | ITestItemUpdateCanResolveChildren | ITestItemSetProp | ITestItemBulkReplace; export interface ITestItemApi<T> { controllerId: string; parent?: T; listener?: (evt: ExtHostTestItemEvent) => void; } export interface ITestItemCollectionOptions<T> { /** Controller ID to use to prefix these test items. */ controllerId: string; /** Gets API for the given test item, used to listen for events and set parents. */ getApiFor(item: T): ITestItemApi<T>; /** Converts the full test item to the common interface. */ toITestItem(item: T): ITestItem; /** Gets children for the item. */ getChildren(item: T): ITestChildrenLike<T>; /** Root to use for the new test collection. */ root: T; } const strictEqualComparator = <T>(a: T, b: T) => a === b; const diffableProps: { [K in keyof ITestItem]?: (a: ITestItem[K], b: ITestItem[K]) => boolean } = { range: (a, b) => { if (a === b) { return true; } if (!a || !b) { return false; } return a.equalsRange(b); }, busy: strictEqualComparator, label: strictEqualComparator, description: strictEqualComparator, error: strictEqualComparator, tags: (a, b) => { if (a.length !== b.length) { return false; } if (a.some(t1 => !b.includes(t1))) { return false; } return true; }, }; const diffTestItems = (a: ITestItem, b: ITestItem) => { let output: Record<string, unknown> | undefined; for (const [key, cmp] of Object.entries(diffableProps) as [keyof ITestItem, (a: any, b: any) => boolean][]) { if (!cmp(a[key], b[key])) { if (output) { output[key] = b[key]; } else { output = { [key]: b[key] }; } } } return output as Partial<ITestItem> | undefined; }; export interface ITestChildrenLike<T> extends Iterable<[string, T]> { get(id: string): T | undefined; delete(id: string): void; } export interface ITestItemLike { id: string; tags: readonly ITestTag[]; canResolveChildren: boolean; } /** * Maintains a collection of test items for a single controller. */ export class TestItemCollection<T extends ITestItemLike> extends Disposable { private readonly debounceSendDiff = this._register(new RunOnceScheduler(() => this.flushDiff(), 200)); private readonly diffOpEmitter = this._register(new Emitter<TestsDiff>()); private _resolveHandler?: (item: T | undefined) => Promise<void> | void; public get root() { return this.options.root; } public readonly tree = new Map</* full test id */string, CollectionItem<T>>(); private readonly tags = new Map<string, { label?: string; refCount: number }>(); protected diff: TestsDiff = []; constructor(private readonly options: ITestItemCollectionOptions<T>) { super(); this.root.canResolveChildren = true; this.upsertItem(this.root, undefined); } /** * Handler used for expanding test items. */ public set resolveHandler(handler: undefined | ((item: T | undefined) => void)) { this._resolveHandler = handler; for (const test of this.tree.values()) { this.updateExpandability(test); } } /** * Fires when an operation happens that should result in a diff. */ public readonly onDidGenerateDiff = this.diffOpEmitter.event; /** * Gets a diff of all changes that have been made, and clears the diff queue. */ public collectDiff() { const diff = this.diff; this.diff = []; return diff; } /** * Pushes a new diff entry onto the collected diff list. */ public pushDiff(diff: TestsDiffOp) { // Try to merge updates, since they're invoked per-property const last = this.diff[this.diff.length - 1]; if (last && diff.op === TestDiffOpType.Update) { if (last.op === TestDiffOpType.Update && last.item.extId === diff.item.extId) { applyTestItemUpdate(last.item, diff.item); return; } if (last.op === TestDiffOpType.Add && last.item.item.extId === diff.item.extId) { applyTestItemUpdate(last.item, diff.item); return; } } this.diff.push(diff); if (!this.debounceSendDiff.isScheduled()) { this.debounceSendDiff.schedule(); } } /** * Expands the test and the given number of `levels` of children. If levels * is < 0, then all children will be expanded. If it's 0, then only this * item will be expanded. */ public expand(testId: string, levels: number): Promise<void> | void { const internal = this.tree.get(testId); if (!internal) { return; } if (internal.expandLevels === undefined || levels > internal.expandLevels) { internal.expandLevels = levels; } // try to avoid awaiting things if the provider returns synchronously in // order to keep everything in a single diff and DOM update. if (internal.expand === TestItemExpandState.Expandable) { const r = this.resolveChildren(internal); return !r.isOpen() ? r.wait().then(() => this.expandChildren(internal, levels - 1)) : this.expandChildren(internal, levels - 1); } else if (internal.expand === TestItemExpandState.Expanded) { return internal.resolveBarrier?.isOpen() === false ? internal.resolveBarrier.wait().then(() => this.expandChildren(internal, levels - 1)) : this.expandChildren(internal, levels - 1); } } public override dispose() { for (const item of this.tree.values()) { this.options.getApiFor(item.actual).listener = undefined; } this.tree.clear(); this.diff = []; super.dispose(); } private onTestItemEvent(internal: CollectionItem<T>, evt: ExtHostTestItemEvent) { switch (evt.op) { case TestItemEventOp.RemoveChild: this.removeItem(TestId.joinToString(internal.fullId, evt.id)); break; case TestItemEventOp.Upsert: this.upsertItem(evt.item as T, internal); break; case TestItemEventOp.Bulk: for (const op of evt.ops) { this.onTestItemEvent(internal, op); } break; case TestItemEventOp.SetTags: this.diffTagRefs(evt.new, evt.old, internal.fullId.toString()); break; case TestItemEventOp.UpdateCanResolveChildren: this.updateExpandability(internal); break; case TestItemEventOp.SetProp: this.pushDiff({ op: TestDiffOpType.Update, item: { extId: internal.fullId.toString(), item: evt.update } }); break; default: assertNever(evt); } } private upsertItem(actual: T, parent: CollectionItem<T> | undefined) { const fullId = TestId.fromExtHostTestItem(actual, this.root.id, parent?.actual); // If this test item exists elsewhere in the tree already (exists at an // old ID with an existing parent), remove that old item. const privateApi = this.options.getApiFor(actual); if (privateApi.parent && privateApi.parent !== parent?.actual) { this.options.getChildren(privateApi.parent).delete(actual.id); } let internal = this.tree.get(fullId.toString()); // Case 1: a brand new item if (!internal) { internal = { fullId, actual, parent: parent ? fullId.parentId : null, expandLevels: parent?.expandLevels /* intentionally undefined or 0 */ ? parent.expandLevels - 1 : undefined, expand: TestItemExpandState.NotExpandable, // updated by `connectItemAndChildren` }; actual.tags.forEach(this.incrementTagRefs, this); this.tree.set(internal.fullId.toString(), internal); this.setItemParent(actual, parent); this.pushDiff({ op: TestDiffOpType.Add, item: { parent: internal.parent && internal.parent.toString(), controllerId: this.options.controllerId, expand: internal.expand, item: this.options.toITestItem(actual), }, }); this.connectItemAndChildren(actual, internal, parent); return; } // Case 2: re-insertion of an existing item, no-op if (internal.actual === actual) { this.connectItem(actual, internal, parent); // re-connect in case the parent changed return; // no-op } // Case 3: upsert of an existing item by ID, with a new instance const oldChildren = this.options.getChildren(internal.actual); const oldActual = internal.actual; const update = diffTestItems(this.options.toITestItem(oldActual), this.options.toITestItem(actual)); this.options.getApiFor(oldActual).listener = undefined; internal.actual = actual; internal.expand = TestItemExpandState.NotExpandable; // updated by `connectItemAndChildren` if (update) { // tags are handled in a special way if (update.hasOwnProperty('tags')) { this.diffTagRefs(actual.tags, oldActual.tags, fullId.toString()); delete update.tags; } this.onTestItemEvent(internal, { op: TestItemEventOp.SetProp, update }); } this.connectItemAndChildren(actual, internal, parent); // Remove any orphaned children. for (const [_, child] of oldChildren) { if (!this.options.getChildren(actual).get(child.id)) { this.removeItem(TestId.joinToString(fullId, child.id)); } } } private diffTagRefs(newTags: readonly ITestTag[], oldTags: readonly ITestTag[], extId: string) { const toDelete = new Set(oldTags.map(t => t.id)); for (const tag of newTags) { if (!toDelete.delete(tag.id)) { this.incrementTagRefs(tag); } } this.pushDiff({ op: TestDiffOpType.Update, item: { extId, item: { tags: newTags.map(v => namespaceTestTag(this.options.controllerId, v.id)) } } }); toDelete.forEach(this.decrementTagRefs, this); } private incrementTagRefs(tag: ITestTag) { const existing = this.tags.get(tag.id); if (existing) { existing.refCount++; } else { this.tags.set(tag.id, { refCount: 1 }); this.pushDiff({ op: TestDiffOpType.AddTag, tag: { id: namespaceTestTag(this.options.controllerId, tag.id), } }); } } private decrementTagRefs(tagId: string) { const existing = this.tags.get(tagId); if (existing && !--existing.refCount) { this.tags.delete(tagId); this.pushDiff({ op: TestDiffOpType.RemoveTag, id: namespaceTestTag(this.options.controllerId, tagId) }); } } private setItemParent(actual: T, parent: CollectionItem<T> | undefined) { this.options.getApiFor(actual).parent = parent && parent.actual !== this.root ? parent.actual : undefined; } private connectItem(actual: T, internal: CollectionItem<T>, parent: CollectionItem<T> | undefined) { this.setItemParent(actual, parent); const api = this.options.getApiFor(actual); api.parent = parent?.actual; api.listener = evt => this.onTestItemEvent(internal, evt); this.updateExpandability(internal); } private connectItemAndChildren(actual: T, internal: CollectionItem<T>, parent: CollectionItem<T> | undefined) { this.connectItem(actual, internal, parent); // Discover any existing children that might have already been added for (const [_, child] of this.options.getChildren(actual)) { this.upsertItem(child, internal); } } /** * Updates the `expand` state of the item. Should be called whenever the * resolved state of the item changes. Can automatically expand the item * if requested by a consumer. */ private updateExpandability(internal: CollectionItem<T>) { let newState: TestItemExpandState; if (!this._resolveHandler) { newState = TestItemExpandState.NotExpandable; } else if (internal.resolveBarrier) { newState = internal.resolveBarrier.isOpen() ? TestItemExpandState.Expanded : TestItemExpandState.BusyExpanding; } else { newState = internal.actual.canResolveChildren ? TestItemExpandState.Expandable : TestItemExpandState.NotExpandable; } if (newState === internal.expand) { return; } internal.expand = newState; this.pushDiff({ op: TestDiffOpType.Update, item: { extId: internal.fullId.toString(), expand: newState } }); if (newState === TestItemExpandState.Expandable && internal.expandLevels !== undefined) { this.resolveChildren(internal); } } /** * Expands all children of the item, "levels" deep. If levels is 0, only * the children will be expanded. If it's 1, the children and their children * will be expanded. If it's <0, it's a no-op. */ private expandChildren(internal: CollectionItem<T>, levels: number): Promise<void> | void { if (levels < 0) { return; } const expandRequests: Promise<void>[] = []; for (const [_, child] of this.options.getChildren(internal.actual)) { const promise = this.expand(TestId.joinToString(internal.fullId, child.id), levels); if (isThenable(promise)) { expandRequests.push(promise); } } if (expandRequests.length) { return Promise.all(expandRequests).then(() => { }); } } /** * Calls `discoverChildren` on the item, refreshing all its tests. */ private resolveChildren(internal: CollectionItem<T>) { if (internal.resolveBarrier) { return internal.resolveBarrier; } if (!this._resolveHandler) { const b = new Barrier(); b.open(); return b; } internal.expand = TestItemExpandState.BusyExpanding; this.pushExpandStateUpdate(internal); const barrier = internal.resolveBarrier = new Barrier(); const applyError = (err: Error) => { console.error(`Unhandled error in resolveHandler of test controller "${this.options.controllerId}"`, err); }; let r: Thenable<void> | void; try { r = this._resolveHandler(internal.actual === this.root ? undefined : internal.actual); } catch (err) { applyError(err); } if (isThenable(r)) { r.catch(applyError).then(() => { barrier.open(); this.updateExpandability(internal); }); } else { barrier.open(); this.updateExpandability(internal); } return internal.resolveBarrier; } private pushExpandStateUpdate(internal: CollectionItem<T>) { this.pushDiff({ op: TestDiffOpType.Update, item: { extId: internal.fullId.toString(), expand: internal.expand } }); } private removeItem(childId: string) { const childItem = this.tree.get(childId); if (!childItem) { throw new Error('attempting to remove non-existent child'); } this.pushDiff({ op: TestDiffOpType.Remove, itemId: childId }); const queue: (CollectionItem<T> | undefined)[] = [childItem]; while (queue.length) { const item = queue.pop(); if (!item) { continue; } this.options.getApiFor(item.actual).listener = undefined; for (const tag of item.actual.tags) { this.decrementTagRefs(tag.id); } this.tree.delete(item.fullId.toString()); for (const [_, child] of this.options.getChildren(item.actual)) { queue.push(this.tree.get(TestId.joinToString(item.fullId, child.id))); } } } /** * Immediately emits any pending diffs on the collection. */ public flushDiff() { const diff = this.collectDiff(); if (diff.length) { this.diffOpEmitter.fire(diff); } } } /** Implementation of vscode.TestItemCollection */ export interface ITestItemChildren<T extends ITestItemLike> extends Iterable<[string, T]> { readonly size: number; replace(items: readonly T[]): void; forEach(callback: (item: T, collection: this) => unknown, thisArg?: unknown): void; add(item: T): void; delete(itemId: string): void; get(itemId: string): T | undefined; toJSON(): readonly T[]; } export class DuplicateTestItemError extends Error { constructor(id: string) { super(`Attempted to insert a duplicate test item ID ${id}`); } } export class InvalidTestItemError extends Error { constructor(id: string) { super(`TestItem with ID "${id}" is invalid. Make sure to create it from the createTestItem method.`); } } export class MixedTestItemController extends Error { constructor(id: string, ctrlA: string, ctrlB: string) { super(`TestItem with ID "${id}" is from controller "${ctrlA}" and cannot be added as a child of an item from controller "${ctrlB}".`); } } export const createTestItemChildren = <T extends ITestItemLike>(api: ITestItemApi<T>, getApi: (item: T) => ITestItemApi<T>, checkCtor: Function): ITestItemChildren<T> => { let mapped = new Map<string, T>(); return { /** @inheritdoc */ get size() { return mapped.size; }, /** @inheritdoc */ forEach(callback: (item: T, collection: ITestItemChildren<T>) => unknown, thisArg?: unknown) { for (const item of mapped.values()) { callback.call(thisArg, item, this); } }, /** @inheritdoc */ [Symbol.iterator](): IterableIterator<[string, T]> { return mapped.entries(); }, /** @inheritdoc */ replace(items: Iterable<T>) { const newMapped = new Map<string, T>(); const toDelete = new Set(mapped.keys()); const bulk: ITestItemBulkReplace = { op: TestItemEventOp.Bulk, ops: [] }; for (const item of items) { if (!(item instanceof checkCtor)) { throw new InvalidTestItemError(item.id); } const itemController = getApi(item).controllerId; if (itemController !== api.controllerId) { throw new MixedTestItemController(item.id, itemController, api.controllerId); } if (newMapped.has(item.id)) { throw new DuplicateTestItemError(item.id); } newMapped.set(item.id, item); toDelete.delete(item.id); bulk.ops.push({ op: TestItemEventOp.Upsert, item }); } for (const id of toDelete.keys()) { bulk.ops.push({ op: TestItemEventOp.RemoveChild, id }); } api.listener?.(bulk); // important mutations come after firing, so if an error happens no // changes will be "saved": mapped = newMapped; }, /** @inheritdoc */ add(item: T) { if (!(item instanceof checkCtor)) { throw new InvalidTestItemError(item.id); } mapped.set(item.id, item); api.listener?.({ op: TestItemEventOp.Upsert, item }); }, /** @inheritdoc */ delete(id: string) { if (mapped.delete(id)) { api.listener?.({ op: TestItemEventOp.RemoveChild, id }); } }, /** @inheritdoc */ get(itemId: string) { return mapped.get(itemId); }, /** JSON serialization function. */ toJSON() { return Array.from(mapped.values()); }, }; };
the_stack
import { cloneDeep } from 'lodash'; import gql from 'graphql-tag'; import { GraphQLError } from 'graphql'; import { ApolloClient } from '../core'; import { InMemoryCache } from '../cache'; import { ApolloLink } from '../link/core'; import { Observable, ObservableSubscription as Subscription } from '../utilities'; import { itAsync, subscribeAndCount, mockSingleLink, withErrorSpy } from '../testing'; describe('mutation results', () => { const query = gql` query todoList { todoList(id: 5) { id todos { id text completed } filteredTodos: todos(completed: true) { id text completed } } noIdList: todoList(id: 6) { id todos { text completed } } } `; const queryWithTypename = gql` query todoList { todoList(id: 5) { id todos { id text completed __typename } filteredTodos: todos(completed: true) { id text completed __typename } __typename } noIdList: todoList(id: 6) { id todos { text completed __typename } __typename } } `; const result: any = { data: { __typename: 'Query', todoList: { __typename: 'TodoList', id: '5', todos: [ { __typename: 'Todo', id: '3', text: 'Hello world', completed: false, }, { __typename: 'Todo', id: '6', text: 'Second task', completed: false, }, { __typename: 'Todo', id: '12', text: 'Do other stuff', completed: false, }, ], filteredTodos: [], }, noIdList: { __typename: 'TodoList', id: '7', todos: [ { __typename: 'Todo', text: 'Hello world', completed: false, }, { __typename: 'Todo', text: 'Second task', completed: false, }, { __typename: 'Todo', text: 'Do other stuff', completed: false, }, ], }, }, }; function setupObsQuery( reject: (reason: any) => any, ...mockedResponses: any[] ) { const client = new ApolloClient({ link: mockSingleLink({ request: { query: queryWithTypename } as any, result, }, ...mockedResponses), cache: new InMemoryCache({ dataIdFromObject: (obj: any) => { if (obj.id && obj.__typename) { return obj.__typename + obj.id; } return null; }, // Passing an empty map enables warnings about missing fields: possibleTypes: {}, }), }); return { client, obsQuery: client.watchQuery({ query, notifyOnNetworkStatusChange: false, }), }; } function setupDelayObsQuery( reject: (reason: any) => any, delay: number, ...mockedResponses: any[] ) { const client = new ApolloClient({ link: mockSingleLink({ request: { query: queryWithTypename } as any, result, delay, }, ...mockedResponses).setOnError(reject), cache: new InMemoryCache({ dataIdFromObject: (obj: any) => { if (obj.id && obj.__typename) { return obj.__typename + obj.id; } return null; }, // Passing an empty map enables warnings about missing fields: possibleTypes: {}, }), }); return { client, obsQuery: client.watchQuery({ query, notifyOnNetworkStatusChange: false, }), }; } itAsync('correctly primes cache for tests', (resolve, reject) => { const { client, obsQuery } = setupObsQuery(reject); return obsQuery.result().then( () => client.query({ query }) ).then(resolve, reject); }); itAsync('correctly integrates field changes by default', (resolve, reject) => { const mutation = gql` mutation setCompleted { setCompleted(todoId: "3") { id completed __typename } __typename } `; const mutationResult = { data: { __typename: 'Mutation', setCompleted: { __typename: 'Todo', id: '3', completed: true, }, }, }; const { client, obsQuery } = setupObsQuery(reject, { request: { query: mutation }, result: mutationResult, }); return obsQuery.result().then(() => { return client.mutate({ mutation }); }).then(() => { return client.query({ query }); }).then((newResult: any) => { expect(newResult.data.todoList.todos[0].completed).toBe(true); }).then(resolve, reject); }); itAsync('correctly integrates field changes by default with variables', (resolve, reject) => { const query = gql` query getMini($id: ID!) { mini(id: $id) { id cover(maxWidth: 600, maxHeight: 400) __typename } } `; const mutation = gql` mutation upload($signature: String!) { mini: submitMiniCoverS3DirectUpload(signature: $signature) { id cover(maxWidth: 600, maxHeight: 400) __typename } } `; const link = mockSingleLink({ request: { query, variables: { id: 1 }, } as any, delay: 100, result: { data: { mini: { id: 1, cover: 'image', __typename: 'Mini' } }, }, }, { request: { query: mutation, variables: { signature: '1234' }, } as any, delay: 150, result: { data: { mini: { id: 1, cover: 'image2', __typename: 'Mini' } }, }, }).setOnError(reject); interface Data { mini: { id: number; cover: string; __typename: string }; } const client = new ApolloClient({ link, cache: new InMemoryCache({ dataIdFromObject: (obj: any) => { if (obj.id && obj.__typename) { return obj.__typename + obj.id; } return null; }, }), }); const obs = client.watchQuery<Data>({ query, variables: { id: 1 }, notifyOnNetworkStatusChange: false, }); let count = 0; obs.subscribe({ next: result => { if (count === 0) { client.mutate({ mutation, variables: { signature: '1234' } }); expect(result.data!.mini.cover).toBe('image'); setTimeout(() => { if (count === 0) reject( new Error('mutate did not re-call observable with next value'), ); }, 250); } if (count === 1) { expect(result.data!.mini.cover).toBe('image2'); resolve(); } count++; }, error: reject, }); }); itAsync("should write results to cache according to errorPolicy", async (resolve, reject) => { const expectedFakeError = new GraphQLError("expected/fake error"); const client = new ApolloClient({ cache: new InMemoryCache({ typePolicies: { Person: { keyFields: ["name"], }, }, }), link: new ApolloLink(operation => new Observable(observer => { observer.next({ errors: [ expectedFakeError, ], data: { newPerson: { __typename: "Person", name: operation.variables.newName, }, }, }); observer.complete(); })).setOnError(reject), }); const mutation = gql` mutation AddNewPerson($newName: String!) { newPerson(name: $newName) { name } } `; await client.mutate({ mutation, variables: { newName: "Hugh Willson", }, }).then(() => { reject("should have thrown for default errorPolicy"); }, error => { expect(error.message).toBe(expectedFakeError.message); }); expect(client.cache.extract()).toMatchSnapshot(); const ignoreErrorsResult = await client.mutate({ mutation, errorPolicy: "ignore", variables: { newName: "Jenn Creighton", }, }); expect(ignoreErrorsResult).toEqual({ data: { newPerson: { __typename: "Person", name: "Jenn Creighton", }, }, }); expect(client.cache.extract()).toMatchSnapshot(); const allErrorsResult = await client.mutate({ mutation, errorPolicy: "all", variables: { newName: "Ellen Shapiro", }, }); expect(allErrorsResult).toEqual({ data: { newPerson: { __typename: "Person", name: "Ellen Shapiro", }, }, errors: [ expectedFakeError, ], }); expect(client.cache.extract()).toMatchSnapshot(); resolve(); }); withErrorSpy(itAsync, "should warn when the result fields don't match the query fields", (resolve, reject) => { let handle: any; let subscriptionHandle: Subscription; const queryTodos = gql` query todos { todos { id name description __typename } } `; const queryTodosResult = { data: { todos: [ { id: '1', name: 'Todo 1', description: 'Description 1', __typename: 'todos', }, ], }, }; const mutationTodo = gql` mutation createTodo { createTodo { id name # missing field: description __typename } } `; const mutationTodoResult = { data: { createTodo: { id: '2', name: 'Todo 2', __typename: 'createTodo', }, }, }; const { client, obsQuery } = setupObsQuery( reject, { request: { query: queryTodos }, result: queryTodosResult, }, { request: { query: mutationTodo }, result: mutationTodoResult, }, ); return obsQuery.result().then(() => { // we have to actually subscribe to the query to be able to update it return new Promise(resolve => { handle = client.watchQuery({ query: queryTodos }); subscriptionHandle = handle.subscribe({ next(res: any) { resolve(res); }, }); }); }).then(() => client.mutate({ mutation: mutationTodo, updateQueries: { todos: (prev, { mutationResult }) => { const newTodo = (mutationResult as any).data.createTodo; const newResults = { todos: [...(prev as any).todos, newTodo], }; return newResults; }, }, })).finally( () => subscriptionHandle.unsubscribe(), ).then(result => { expect(result).toEqual(mutationTodoResult); }).then(resolve, reject); }); describe('InMemoryCache type/field policies', () => { const startTime = Date.now(); const link = new ApolloLink(operation => new Observable(observer => { observer.next({ data: { __typename: "Mutation", doSomething: { __typename: "MutationPayload", time: startTime, }, }, }); observer.complete(); })); const mutation = gql` mutation DoSomething { doSomething { time } } `; it('mutation update function receives result from cache', () => { let timeReadCount = 0; let timeMergeCount = 0; const client = new ApolloClient({ link, cache: new InMemoryCache({ typePolicies: { MutationPayload: { fields: { time: { read(ms: number = Date.now()) { ++timeReadCount; return new Date(ms); }, merge(existing, incoming: number) { ++timeMergeCount; expect(existing).toBeUndefined(); return incoming; }, }, }, }, }, }), }); return client.mutate({ mutation, update(cache, { data: { doSomething: { __typename, time, }, }, }) { expect(__typename).toBe("MutationPayload"); expect(time).toBeInstanceOf(Date); expect(time.getTime()).toBe(startTime); expect(timeReadCount).toBe(1); expect(timeMergeCount).toBe(1); expect(cache.extract()).toEqual({ ROOT_MUTATION: { __typename: "Mutation", doSomething: { __typename: "MutationPayload", time: startTime, }, }, }); }, }).then(({ data: { doSomething: { __typename, time, }, }, }) => { expect(__typename).toBe("MutationPayload"); expect(time).toBeInstanceOf(Date); expect(time.getTime()).toBe(startTime); expect(timeReadCount).toBe(1); expect(timeMergeCount).toBe(1); // The contents of the ROOT_MUTATION object exist only briefly, for the // duration of the mutation update, and are removed after the mutation // write is finished. expect(client.cache.extract()).toEqual({ ROOT_MUTATION: { __typename: "Mutation", }, }); }); }); it('mutations can preserve ROOT_MUTATION cache data with keepRootFields: true', () => { let timeReadCount = 0; let timeMergeCount = 0; const client = new ApolloClient({ link, cache: new InMemoryCache({ typePolicies: { MutationPayload: { fields: { time: { read(ms: number = Date.now()) { ++timeReadCount; return new Date(ms); }, merge(existing, incoming: number) { ++timeMergeCount; expect(existing).toBeUndefined(); return incoming; }, }, }, }, }, }), }); return client.mutate({ mutation, keepRootFields: true, update(cache, { data: { doSomething: { __typename, time, }, }, }) { expect(__typename).toBe("MutationPayload"); expect(time).toBeInstanceOf(Date); expect(time.getTime()).toBe(startTime); expect(timeReadCount).toBe(1); expect(timeMergeCount).toBe(1); expect(cache.extract()).toEqual({ ROOT_MUTATION: { __typename: "Mutation", doSomething: { __typename: "MutationPayload", time: startTime, }, }, }); }, }).then(({ data: { doSomething: { __typename, time, }, }, }) => { expect(__typename).toBe("MutationPayload"); expect(time).toBeInstanceOf(Date); expect(time.getTime()).toBe(startTime); expect(timeReadCount).toBe(1); expect(timeMergeCount).toBe(1); expect(client.cache.extract()).toEqual({ ROOT_MUTATION: { __typename: "Mutation", doSomething: { __typename: "MutationPayload", time: startTime, }, }, }); }); }); it('mutation update function runs even when fetchPolicy is "no-cache"', async () => { let timeReadCount = 0; let timeMergeCount = 0; let mutationUpdateCount = 0; const client = new ApolloClient({ link, cache: new InMemoryCache({ typePolicies: { MutationPayload: { fields: { time: { read(ms: number = Date.now()) { ++timeReadCount; return new Date(ms); }, merge(existing, incoming: number) { ++timeMergeCount; expect(existing).toBeUndefined(); return incoming; }, }, }, }, }, }), }); return client.mutate({ mutation, fetchPolicy: "no-cache", update(cache, { data: { doSomething: { __typename, time, }, }, }) { expect(++mutationUpdateCount).toBe(1); expect(__typename).toBe("MutationPayload"); expect(time).not.toBeInstanceOf(Date); expect(time).toBe(startTime); expect(timeReadCount).toBe(0); expect(timeMergeCount).toBe(0); expect(cache.extract()).toEqual({}); }, }).then(({ data: { doSomething: { __typename, time, }, }, }) => { expect(__typename).toBe("MutationPayload"); expect(time).not.toBeInstanceOf(Date); expect(time).toBe(+startTime); expect(timeReadCount).toBe(0); expect(timeMergeCount).toBe(0); expect(mutationUpdateCount).toBe(1); expect(client.cache.extract()).toEqual({}); }); }); }); describe('updateQueries', () => { const mutation = gql` mutation createTodo { # skipping arguments in the test since they don't matter createTodo { id text completed __typename } __typename } `; const mutationResult = { data: { __typename: 'Mutation', createTodo: { id: '99', __typename: 'Todo', text: 'This one was created with a mutation.', completed: true, }, }, }; itAsync('analogous of ARRAY_INSERT', (resolve, reject) => { let subscriptionHandle: Subscription; const { client, obsQuery } = setupObsQuery(reject, { request: { query: mutation }, result: mutationResult, }); return obsQuery.result().then(() => { // we have to actually subscribe to the query to be able to update it return new Promise(resolve => { const handle = client.watchQuery({ query }); subscriptionHandle = handle.subscribe({ next(res) { resolve(res); }, }); }); }).then(() => client.mutate({ mutation, updateQueries: { todoList: (prev, options) => { const mResult = options.mutationResult as any; expect(mResult.data.createTodo.id).toBe('99'); expect(mResult.data.createTodo.text).toBe( 'This one was created with a mutation.', ); const state = cloneDeep(prev) as any; state.todoList.todos.unshift(mResult.data.createTodo); return state; }, }, })).then( () => client.query({ query }) ).then((newResult: any) => { subscriptionHandle.unsubscribe(); // There should be one more todo item than before expect(newResult.data.todoList.todos.length).toBe(4); // Since we used `prepend` it should be at the front expect(newResult.data.todoList.todos[0].text).toBe( 'This one was created with a mutation.', ); }).then(resolve, reject); }); itAsync('does not fail if optional query variables are not supplied', (resolve, reject) => { let subscriptionHandle: Subscription; const mutationWithVars = gql` mutation createTodo($requiredVar: String!, $optionalVar: String) { createTodo(requiredVar: $requiredVar, optionalVar: $optionalVar) { id text completed __typename } __typename } `; // the test will pass if optionalVar is uncommented const variables = { requiredVar: 'x', // optionalVar: 'y', }; const { client, obsQuery } = setupObsQuery(reject, { request: { query: mutationWithVars, variables, }, result: mutationResult, }); return obsQuery.result().then(() => { // we have to actually subscribe to the query to be able to update it return new Promise(resolve => { const handle = client.watchQuery({ query, variables, }); subscriptionHandle = handle.subscribe({ next(res) { resolve(res); }, }); }); }).then(() => client.mutate({ mutation: mutationWithVars, variables, updateQueries: { todoList: (prev, options) => { const mResult = options.mutationResult as any; expect(mResult.data.createTodo.id).toBe('99'); expect(mResult.data.createTodo.text).toBe( 'This one was created with a mutation.', ); const state = cloneDeep(prev) as any; state.todoList.todos.unshift(mResult.data.createTodo); return state; }, }, })).then(() => { return client.query({ query }); }).then((newResult: any) => { subscriptionHandle.unsubscribe(); // There should be one more todo item than before expect(newResult.data.todoList.todos.length).toBe(4); // Since we used `prepend` it should be at the front expect(newResult.data.todoList.todos[0].text).toBe( 'This one was created with a mutation.', ); }).then(resolve, reject); }); itAsync('does not fail if the query did not complete correctly', (resolve, reject) => { const { client, obsQuery } = setupObsQuery(reject, { request: { query: mutation }, result: mutationResult, }); const subs = obsQuery.subscribe({ next: () => null, }); // Cancel the query right away! subs.unsubscribe(); return client.mutate({ mutation, updateQueries: { todoList: (prev, options) => { const mResult = options.mutationResult as any; expect(mResult.data.createTodo.id).toBe('99'); expect(mResult.data.createTodo.text).toBe( 'This one was created with a mutation.', ); const state = cloneDeep(prev) as any; state.todoList.todos.unshift(mResult.data.createTodo); return state; }, }, }).then(resolve, reject); }); itAsync('does not fail if the query did not finish loading', (resolve, reject) => { const { client, obsQuery } = setupDelayObsQuery(reject, 15, { request: { query: mutation }, result: mutationResult, }); obsQuery.subscribe({ next: () => null, }); return client.mutate({ mutation, updateQueries: { todoList: (prev, options) => { const mResult = options.mutationResult as any; expect(mResult.data.createTodo.id).toBe('99'); expect(mResult.data.createTodo.text).toBe( 'This one was created with a mutation.', ); const state = cloneDeep(prev) as any; state.todoList.todos.unshift(mResult.data.createTodo); return state; }, }, }).then(resolve, reject); }); itAsync('does not make next queries fail if a mutation fails', (resolve, reject) => { const { client, obsQuery } = setupObsQuery( error => { throw error }, { request: { query: mutation }, result: { errors: [new Error('mock error')] }, }, { request: { query: queryWithTypename }, result, }, ); obsQuery.subscribe({ next() { client .mutate({ mutation, updateQueries: { todoList: (prev, options) => { const mResult = options.mutationResult as any; const state = cloneDeep(prev) as any; // It's unfortunate that this function is called at all, but we are removing // the updateQueries API soon so it won't matter. state.todoList.todos.unshift( mResult.data && mResult.data.createTodo, ); return state; }, }, }) .then( () => reject(new Error('Mutation should have failed')), () => client.mutate({ mutation, updateQueries: { todoList: (prev, options) => { const mResult = options.mutationResult as any; const state = cloneDeep(prev) as any; state.todoList.todos.unshift(mResult.data.createTodo); return state; }, }, }), ) .then( () => reject(new Error('Mutation should have failed')), () => obsQuery.refetch(), ) .then(resolve, reject); }, }); }); itAsync('error handling in reducer functions', (resolve, reject) => { let subscriptionHandle: Subscription; const { client, obsQuery } = setupObsQuery(reject, { request: { query: mutation }, result: mutationResult, }); return obsQuery.result().then(() => { // we have to actually subscribe to the query to be able to update it return new Promise(resolve => { const handle = client.watchQuery({ query }); subscriptionHandle = handle.subscribe({ next(res) { resolve(res); }, }); }); }).then(() => client.mutate({ mutation, updateQueries: { todoList: () => { throw new Error(`Hello... It's me.`); }, }, })).then(() => { subscriptionHandle.unsubscribe(); reject("should have thrown"); }, error => { subscriptionHandle.unsubscribe(); expect(error.message).toBe(`Hello... It's me.`); }).then(resolve, reject); }); }); itAsync('does not fail if one of the previous queries did not complete correctly', (resolve, reject) => { const variableQuery = gql` query Echo($message: String) { echo(message: $message) } `; const variables1 = { message: 'a', }; const result1 = { data: { echo: 'a', }, }; const variables2 = { message: 'b', }; const result2 = { data: { echo: 'b', }, }; const resetMutation = gql` mutation Reset { reset { echo } } `; const resetMutationResult = { data: { reset: { echo: '0', }, }, }; const client = new ApolloClient({ link: mockSingleLink({ request: { query: variableQuery, variables: variables1 } as any, result: result1, }, { request: { query: variableQuery, variables: variables2 } as any, result: result2, }, { request: { query: resetMutation } as any, result: resetMutationResult, }).setOnError(reject), cache: new InMemoryCache({ addTypename: false }), }); const watchedQuery = client.watchQuery({ query: variableQuery, variables: variables1, }); const firstSubs = watchedQuery.subscribe({ next: () => null, error: reject, }); // Cancel the query right away! firstSubs.unsubscribe(); subscribeAndCount(reject, watchedQuery, (count, result) => { if (count === 1) { expect(result.data).toEqual({ echo: "a" }); } else if (count === 2) { expect(result.data).toEqual({ echo: "b" }); client.mutate({ mutation: resetMutation, updateQueries: { Echo: () => { return { echo: "0" }; }, }, }); } else if (count === 3) { expect(result.data).toEqual({ echo: "0" }); resolve(); } }); watchedQuery.refetch(variables2); }); itAsync('allows mutations with optional arguments', (resolve, reject) => { let count = 0; const client = new ApolloClient({ cache: new InMemoryCache({ addTypename: false }), link: ApolloLink.from([ ({ variables }: any) => new Observable(observer => { switch (count++) { case 0: expect(variables).toEqual({ a: 1, b: 2 }); observer.next({ data: { result: 'hello' } }); observer.complete(); return; case 1: expect(variables).toEqual({ a: 1, c: 3 }); observer.next({ data: { result: 'world' } }); observer.complete(); return; case 2: expect(variables).toEqual({ a: undefined, b: 2, c: 3, }); observer.next({ data: { result: 'goodbye' } }); observer.complete(); return; case 3: expect(variables).toEqual({}); observer.next({ data: { result: 'moon' } }); observer.complete(); return; default: observer.error(new Error('Too many network calls.')); return; } }), ] as any), }); const mutation = gql` mutation($a: Int!, $b: Int, $c: Int) { result(a: $a, b: $b, c: $c) } `; Promise.all([ client.mutate({ mutation, variables: { a: 1, b: 2 }, }), client.mutate({ mutation, variables: { a: 1, c: 3 }, }), client.mutate({ mutation, variables: { a: undefined, b: 2, c: 3 }, }), client.mutate({ mutation, }), ]).then(results => { expect(client.cache.extract()).toEqual({ ROOT_MUTATION: { __typename: "Mutation", }, }); expect(results).toEqual([ { data: { result: "hello" }}, { data: { result: "world" }}, { data: { result: "goodbye" }}, { data: { result: "moon" }}, ]); }).then(resolve, reject); }); itAsync('allows mutations with default values', (resolve, reject) => { let count = 0; const client = new ApolloClient({ cache: new InMemoryCache({ addTypename: false }), link: ApolloLink.from([ ({ variables }: any) => new Observable(observer => { switch (count++) { case 0: expect(variables).toEqual({ a: 1, b: 'water', }); observer.next({ data: { result: 'hello' } }); observer.complete(); return; case 1: expect(variables).toEqual({ a: 2, b: 'cheese', c: 3, }); observer.next({ data: { result: 'world' } }); observer.complete(); return; case 2: expect(variables).toEqual({ a: 1, b: 'cheese', c: 3, }); observer.next({ data: { result: 'goodbye' } }); observer.complete(); return; default: observer.error(new Error('Too many network calls.')); return; } }), ] as any), }); const mutation = gql` mutation($a: Int = 1, $b: String = "cheese", $c: Int) { result(a: $a, b: $b, c: $c) } `; Promise.all([ client.mutate({ mutation, variables: { a: 1, b: 'water' }, }), client.mutate({ mutation, variables: { a: 2, c: 3 }, }), client.mutate({ mutation, variables: { c: 3 }, }), ]).then(results => { expect(client.cache.extract()).toEqual({ ROOT_MUTATION: { __typename: "Mutation", }, }); expect(results).toEqual([ { data: { result: 'hello' }}, { data: { result: 'world' }}, { data: { result: 'goodbye' }}, ]); }).then(resolve, reject); }); itAsync('will pass null to the network interface when provided', (resolve, reject) => { let count = 0; const client = new ApolloClient({ cache: new InMemoryCache({ addTypename: false }), link: ApolloLink.from([ ({ variables }: any) => new Observable(observer => { switch (count++) { case 0: expect(variables).toEqual({ a: 1, b: 2, c: null, }); observer.next({ data: { result: 'hello' } }); observer.complete(); return; case 1: expect(variables).toEqual({ a: 1, b: null, c: 3, }); observer.next({ data: { result: 'world' } }); observer.complete(); return; case 2: expect(variables).toEqual({ a: null, b: null, c: null, }); observer.next({ data: { result: 'moon' } }); observer.complete(); return; default: observer.error(new Error('Too many network calls.')); return; } }), ] as any), }); const mutation = gql` mutation($a: Int!, $b: Int, $c: Int) { result(a: $a, b: $b, c: $c) } `; Promise.all([ client.mutate({ mutation, variables: { a: 1, b: 2, c: null }, }), client.mutate({ mutation, variables: { a: 1, b: null, c: 3 }, }), client.mutate({ mutation, variables: { a: null, b: null, c: null }, }), ]).then(results => { expect(client.cache.extract()).toEqual({ ROOT_MUTATION: { __typename: "Mutation", }, }); expect(results).toEqual([ { data: { result: 'hello' }}, { data: { result: 'world' }}, { data: { result: 'moon' }}, ]); }).then(resolve, reject); }); describe('store transaction updater', () => { const mutation = gql` mutation createTodo { # skipping arguments in the test since they don't matter createTodo { id text completed __typename } __typename } `; const mutationResult = { data: { __typename: 'Mutation', createTodo: { id: '99', __typename: 'Todo', text: 'This one was created with a mutation.', completed: true, }, }, }; itAsync('analogous of ARRAY_INSERT', (resolve, reject) => { let subscriptionHandle: Subscription; const { client, obsQuery } = setupObsQuery(reject, { request: { query: mutation }, result: mutationResult, }); return obsQuery.result().then(() => { // we have to actually subscribe to the query to be able to update it return new Promise(resolve => { const handle = client.watchQuery({ query }); subscriptionHandle = handle.subscribe({ next(res) { resolve(res); }, }); }); }).then(() => client.mutate({ mutation, update: (proxy, mResult: any) => { expect(mResult.data.createTodo.id).toBe('99'); expect(mResult.data.createTodo.text).toBe( 'This one was created with a mutation.', ); const id = 'TodoList5'; const fragment = gql` fragment todoList on TodoList { todos { id text completed __typename } } `; const data: any = proxy.readFragment({ id, fragment }); proxy.writeFragment({ data: { ...data, todos: [mResult.data.createTodo, ...data.todos], }, id, fragment, }); }, })).then(() => { return client.query({ query }); }).then((newResult: any) => { subscriptionHandle.unsubscribe(); // There should be one more todo item than before expect(newResult.data.todoList.todos.length).toBe(4); // Since we used `prepend` it should be at the front expect(newResult.data.todoList.todos[0].text).toBe( 'This one was created with a mutation.', ); }).then(resolve, reject); }); itAsync('does not fail if optional query variables are not supplied', (resolve, reject) => { let subscriptionHandle: Subscription; const mutationWithVars = gql` mutation createTodo($requiredVar: String!, $optionalVar: String) { createTodo(requiredVar: $requiredVar, optionalVar: $optionalVar) { id text completed __typename } __typename } `; // the test will pass if optionalVar is uncommented const variables = { requiredVar: 'x', // optionalVar: 'y', }; const { client, obsQuery } = setupObsQuery(reject, { request: { query: mutationWithVars, variables, }, result: mutationResult, }); return obsQuery.result().then(() => { // we have to actually subscribe to the query to be able to update it return new Promise(resolve => { const handle = client.watchQuery({ query, variables, }); subscriptionHandle = handle.subscribe({ next(res) { resolve(res); }, }); }); }).then(() => client.mutate({ mutation: mutationWithVars, variables, update: (proxy, mResult: any) => { expect(mResult.data.createTodo.id).toBe('99'); expect(mResult.data.createTodo.text).toBe( 'This one was created with a mutation.', ); const id = 'TodoList5'; const fragment = gql` fragment todoList on TodoList { todos { id text completed __typename } } `; const data: any = proxy.readFragment({ id, fragment }); proxy.writeFragment({ data: { ...data, todos: [mResult.data.createTodo, ...data.todos], }, id, fragment, }); }, })).then(() => { return client.query({ query }); }).then((newResult: any) => { subscriptionHandle.unsubscribe(); // There should be one more todo item than before expect(newResult.data.todoList.todos.length).toBe(4); // Since we used `prepend` it should be at the front expect(newResult.data.todoList.todos[0].text).toBe( 'This one was created with a mutation.', ); }).then(resolve, reject); }); itAsync('does not make next queries fail if a mutation fails', (resolve, reject) => { const { client, obsQuery } = setupObsQuery( error => { throw error }, { request: { query: mutation }, result: { errors: [new Error('mock error')] }, }, { request: { query: queryWithTypename }, result, }, ); obsQuery.subscribe({ next() { client .mutate({ mutation, update: (proxy, mResult: any) => { expect(mResult.data.createTodo.id).toBe('99'); expect(mResult.data.createTodo.text).toBe( 'This one was created with a mutation.', ); const id = 'TodoList5'; const fragment = gql` fragment todoList on TodoList { todos { id text completed __typename } } `; const data: any = proxy.readFragment({ id, fragment }); proxy.writeFragment({ data: { ...data, todos: [mResult.data.createTodo, ...data.todos], }, id, fragment, }); }, }) .then( () => reject(new Error('Mutation should have failed')), () => client.mutate({ mutation, update: (proxy, mResult: any) => { expect(mResult.data.createTodo.id).toBe('99'); expect(mResult.data.createTodo.text).toBe( 'This one was created with a mutation.', ); const id = 'TodoList5'; const fragment = gql` fragment todoList on TodoList { todos { id text completed __typename } } `; const data: any = proxy.readFragment({ id, fragment }); proxy.writeFragment({ data: { ...data, todos: [mResult.data.createTodo, ...data.todos], }, id, fragment, }); }, }), ) .then( () => reject(new Error('Mutation should have failed')), () => obsQuery.refetch(), ) .then(resolve, reject); }, }); }); itAsync('error handling in reducer functions', (resolve, reject) => { let subscriptionHandle: Subscription; const { client, obsQuery } = setupObsQuery(reject, { request: { query: mutation }, result: mutationResult, }); return obsQuery.result().then(() => { // we have to actually subscribe to the query to be able to update it return new Promise(resolve => { const handle = client.watchQuery({ query }); subscriptionHandle = handle.subscribe({ next(res) { resolve(res); }, }); }); }).then(() => client.mutate({ mutation, update: () => { throw new Error(`Hello... It's me.`); }, })).then(() => { subscriptionHandle.unsubscribe(); reject("should have thrown"); }, error => { subscriptionHandle.unsubscribe(); expect(error.message).toBe(`Hello... It's me.`); }).then(resolve, reject); }); itAsync('mutate<MyType>() data should never be `undefined` in case of success', (resolve, reject) => { const mutation = gql` mutation Foo { foo { bar } } `; const result1 = { data: { foo: { bar: 'a', }, }, }; const client = new ApolloClient({ link: mockSingleLink({ request: {query: mutation} as any, result: result1, }).setOnError(reject), cache: new InMemoryCache({addTypename: false}), }); client.mutate<{ foo: { bar: string; }; }>({ mutation: mutation, }).then(result => { // This next line should **not** raise "TS2533: Object is possibly 'null' or 'undefined'.", even without `!` operator if (result.data!.foo.bar) { resolve(); } }, reject); }) }); });
the_stack
* Miscellaneous types. */ type Attributes = {[key: string]: any}; type GraphType = 'mixed' | 'directed' | 'undirected'; type UpdateHints = {attributes?: Array<string>}; type EdgeKeyGeneratorFunction<EdgeAttributes extends Attributes = Attributes> = (data: { undirected: boolean; source: string; target: string; attributes: EdgeAttributes; }) => unknown; type GraphOptions<EdgeAttributes extends Attributes = Attributes> = { allowSelfLoops?: boolean; edgeKeyGenerator?: EdgeKeyGeneratorFunction<EdgeAttributes>; multi?: boolean; type?: GraphType; }; type AdjacencyEntry< NodeAttributes extends Attributes = Attributes, EdgeAttributes extends Attributes = Attributes > = [string, string, NodeAttributes, NodeAttributes, string, EdgeAttributes]; type NodeEntry<NodeAttributes extends Attributes = Attributes> = [ string, NodeAttributes ]; type EdgeEntry< NodeAttributes extends Attributes = Attributes, EdgeAttributes extends Attributes = Attributes > = [string, EdgeAttributes, string, string, NodeAttributes, NodeAttributes]; type AdjacencyIterationCallback< NodeAttributes extends Attributes = Attributes, EdgeAttributes extends Attributes = Attributes > = ( source: string, target: string, sourceAttributes: NodeAttributes, targetAttributes: NodeAttributes, edge: string, edgeAttributes: EdgeAttributes, undirected: boolean, generatedKey: boolean ) => void; type AdjacencyUntilIterationCallback< NodeAttributes extends Attributes = Attributes, EdgeAttributes extends Attributes = Attributes > = ( source: string, target: string, sourceAttributes: NodeAttributes, targetAttributes: NodeAttributes, edge: string, edgeAttributes: EdgeAttributes, undirected: boolean, generatedKey: boolean ) => boolean | undefined; type NodeIterationCallback<NodeAttributes extends Attributes = Attributes> = ( node: string, attributes: NodeAttributes ) => void; type NodeUntilIterationCallback< NodeAttributes extends Attributes = Attributes > = (node: string, attributes: NodeAttributes) => boolean | undefined; type NodeUpdateIterationCallback< NodeAttributes extends Attributes = Attributes > = (node: string, attributes: NodeAttributes) => NodeAttributes; type EdgeIterationCallback< NodeAttributes extends Attributes = Attributes, EdgeAttributes extends Attributes = Attributes > = ( edge: string, attributes: EdgeAttributes, source: string, target: string, sourceAttributes: NodeAttributes, targetAttributes: NodeAttributes, undirected: boolean, generatedKey: boolean ) => void; type EdgeUntilIterationCallback< NodeAttributes extends Attributes = Attributes, EdgeAttributes extends Attributes = Attributes > = ( edge: string, attributes: EdgeAttributes, source: string, target: string, sourceAttributes: NodeAttributes, targetAttributes: NodeAttributes, undirected: boolean, generatedKey: boolean ) => boolean | undefined; type EdgeUpdateIterationCallback< EdgeAttributes extends Attributes = Attributes > = (edge: string, attributes: EdgeAttributes) => EdgeAttributes; type SerializedNode<NodeAttributes extends Attributes = Attributes> = { key: string; attributes?: NodeAttributes; }; type SerializedEdge<EdgeAttributes extends Attributes = Attributes> = { key?: string; source: string; target: string; attributes?: EdgeAttributes; undirected?: boolean; }; type SerializedGraphOptions = { allowSelfLoops?: boolean; multi?: boolean; type?: GraphType; }; type SerializedGraph< NodeAttributes extends Attributes = Attributes, EdgeAttributes extends Attributes = Attributes, GraphAttributes extends Attributes = Attributes > = { attributes?: GraphAttributes; options?: SerializedGraphOptions; nodes: Array<SerializedNode<NodeAttributes>>; edges: Array<SerializedEdge<EdgeAttributes>>; }; /** * Event Emitter typings for convience. * @note Taken from here: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/events/index.d.ts */ type Listener = (...args: any[]) => void; type AttributeUpdateTypes = 'set' | 'remove' | 'replace' | 'merge'; interface GraphEvents< NodeAttributes extends Attributes = Attributes, EdgeAttributes extends Attributes = Attributes, GraphAttributes extends Attributes = Attributes > { nodeAdded(payload: {key: string; attributes: NodeAttributes}): void; edgeAdded(payload: { key: string; source: string; target: string; attributes: EdgeAttributes; undirected: boolean; }): void; nodeDropped(payload: {key: string; attributes: NodeAttributes}): void; edgeDropped(payload: { key: string; source: string; target: string; attributes: EdgeAttributes; undirected: boolean; }): void; cleared(): void; edgesCleared(): void; attributesUpdated(payload: { type: AttributeUpdateTypes; attributes: GraphAttributes; name: string; data: GraphAttributes; }): void; nodeAttributesUpdated(payload: { type: AttributeUpdateTypes; key: string; attributes: NodeAttributes; name: string; data: NodeAttributes; }): void; edgeAttributesUpdated(payload: { type: AttributeUpdateTypes; key: string; attributes: EdgeAttributes; name: string; data: EdgeAttributes; }): void; eachNodeAttributesUpdated(payload: {hints: UpdateHints}): void; eachEdgeAttributesUpdated(payload: {hints: UpdateHints}): void; } declare class EventEmitter< NodeAttributes extends Attributes = Attributes, EdgeAttributes extends Attributes = Attributes, GraphAttributes extends Attributes = Attributes > { static listenerCount(emitter: EventEmitter, type: string | number): number; static defaultMaxListeners: number; eventNames(): Array<string | number>; setMaxListeners(n: number): this; getMaxListeners(): number; emit(type: string | number, ...args: any[]): boolean; addListener< Event extends keyof GraphEvents< NodeAttributes, EdgeAttributes, GraphAttributes > >( type: Event, listener: GraphEvents< NodeAttributes, EdgeAttributes, GraphAttributes >[Event] ): this; addListener(type: string | number, listener: Listener): this; on< Event extends keyof GraphEvents< NodeAttributes, EdgeAttributes, GraphAttributes > >( type: Event, listener: GraphEvents< NodeAttributes, EdgeAttributes, GraphAttributes >[Event] ): this; on(type: string | number, listener: Listener): this; once< Event extends keyof GraphEvents< NodeAttributes, EdgeAttributes, GraphAttributes > >( type: Event, listener: GraphEvents< NodeAttributes, EdgeAttributes, GraphAttributes >[Event] ): this; once(type: string | number, listener: Listener): this; prependListener< Event extends keyof GraphEvents< NodeAttributes, EdgeAttributes, GraphAttributes > >( type: Event, listener: GraphEvents< NodeAttributes, EdgeAttributes, GraphAttributes >[Event] ): this; prependListener(type: string | number, listener: Listener): this; prependOnceListener< Event extends keyof GraphEvents< NodeAttributes, EdgeAttributes, GraphAttributes > >( type: Event, listener: GraphEvents< NodeAttributes, EdgeAttributes, GraphAttributes >[Event] ): this; prependOnceListener(type: string | number, listener: Listener): this; removeListener< Event extends keyof GraphEvents< NodeAttributes, EdgeAttributes, GraphAttributes > >( type: Event, listener: GraphEvents< NodeAttributes, EdgeAttributes, GraphAttributes >[Event] ): this; removeListener(type: string | number, listener: Listener): this; off< Event extends keyof GraphEvents< NodeAttributes, EdgeAttributes, GraphAttributes > >( type: Event, listener: GraphEvents< NodeAttributes, EdgeAttributes, GraphAttributes >[Event] ): this; off(type: string | number, listener: Listener): this; removeAllListeners< Event extends keyof GraphEvents< NodeAttributes, EdgeAttributes, GraphAttributes > >(type?: Event): this; removeAllListeners(type?: string | number): this; listeners(type: string | number): Listener[]; listenerCount(type: string | number): number; rawListeners(type: string | number): Listener[]; } /** * Main interface. */ declare abstract class AbstractGraph< NodeAttributes extends Attributes = Attributes, EdgeAttributes extends Attributes = Attributes, GraphAttributes extends Attributes = Attributes > extends EventEmitter<NodeAttributes, EdgeAttributes, GraphAttributes> implements Iterable<AdjacencyEntry<NodeAttributes, EdgeAttributes>> { // Constructor constructor(options?: GraphOptions<EdgeAttributes>); // Members order: number; size: number; directedSize: number; undirectedSize: number; type: GraphType; multi: boolean; allowSelfLoops: boolean; implementation: string; selfLoopCount: number; directedSelfLoopCount: number; undirectedSelfLoopCount: number; // Read methods hasNode(node: unknown): boolean; hasDirectedEdge(edge: unknown): boolean; hasDirectedEdge(source: unknown, target: unknown): boolean; hasUndirectedEdge(edge: unknown): boolean; hasUndirectedEdge(source: unknown, target: unknown): boolean; hasEdge(edge: unknown): boolean; hasEdge(source: unknown, target: unknown): boolean; directedEdge(source: unknown, target: unknown): string | undefined; undirectedEdge(source: unknown, target: unknown): string | undefined; edge(source: unknown, target: unknown): string | undefined; inDegree(node: unknown, selfLoops?: boolean): number; outDegree(node: unknown, selfLoops?: boolean): number; directedDegree(node: unknown, selfLoops?: boolean): number; undirectedDegree(node: unknown, selfLoops?: boolean): number; degree(node: unknown, selfLoops?: boolean): number; source(edge: unknown): string; target(edge: unknown): string; extremities(edge: unknown): [string, string]; opposite(node: unknown, edge: unknown): string; isUndirected(edge: unknown): boolean; isDirected(edge: unknown): boolean; isSelfLoop(edge: unknown): boolean; hasExtremity(edge: unknown, node: unknown): boolean; hasGeneratedKey(edge: unknown): boolean; neighbors(source: unknown, target: unknown): boolean; undirectedNeighbors(source: unknown, target: unknown): boolean; directedNeighbors(source: unknown, target: unknown): boolean; inNeighbors(source: unknown, target: unknown): boolean; outNeighbors(source: unknown, target: unknown): boolean; inboundNeighbors(source: unknown, target: unknown): boolean; outboundNeighbors(source: unknown, target: unknown): boolean; // Mutation methods addNode(node: unknown, attributes?: NodeAttributes): string; mergeNode(node: unknown, attributes?: Partial<NodeAttributes>): string; updateNode( node: unknown, updater?: (attributes: NodeAttributes) => NodeAttributes ): string; addEdge( source: unknown, target: unknown, attributes?: EdgeAttributes ): string; mergeEdge( source: unknown, target: unknown, attributes?: Partial<EdgeAttributes> ): string; updateEdge( source: unknown, target: unknown, updater?: (attributes: EdgeAttributes) => EdgeAttributes ): string; addDirectedEdge( source: unknown, target: unknown, attributes?: EdgeAttributes ): string; mergeDirectedEdge( source: unknown, target: unknown, attributes?: Partial<EdgeAttributes> ): string; updateDirectedEdge( source: unknown, target: unknown, updater?: (attributes: EdgeAttributes) => EdgeAttributes ): string; addUndirectedEdge( source: unknown, target: unknown, attributes?: EdgeAttributes ): string; mergeUndirectedEdge( source: unknown, target: unknown, attributes?: Partial<EdgeAttributes> ): string; updateUndirectedEdge( source: unknown, target: unknown, updater?: (attributes: EdgeAttributes) => EdgeAttributes ): string; addEdgeWithKey( edge: unknown, source: unknown, target: unknown, attributes?: EdgeAttributes ): string; mergeEdgeWithKey( edge: unknown, source: unknown, target: unknown, attributes?: Partial<EdgeAttributes> ): string; updateEdgeWithKey( source: unknown, target: unknown, updater?: (attributes: EdgeAttributes) => EdgeAttributes ): string; addDirectedEdgeWithKey( edge: unknown, source: unknown, target: unknown, attributes?: EdgeAttributes ): string; mergeDirectedEdgeWithKey( edge: unknown, source: unknown, target: unknown, attributes?: Partial<EdgeAttributes> ): string; updateDirectedEdgeWithKey( source: unknown, target: unknown, updater?: (attributes: EdgeAttributes) => EdgeAttributes ): string; addUndirectedEdgeWithKey( edge: unknown, source: unknown, target: unknown, attributes?: EdgeAttributes ): string; mergeUndirectedEdgeWithKey( edge: unknown, source: unknown, target: unknown, attributes?: Partial<EdgeAttributes> ): string; updateUndirectedEdgeWithKey( source: unknown, target: unknown, updater?: (attributes: EdgeAttributes) => EdgeAttributes ): string; dropNode(node: unknown): void; dropEdge(edge: unknown): void; dropEdge(source: unknown, target: unknown): void; clear(): void; clearEdges(): void; // Graph attribute methods getAttribute<AttributeName extends keyof GraphAttributes>( name: AttributeName ): GraphAttributes[AttributeName]; getAttributes(): GraphAttributes; hasAttribute<AttributeName extends keyof GraphAttributes>( name: AttributeName ): boolean; setAttribute<AttributeName extends keyof GraphAttributes>( name: AttributeName, value: GraphAttributes[AttributeName] ): this; updateAttribute<AttributeName extends keyof GraphAttributes>( name: AttributeName, updater: ( value: GraphAttributes[AttributeName] | undefined ) => GraphAttributes[AttributeName] ): this; removeAttribute<AttributeName extends keyof GraphAttributes>( name: AttributeName ): this; replaceAttributes(attributes: GraphAttributes): this; mergeAttributes(attributes: Partial<GraphAttributes>): this; // Node attribute methods getNodeAttribute<AttributeName extends keyof NodeAttributes>( node: unknown, name: AttributeName ): NodeAttributes[AttributeName]; getNodeAttributes(node: unknown): NodeAttributes; hasNodeAttribute<AttributeName extends keyof NodeAttributes>( node: unknown, name: AttributeName ): boolean; setNodeAttribute<AttributeName extends keyof NodeAttributes>( node: unknown, name: AttributeName, value: NodeAttributes[AttributeName] ): this; updateNodeAttribute<AttributeName extends keyof NodeAttributes>( node: unknown, name: AttributeName, updater: ( value: NodeAttributes[AttributeName] | undefined ) => NodeAttributes[AttributeName] ): this; removeNodeAttribute<AttributeName extends keyof NodeAttributes>( node: unknown, name: AttributeName ): this; replaceNodeAttributes(node: unknown, attributes: NodeAttributes): this; mergeNodeAttributes(node: unknown, attributes: Partial<NodeAttributes>): this; updateEachNodeAttributes( updater: NodeUpdateIterationCallback<NodeAttributes>, hints?: UpdateHints ): void; // Edge attribute methods getEdgeAttribute<AttributeName extends keyof EdgeAttributes>( edge: unknown, name: AttributeName ): EdgeAttributes[AttributeName]; getEdgeAttributes(edge: unknown): EdgeAttributes; hasEdgeAttribute<AttributeName extends keyof EdgeAttributes>( edge: unknown, name: AttributeName ): boolean; setEdgeAttribute<AttributeName extends keyof EdgeAttributes>( edge: unknown, name: AttributeName, value: EdgeAttributes[AttributeName] ): this; updateEdgeAttribute<AttributeName extends keyof EdgeAttributes>( edge: unknown, name: AttributeName, updater: ( value: EdgeAttributes[AttributeName] | undefined ) => EdgeAttributes[AttributeName] ): this; removeEdgeAttribute<AttributeName extends keyof EdgeAttributes>( edge: unknown, name: AttributeName ): this; replaceEdgeAttributes(edge: unknown, attributes: EdgeAttributes): this; mergeEdgeAttributes(edge: unknown, attributes: Partial<EdgeAttributes>): this; getDirectedEdgeAttribute<AttributeName extends keyof EdgeAttributes>( edge: unknown, name: AttributeName ): EdgeAttributes[AttributeName]; getDirectedEdgeAttributes(edge: unknown): EdgeAttributes; hasDirectedEdgeAttribute<AttributeName extends keyof EdgeAttributes>( edge: unknown, name: AttributeName ): boolean; setDirectedEdgeAttribute<AttributeName extends keyof EdgeAttributes>( edge: unknown, name: AttributeName, value: EdgeAttributes[AttributeName] ): this; updateDirectedEdgeAttribute<AttributeName extends keyof EdgeAttributes>( edge: unknown, name: AttributeName, updater: ( value: EdgeAttributes[AttributeName] | undefined ) => EdgeAttributes[AttributeName] ): this; removeDirectedEdgeAttribute<AttributeName extends keyof EdgeAttributes>( edge: unknown, name: AttributeName ): this; replaceDirectedEdgeAttributes( edge: unknown, attributes: EdgeAttributes ): this; mergeDirectedEdgeAttributes( edge: unknown, attributes: Partial<EdgeAttributes> ): this; getUndirectedEdgeAttribute<AttributeName extends keyof EdgeAttributes>( edge: unknown, name: AttributeName ): EdgeAttributes[AttributeName]; getUndirectedEdgeAttributes(edge: unknown): EdgeAttributes; hasUndirectedEdgeAttribute<AttributeName extends keyof EdgeAttributes>( edge: unknown, name: AttributeName ): boolean; setUndirectedEdgeAttribute<AttributeName extends keyof EdgeAttributes>( edge: unknown, name: AttributeName, value: EdgeAttributes[AttributeName] ): this; updateUndirectedEdgeAttribute<AttributeName extends keyof EdgeAttributes>( edge: unknown, name: AttributeName, updater: ( value: EdgeAttributes[AttributeName] | undefined ) => EdgeAttributes[AttributeName] ): this; removeUndirectedEdgeAttribute<AttributeName extends keyof EdgeAttributes>( edge: unknown, name: AttributeName ): this; replaceUndirectedEdgeAttributes( edge: unknown, attributes: EdgeAttributes ): this; mergeUndirectedEdgeAttributes( edge: unknown, attributes: Partial<EdgeAttributes> ): this; updateEachEdgeAttributes( updater: EdgeUpdateIterationCallback<EdgeAttributes>, hints?: UpdateHints ): void; // Edge attribute methods (source, target) getEdgeAttribute<AttributeName extends keyof EdgeAttributes>( source: unknown, target: unknown, name: AttributeName ): EdgeAttributes[AttributeName]; getEdgeAttributes(source: unknown, target: unknown): EdgeAttributes; hasEdgeAttribute<AttributeName extends keyof EdgeAttributes>( source: unknown, target: unknown, name: AttributeName ): boolean; setEdgeAttribute<AttributeName extends keyof EdgeAttributes>( source: unknown, target: unknown, name: AttributeName, value: EdgeAttributes[AttributeName] ): this; updateEdgeAttribute<AttributeName extends keyof EdgeAttributes>( source: unknown, target: unknown, name: AttributeName, updater: ( value: EdgeAttributes[AttributeName] | undefined ) => EdgeAttributes[AttributeName] ): this; removeEdgeAttribute<AttributeName extends keyof EdgeAttributes>( source: unknown, target: unknown, name: AttributeName ): this; replaceEdgeAttributes( source: unknown, target: unknown, attributes: EdgeAttributes ): this; mergeEdgeAttributes( source: unknown, target: unknown, attributes: Partial<EdgeAttributes> ): this; getDirectedEdgeAttribute<AttributeName extends keyof EdgeAttributes>( source: unknown, target: unknown, name: AttributeName ): EdgeAttributes[AttributeName]; getDirectedEdgeAttributes(source: unknown, target: unknown): EdgeAttributes; hasDirectedEdgeAttribute<AttributeName extends keyof EdgeAttributes>( source: unknown, target: unknown, name: AttributeName ): boolean; setDirectedEdgeAttribute<AttributeName extends keyof EdgeAttributes>( source: unknown, target: unknown, name: AttributeName, value: EdgeAttributes[AttributeName] ): this; updateDirectedEdgeAttribute<AttributeName extends keyof EdgeAttributes>( source: unknown, target: unknown, name: AttributeName, updater: ( value: EdgeAttributes[AttributeName] | undefined ) => EdgeAttributes[AttributeName] ): this; removeDirectedEdgeAttribute<AttributeName extends keyof EdgeAttributes>( source: unknown, target: unknown, name: AttributeName ): this; replaceDirectedEdgeAttributes( source: unknown, target: unknown, attributes: EdgeAttributes ): this; mergeDirectedEdgeAttributes( source: unknown, target: unknown, attributes: Partial<EdgeAttributes> ): this; getUndirectedEdgeAttribute<AttributeName extends keyof EdgeAttributes>( source: unknown, target: unknown, name: AttributeName ): EdgeAttributes[AttributeName]; getUndirectedEdgeAttributes(source: unknown, target: unknown): EdgeAttributes; hasUndirectedEdgeAttribute<AttributeName extends keyof EdgeAttributes>( source: unknown, target: unknown, name: AttributeName ): boolean; setUndirectedEdgeAttribute<AttributeName extends keyof EdgeAttributes>( source: unknown, target: unknown, name: AttributeName, value: EdgeAttributes[AttributeName] ): this; updateUndirectedEdgeAttribute<AttributeName extends keyof EdgeAttributes>( source: unknown, target: unknown, name: AttributeName, updater: ( value: EdgeAttributes[AttributeName] | undefined ) => EdgeAttributes[AttributeName] ): this; removeUndirectedEdgeAttribute<AttributeName extends keyof EdgeAttributes>( source: unknown, target: unknown, name: AttributeName ): this; replaceUndirectedEdgeAttributes( source: unknown, target: unknown, attributes: EdgeAttributes ): this; mergeUndirectedEdgeAttributes( source: unknown, target: unknown, attributes: Partial<EdgeAttributes> ): this; // Iteration methods [Symbol.iterator](): IterableIterator< AdjacencyEntry<NodeAttributes, EdgeAttributes> >; forEach( callback: AdjacencyIterationCallback<NodeAttributes, EdgeAttributes> ): void; forEachUntil( callback: AdjacencyUntilIterationCallback<NodeAttributes, EdgeAttributes> ): boolean; adjacency(): IterableIterator<AdjacencyEntry<NodeAttributes, EdgeAttributes>>; nodes(): Array<string>; forEachNode(callback: NodeIterationCallback<NodeAttributes>): void; forEachNodeUntil( callback: NodeUntilIterationCallback<NodeAttributes> ): boolean; nodeEntries(): IterableIterator<NodeEntry<NodeAttributes>>; edges(): Array<string>; edges(node: unknown): Array<string>; edges(source: unknown, target: unknown): Array<string>; undirectedEdges(): Array<string>; undirectedEdges(node: unknown): Array<string>; undirectedEdges(source: unknown, target: unknown): Array<string>; directedEdges(): Array<string>; directedEdges(node: unknown): Array<string>; directedEdges(source: unknown, target: unknown): Array<string>; inEdges(): Array<string>; inEdges(node: unknown): Array<string>; inEdges(source: unknown, target: unknown): Array<string>; outEdges(): Array<string>; outEdges(node: unknown): Array<string>; outEdges(source: unknown, target: unknown): Array<string>; inboundEdges(): Array<string>; inboundEdges(node: unknown): Array<string>; inboundEdges(source: unknown, target: unknown): Array<string>; outboundEdges(): Array<string>; outboundEdges(node: unknown): Array<string>; outboundEdges(source: unknown, target: unknown): Array<string>; forEachEdge( callback: EdgeIterationCallback<NodeAttributes, EdgeAttributes> ): void; forEachEdge( node: unknown, callback: EdgeIterationCallback<NodeAttributes, EdgeAttributes> ): void; forEachEdge( source: unknown, target: unknown, callback: EdgeIterationCallback<NodeAttributes, EdgeAttributes> ): void; forEachUndirectedEdge( callback: EdgeIterationCallback<NodeAttributes, EdgeAttributes> ): void; forEachUndirectedEdge( node: unknown, callback: EdgeIterationCallback<NodeAttributes, EdgeAttributes> ): void; forEachUndirectedEdge( source: unknown, target: unknown, callback: EdgeIterationCallback<NodeAttributes, EdgeAttributes> ): void; forEachDirectedEdge( callback: EdgeIterationCallback<NodeAttributes, EdgeAttributes> ): void; forEachDirectedEdge( node: unknown, callback: EdgeIterationCallback<NodeAttributes, EdgeAttributes> ): void; forEachDirectedEdge( source: unknown, target: unknown, callback: EdgeIterationCallback<NodeAttributes, EdgeAttributes> ): void; forEachInEdge( callback: EdgeIterationCallback<NodeAttributes, EdgeAttributes> ): void; forEachInEdge( node: unknown, callback: EdgeIterationCallback<NodeAttributes, EdgeAttributes> ): void; forEachInEdge( source: unknown, target: unknown, callback: EdgeIterationCallback<NodeAttributes, EdgeAttributes> ): void; forEachOutEdge( callback: EdgeIterationCallback<NodeAttributes, EdgeAttributes> ): void; forEachOutEdge( node: unknown, callback: EdgeIterationCallback<NodeAttributes, EdgeAttributes> ): void; forEachOutEdge( source: unknown, target: unknown, callback: EdgeIterationCallback<NodeAttributes, EdgeAttributes> ): void; forEachInboundEdge( callback: EdgeIterationCallback<NodeAttributes, EdgeAttributes> ): void; forEachInboundEdge( node: unknown, callback: EdgeIterationCallback<NodeAttributes, EdgeAttributes> ): void; forEachInboundEdge( source: unknown, target: unknown, callback: EdgeIterationCallback<NodeAttributes, EdgeAttributes> ): void; forEachOutboundEdge( callback: EdgeIterationCallback<NodeAttributes, EdgeAttributes> ): void; forEachOutboundEdge( node: unknown, callback: EdgeIterationCallback<NodeAttributes, EdgeAttributes> ): void; forEachOutboundEdge( source: unknown, target: unknown, callback: EdgeIterationCallback<NodeAttributes, EdgeAttributes> ): void; forEachEdgeUntil( callback: EdgeUntilIterationCallback<NodeAttributes, EdgeAttributes> ): boolean; forEachEdgeUntil( node: unknown, callback: EdgeUntilIterationCallback<NodeAttributes, EdgeAttributes> ): boolean; forEachEdgeUntil( source: unknown, target: unknown, callback: EdgeUntilIterationCallback<NodeAttributes, EdgeAttributes> ): boolean; forEachUndirectedEdgeUntil( callback: EdgeUntilIterationCallback<NodeAttributes, EdgeAttributes> ): boolean; forEachUndirectedEdgeUntil( node: unknown, callback: EdgeUntilIterationCallback<NodeAttributes, EdgeAttributes> ): boolean; forEachUndirectedEdgeUntil( source: unknown, target: unknown, callback: EdgeUntilIterationCallback<NodeAttributes, EdgeAttributes> ): boolean; forEachDirectedEdgeUntil( callback: EdgeUntilIterationCallback<NodeAttributes, EdgeAttributes> ): boolean; forEachDirectedEdgeUntil( node: unknown, callback: EdgeUntilIterationCallback<NodeAttributes, EdgeAttributes> ): boolean; forEachDirectedEdgeUntil( source: unknown, target: unknown, callback: EdgeUntilIterationCallback<NodeAttributes, EdgeAttributes> ): boolean; forEachInEdgeUntil( callback: EdgeUntilIterationCallback<NodeAttributes, EdgeAttributes> ): boolean; forEachInEdgeUntil( node: unknown, callback: EdgeUntilIterationCallback<NodeAttributes, EdgeAttributes> ): boolean; forEachInEdgeUntil( source: unknown, target: unknown, callback: EdgeUntilIterationCallback<NodeAttributes, EdgeAttributes> ): boolean; forEachOutEdgeUntil( callback: EdgeUntilIterationCallback<NodeAttributes, EdgeAttributes> ): boolean; forEachOutEdgeUntil( node: unknown, callback: EdgeUntilIterationCallback<NodeAttributes, EdgeAttributes> ): boolean; forEachOutEdgeUntil( source: unknown, target: unknown, callback: EdgeUntilIterationCallback<NodeAttributes, EdgeAttributes> ): boolean; forEachInboundEdgeUntil( callback: EdgeUntilIterationCallback<NodeAttributes, EdgeAttributes> ): boolean; forEachInboundEdgeUntil( node: unknown, callback: EdgeUntilIterationCallback<NodeAttributes, EdgeAttributes> ): boolean; forEachInboundEdgeUntil( source: unknown, target: unknown, callback: EdgeUntilIterationCallback<NodeAttributes, EdgeAttributes> ): boolean; forEachOutboundEdgeUntil( callback: EdgeUntilIterationCallback<NodeAttributes, EdgeAttributes> ): boolean; forEachOutboundEdgeUntil( node: unknown, callback: EdgeUntilIterationCallback<NodeAttributes, EdgeAttributes> ): boolean; forEachOutboundEdgeUntil( source: unknown, target: unknown, callback: EdgeUntilIterationCallback<NodeAttributes, EdgeAttributes> ): boolean; edgeEntries(): IterableIterator<EdgeEntry<NodeAttributes, EdgeAttributes>>; edgeEntries( node: unknown ): IterableIterator<EdgeEntry<NodeAttributes, EdgeAttributes>>; edgeEntries( source: unknown, target: unknown ): IterableIterator<EdgeEntry<NodeAttributes, EdgeAttributes>>; undirectedEdgeEntries(): IterableIterator< EdgeEntry<NodeAttributes, EdgeAttributes> >; undirectedEdgeEntries( node: unknown ): IterableIterator<EdgeEntry<NodeAttributes, EdgeAttributes>>; undirectedEdgeEntries( source: unknown, target: unknown ): IterableIterator<EdgeEntry<NodeAttributes, EdgeAttributes>>; directedEdgeEntries(): IterableIterator< EdgeEntry<NodeAttributes, EdgeAttributes> >; directedEdgeEntries( node: unknown ): IterableIterator<EdgeEntry<NodeAttributes, EdgeAttributes>>; directedEdgeEntries( source: unknown, target: unknown ): IterableIterator<EdgeEntry<NodeAttributes, EdgeAttributes>>; inEdgeEntries(): IterableIterator<EdgeEntry<NodeAttributes, EdgeAttributes>>; inEdgeEntries( node: unknown ): IterableIterator<EdgeEntry<NodeAttributes, EdgeAttributes>>; inEdgeEntries( source: unknown, target: unknown ): IterableIterator<EdgeEntry<NodeAttributes, EdgeAttributes>>; outEdgeEntries(): IterableIterator<EdgeEntry<NodeAttributes, EdgeAttributes>>; outEdgeEntries( node: unknown ): IterableIterator<EdgeEntry<NodeAttributes, EdgeAttributes>>; outEdgeEntries( source: unknown, target: unknown ): IterableIterator<EdgeEntry<NodeAttributes, EdgeAttributes>>; inboundEdgeEntries(): IterableIterator< EdgeEntry<NodeAttributes, EdgeAttributes> >; inboundEdgeEntries( node: unknown ): IterableIterator<EdgeEntry<NodeAttributes, EdgeAttributes>>; inboundEdgeEntries( source: unknown, target: unknown ): IterableIterator<EdgeEntry<NodeAttributes, EdgeAttributes>>; outboundEdgeEntries(): IterableIterator< EdgeEntry<NodeAttributes, EdgeAttributes> >; outboundEdgeEntries( node: unknown ): IterableIterator<EdgeEntry<NodeAttributes, EdgeAttributes>>; outboundEdgeEntries( source: unknown, target: unknown ): IterableIterator<EdgeEntry<NodeAttributes, EdgeAttributes>>; neighbors(node: unknown): Array<string>; undirectedNeighbors(node: unknown): Array<string>; directedNeighbors(node: unknown): Array<string>; inNeighbors(node: unknown): Array<string>; outNeighbors(node: unknown): Array<string>; inboundNeighbors(node: unknown): Array<string>; outboundNeighbors(node: unknown): Array<string>; forEachNeighbor( node: unknown, callback: NodeIterationCallback<NodeAttributes> ): void; forEachUndirectedNeighbor( node: unknown, callback: NodeIterationCallback<NodeAttributes> ): void; forEachDirectedNeighbor( node: unknown, callback: NodeIterationCallback<NodeAttributes> ): void; forEachInNeighbor( node: unknown, callback: NodeIterationCallback<NodeAttributes> ): void; forEachOutNeighbor( node: unknown, callback: NodeIterationCallback<NodeAttributes> ): void; forEachInboundNeighbor( node: unknown, callback: NodeIterationCallback<NodeAttributes> ): void; forEachOutboundNeighbor( node: unknown, callback: NodeIterationCallback<NodeAttributes> ): void; forEachNeighborUntil( node: unknown, callback: NodeUntilIterationCallback<NodeAttributes> ): boolean; forEachUndirectedNeighborUntil( node: unknown, callback: NodeUntilIterationCallback<NodeAttributes> ): boolean; forEachDirectedNeighborUntil( node: unknown, callback: NodeUntilIterationCallback<NodeAttributes> ): boolean; forEachInNeighborUntil( node: unknown, callback: NodeUntilIterationCallback<NodeAttributes> ): boolean; forEachOutNeighborUntil( node: unknown, callback: NodeUntilIterationCallback<NodeAttributes> ): boolean; forEachInboundNeighborUntil( node: unknown, callback: NodeUntilIterationCallback<NodeAttributes> ): boolean; forEachOutboundNeighborUntil( node: unknown, callback: NodeUntilIterationCallback<NodeAttributes> ): boolean; neighborEntries(node: unknown): IterableIterator<NodeEntry<NodeAttributes>>; undirectedNeighborEntries( node: unknown ): IterableIterator<NodeEntry<NodeAttributes>>; directedNeighborEntries( node: unknown ): IterableIterator<NodeEntry<NodeAttributes>>; inNeighborEntries(node: unknown): IterableIterator<NodeEntry<NodeAttributes>>; outNeighborEntries( node: unknown ): IterableIterator<NodeEntry<NodeAttributes>>; inboundNeighborEntries( node: unknown ): IterableIterator<NodeEntry<NodeAttributes>>; outboundNeighborEntries( node: unknown ): IterableIterator<NodeEntry<NodeAttributes>>; // Serialization methods exportNode(node: unknown): SerializedNode<NodeAttributes>; exportEdge(edge: unknown): SerializedEdge<EdgeAttributes>; export(): SerializedGraph<NodeAttributes, EdgeAttributes, GraphAttributes>; importNode(data: SerializedNode<NodeAttributes>, merge?: boolean): this; importEdge(data: SerializedEdge<EdgeAttributes>, merge?: boolean): this; import( data: SerializedGraph<NodeAttributes, EdgeAttributes, GraphAttributes>, merge?: boolean ): this; import( graph: AbstractGraph<NodeAttributes, EdgeAttributes, GraphAttributes>, merge?: boolean ): this; // Utils nullCopy(): AbstractGraph<NodeAttributes, EdgeAttributes, GraphAttributes>; emptyCopy(): AbstractGraph<NodeAttributes, EdgeAttributes, GraphAttributes>; copy(): AbstractGraph<NodeAttributes, EdgeAttributes, GraphAttributes>; upgradeToMixed(): this; upgradeToMulti(): this; // Well-known methods toJSON(): SerializedGraph<NodeAttributes, EdgeAttributes, GraphAttributes>; toString(): string; inspect(): any; static from< NodeAttributes extends Attributes = Attributes, EdgeAttributes extends Attributes = Attributes, GraphAttributes extends Attributes = Attributes >( data: SerializedGraph<NodeAttributes, EdgeAttributes, GraphAttributes> ): AbstractGraph<NodeAttributes, EdgeAttributes, GraphAttributes>; static from< NodeAttributes extends Attributes = Attributes, EdgeAttributes extends Attributes = Attributes, GraphAttributes extends Attributes = Attributes >( graph: AbstractGraph<NodeAttributes, EdgeAttributes, GraphAttributes> ): AbstractGraph<NodeAttributes, EdgeAttributes, GraphAttributes>; } interface IGraphConstructor< NodeAttributes extends Attributes = Attributes, EdgeAttributes extends Attributes = Attributes, GraphAttributes extends Attributes = Attributes > { new (options?: GraphOptions<GraphAttributes>): AbstractGraph< NodeAttributes, EdgeAttributes, GraphAttributes >; } type GraphConstructor< NodeAttributes extends Attributes = Attributes, EdgeAttributes extends Attributes = Attributes, GraphAttributes extends Attributes = Attributes > = IGraphConstructor<NodeAttributes, EdgeAttributes, GraphAttributes>; export { AbstractGraph, Attributes, GraphType, EdgeKeyGeneratorFunction, GraphOptions, AdjacencyEntry, NodeEntry, EdgeEntry, AdjacencyIterationCallback, AdjacencyUntilIterationCallback, NodeIterationCallback, NodeUntilIterationCallback, NodeUpdateIterationCallback, EdgeIterationCallback, EdgeUntilIterationCallback, EdgeUpdateIterationCallback, SerializedNode, SerializedEdge, SerializedGraph, GraphConstructor }; export default AbstractGraph;
the_stack
import * as R from 'ramda'; import { ResolverFn } from '../'; import validator from 'validator'; import { logger } from '../../loggers/logger'; import { isPatchEmpty } from '../../util/db'; import { GroupNotFoundError } from '../../models/group'; import { Helpers as projectHelpers } from '../project/helpers'; import { OpendistroSecurityOperations } from './opendistroSecurity'; import { KeycloakUnauthorizedError } from '../../util/auth'; export const getAllGroups: ResolverFn = async ( root, { name, type }, { hasPermission, models, keycloakGrant } ) => { try { await hasPermission('group', 'viewAll'); if (name) { const group = await models.GroupModel.loadGroupByName(name); return [group]; } else { const groups = await models.GroupModel.loadAllGroups(); const filterFn = (key, val) => group => group[key].includes(val); const filteredByName = groups.filter(filterFn('name', name)); const filteredByType = groups.filter(filterFn('type', type)); return name || type ? R.union(filteredByName, filteredByType) : groups; } } catch (err) { if (name && err instanceof GroupNotFoundError) { throw err; } if (err instanceof KeycloakUnauthorizedError) { if (!keycloakGrant) { logger.warn('Access denied to user for getAllGroups'); return []; } else { const user = await models.UserModel.loadUserById( keycloakGrant.access_token.content.sub ); const userGroups = await models.UserModel.getAllGroupsForUser(user); if (name) { return R.filter(R.propEq('name', name), userGroups); } else { return userGroups; } } } logger.warn(`getAllGroups failed unexpectedly: ${err.message}`); throw err; } }; export const getGroupsByProjectId: ResolverFn = async ( { id: pid }, _input, { hasPermission, models, keycloakGrant } ) => { const projectGroups = await models.GroupModel.loadGroupsByProjectId(pid); try { await hasPermission('group', 'viewAll'); return projectGroups; } catch (err) { if (!keycloakGrant) { logger.warn('No grant available for getGroupsByProjectId'); return []; } const user = await models.UserModel.loadUserById( keycloakGrant.access_token.content.sub ); const userGroups = await models.UserModel.getAllGroupsForUser(user); const userProjectGroups = R.intersection(projectGroups, userGroups); return userProjectGroups; } }; export const getGroupsByUserId: ResolverFn = async ( { id: uid }, _input, { hasPermission, models, keycloakGrant } ) => { const queryUser = await models.UserModel.loadUserById(uid); const queryUserGroups = await models.UserModel.getAllGroupsForUser(queryUser); try { await hasPermission('group', 'viewAll'); return queryUserGroups; } catch (err) { if (!keycloakGrant) { logger.warn('No grant available for getGroupsByUserId'); return []; } const currentUser = await models.UserModel.loadUserById( keycloakGrant.access_token.content.sub ); const currentUserGroups = await models.UserModel.getAllGroupsForUser( currentUser ); const bothUserGroups = R.intersection(queryUserGroups, currentUserGroups); return bothUserGroups; } }; export const getGroupByName: ResolverFn = async ( root, { name }, { models, hasPermission, keycloakGrant } ) => { try { await hasPermission('group', 'viewAll'); const group = await models.GroupModel.loadGroupByName(name); return group; } catch (err) { if (err instanceof GroupNotFoundError) { throw err; } if (err instanceof KeycloakUnauthorizedError) { if (!keycloakGrant) { logger.warn('Access denied to user for getGroupByName'); throw new GroupNotFoundError(`Group not found: ${name}`); } else { const user = await models.UserModel.loadUserById( keycloakGrant.access_token.content.sub ); const userGroups = await models.UserModel.getAllGroupsForUser(user); const group = R.head(R.filter(R.propEq('name', name), userGroups)); if (R.isEmpty(group)) { throw new GroupNotFoundError(`Group not found: ${name}`); } return group; } } logger.warn(`getGroupByName failed unexpectedly: ${err.message}`); throw err; } }; export const addGroup: ResolverFn = async ( _root, { input }, { models, sqlClientPool, hasPermission, userActivityLogger } ) => { await hasPermission('group', 'add'); if (validator.matches(input.name, /[^0-9a-z-]/)) { throw new Error( 'Only lowercase characters, numbers and dashes allowed for name!' ); } let parentGroupId: string; if (R.has('parentGroup', input)) { if (R.isEmpty(input.parentGroup)) { throw new Error('You must provide a group id or name'); } const parentGroup = await models.GroupModel.loadGroupByIdOrName( input.parentGroup ); parentGroupId = parentGroup.id; } const group = await models.GroupModel.addGroup({ name: input.name, parentGroupId }); // We don't have any projects yet. So just an empty string OpendistroSecurityOperations(sqlClientPool, models.GroupModel).syncGroup( input.name, '' ); userActivityLogger(`User added a group`, { project: '', event: 'api:addGroup', payload: { data: { group } } }); return group; }; export const updateGroup: ResolverFn = async ( _root, { input: { group: groupInput, patch } }, { models, hasPermission, userActivityLogger } ) => { const group = await models.GroupModel.loadGroupByIdOrName(groupInput); await hasPermission('group', 'update', { group: group.id }); if (isPatchEmpty({ patch })) { throw new Error('Input patch requires at least 1 attribute'); } if (typeof patch.name === 'string') { if (validator.matches(patch.name, /[^0-9a-z-]/)) { throw new Error( 'Only lowercase characters, numbers and dashes allowed for name!' ); } } const updatedGroup = await models.GroupModel.updateGroup({ id: group.id, name: patch.name }); userActivityLogger(`User updated a group`, { project: '', event: 'api:updateGroup', payload: { data: { patch, updatedGroup } } }); return updatedGroup; }; export const deleteGroup: ResolverFn = async ( _root, { input: { group: groupInput } }, { models, sqlClientPool, hasPermission, userActivityLogger } ) => { const group = await models.GroupModel.loadGroupByIdOrName(groupInput); await hasPermission('group', 'delete', { group: group.id }); await models.GroupModel.deleteGroup(group.id); OpendistroSecurityOperations(sqlClientPool, models.GroupModel).deleteGroup( group.name ); userActivityLogger(`User deleted a group`, { project: '', event: 'api:deleteGroup', payload: { data: { group } } }); return 'success'; }; export const deleteAllGroups: ResolverFn = async ( _root, _args, { models, hasPermission } ) => { await hasPermission('group', 'deleteAll'); const groups = await models.GroupModel.loadAllGroups(); let deleteErrors: String[] = []; for (const group of groups) { try { await models.GroupModel.deleteGroup(group.id); } catch (err) { deleteErrors = [...deleteErrors, `${group.name} (${group.id})`]; } } return R.ifElse(R.isEmpty, R.always('success'), deleteErrors => { throw new Error(`Could not delete groups: ${deleteErrors.join(', ')}`); })(deleteErrors); }; export const addUserToGroup: ResolverFn = async ( _root, { input: { user: userInput, group: groupInput, role } }, { models, hasPermission, userActivityLogger } ) => { if (R.isEmpty(userInput)) { throw new Error('You must provide a user id or email'); } const user = await models.UserModel.loadUserByIdOrUsername({ id: R.prop('id', userInput), username: R.prop('email', userInput) }); if (R.isEmpty(groupInput)) { throw new Error('You must provide a group id or name'); } const group = await models.GroupModel.loadGroupByIdOrName(groupInput); await hasPermission('group', 'addUser', { group: group.id }); await models.GroupModel.removeUserFromGroup(user, group); const updatedGroup = await models.GroupModel.addUserToGroup( user, group, role ); userActivityLogger(`User added a user to a group`, { project: '', event: 'api:addUserToGroup', payload: { input: { user: userInput, group: groupInput, role }, data: updatedGroup } }); return updatedGroup; }; export const removeUserFromGroup: ResolverFn = async ( _root, { input: { user: userInput, group: groupInput } }, { models, hasPermission, userActivityLogger } ) => { if (R.isEmpty(userInput)) { throw new Error('You must provide a user id or email'); } const user = await models.UserModel.loadUserByIdOrUsername({ id: R.prop('id', userInput), username: R.prop('email', userInput) }); if (R.isEmpty(groupInput)) { throw new Error('You must provide a group id or name'); } const group = await models.GroupModel.loadGroupByIdOrName(groupInput); await hasPermission('group', 'removeUser', { group: group.id }); const updatedGroup = await models.GroupModel.removeUserFromGroup(user, group); userActivityLogger(`User removed a user from a group`, { project: '', event: 'api:removeUserFromGroup', payload: { input: { user: userInput, group: groupInput }, data: updatedGroup } }); return updatedGroup; }; export const addGroupsToProject: ResolverFn = async ( _root, { input: { project: projectInput, groups: groupsInput } }, { models, sqlClientPool, hasPermission, userActivityLogger } ) => { const project = await projectHelpers(sqlClientPool).getProjectByProjectInput( projectInput ); await hasPermission('project', 'addGroup', { project: project.id }); if (R.isEmpty(groupsInput)) { throw new Error('You must provide groups'); } const groupsInputNotEmpty = R.filter(R.complement(R.isEmpty), groupsInput); if (R.isEmpty(groupsInputNotEmpty)) { throw new Error('One or more of your groups is missing an id or name'); } for (const groupInput of groupsInput) { const group = await models.GroupModel.loadGroupByIdOrName(groupInput); await models.GroupModel.addProjectToGroup(project.id, group); } const syncGroups = groupsInput.map(async groupInput => { const updatedGroup = await models.GroupModel.loadGroupByIdOrName( groupInput ); const projectIdsArray = await models.GroupModel.getProjectsFromGroupAndSubgroups( updatedGroup ); const projectIds = R.join(',')(projectIdsArray); OpendistroSecurityOperations(sqlClientPool, models.GroupModel).syncGroup( updatedGroup.name, projectIds ); }); try { await Promise.all(syncGroups); } catch (err) { throw new Error( `Could not sync groups with opendistro-security: ${err.message}` ); } userActivityLogger(`User synced groups to a project`, { project: project.name || '', event: 'api:addGroupsToProject', payload: { input: { project: projectInput, groups: groupsInput } } }); return await projectHelpers(sqlClientPool).getProjectById(project.id); }; export const addBillingGroup: ResolverFn = async ( _root, { input: { name, currency, billingSoftware, uptimeRobotStatusPageId } }, { models, hasPermission } ) => { await hasPermission('group', 'add'); if (!name) { throw new Error('You must provide a Billing Group name'); } if (!currency) { throw new Error('You must provide a Currency for the Billing Group'); } return models.GroupModel.addGroup({ name, attributes: { type: ['billing'], currency: [currency], uptimeRobotStatusPageId: [uptimeRobotStatusPageId], ...(billingSoftware ? { billingSoftware: [billingSoftware] } : {}) } }); }; export const updateBillingGroup: ResolverFn = async ( _root, { input: { group: groupInput, patch } }, { models, hasPermission } ) => { const group = await models.GroupModel.loadGroupByIdOrName(groupInput); const { id, attributes } = group; await hasPermission('group', 'update', { group: id }); if (isPatchEmpty({ patch })) { throw new Error('Input patch requires at least 1 attribute'); } const { name, currency, billingSoftware, uptimeRobotStatusPageId } = patch; const updatedAttributes = { ...attributes, type: ['billing'], ...(currency ? { currency: [currency] } : {}), ...(R.is(String, uptimeRobotStatusPageId) ? { uptimeRobotStatusPageId: [uptimeRobotStatusPageId] } : {}), ...(billingSoftware ? { billingSoftware: [billingSoftware] } : {}) }; const groupPatch = { ...group, name, attributes: updatedAttributes }; const updatedGroup = await models.GroupModel.updateGroup(groupPatch); return updatedGroup; }; export const addProjectToBillingGroup: ResolverFn = async ( _root, { input: { project: projectInput, group: groupInput } }, { models, sqlClientPool, hasPermission } ) => { const project = await projectHelpers(sqlClientPool).getProjectByProjectInput( projectInput ); await hasPermission('project', 'addGroup', { project: project.id }); if (R.isEmpty(groupInput)) { throw new Error('You must provide a billing group name or id'); } const { loadGroupsByProjectId, loadGroupByIdOrName, addProjectToGroup } = models.GroupModel; // Billing groups for this project const projectGroups = await loadGroupsByProjectId(project.id); const projectBillingGroups = projectGroups.filter(group => { const { attributes } = group; return !!('type' in attributes && attributes.type[0] === 'billing'); }); // A project can only be added to a single billing group. if (projectBillingGroups.length > 0) { throw new Error( `Project already added to billing group: ${projectBillingGroups[0].id}` ); } const group = await loadGroupByIdOrName(groupInput); await addProjectToGroup(project.id, { id: group.id }); return project; }; export const updateProjectBillingGroup: ResolverFn = async ( _root, { input: { project: projectInput, group: groupInput } }, { models, sqlClientPool, hasPermission } ) => { const project = await projectHelpers(sqlClientPool).getProjectByProjectInput( projectInput ); await hasPermission('project', 'addGroup', { project: project.id }); if (R.isEmpty(groupInput)) { throw new Error('You must provide a billing group name or id'); } const { loadGroupsByProjectId, loadGroupByIdOrName, addProjectToGroup } = models.GroupModel; // Get all billing groups for this project const projectGroups = await loadGroupsByProjectId(project.id); const billingGroupFilterFn = group => 'type' in group.attributes && group.attributes.type[0] === 'billing'; const projectBillingGroups = projectGroups.filter(billingGroupFilterFn); for (const group of projectBillingGroups) { await models.GroupModel.removeProjectFromGroup(project.id, group); } const group = await loadGroupByIdOrName(groupInput); await addProjectToGroup(project.id, group); return projectHelpers(sqlClientPool).getProjectById(project.id); }; export const removeProjectFromBillingGroup: ResolverFn = async ( root, { input: { project, group } }, context ) => removeGroupsFromProject( root, { input: { project, groups: [group] } }, context ); export const getAllProjectsByGroupId: ResolverFn = async ( root, input, context ) => getAllProjectsInGroup(root, { input: { id: root.id } }, { ...context }); export const getAllProjectsInGroup: ResolverFn = async ( _root, { input: groupInput }, { models, sqlClientPool, hasPermission, keycloakGrant } ) => { const { GroupModel: { loadGroupByIdOrName, getProjectsFromGroupAndSubgroups } } = models; try { await hasPermission('group', 'viewAll'); const group = await loadGroupByIdOrName(groupInput); const projectIdsArray = await getProjectsFromGroupAndSubgroups(group); return projectIdsArray.map(async id => projectHelpers(sqlClientPool).getProjectByProjectInput({ id }) ); } catch (err) { if (err instanceof GroupNotFoundError) { throw err; } if (!(err instanceof KeycloakUnauthorizedError)) { logger.warn(`getAllGroups failed unexpectedly: ${err.message}`); throw err; } } if (!keycloakGrant) { logger.warn( 'Access denied to user for getAllProjectsInGroup: no keycloakGrant' ); return []; } else { const group = await loadGroupByIdOrName(groupInput); const user = await models.UserModel.loadUserById( keycloakGrant.access_token.content.sub ); const userGroups = await models.UserModel.getAllGroupsForUser(user); // @ts-ignore if (!R.contains(group.name, R.pluck('name', userGroups))) { logger.warn( 'Access denied to user for getAllProjectsInGroup: user not in group' ); return []; } const projectIdsArray = await getProjectsFromGroupAndSubgroups(group); return projectIdsArray.map(async id => projectHelpers(sqlClientPool).getProjectByProjectInput({ id }) ); } }; /** * Given a billingGroup name|id, and month, get the costs for hits, storage, * and prod/dev environment costs * * @param {obj} root The rootValue passed from the Apollo server configuration. * @param {obj} args {input: GroupInput { id: String, name: String}, month: string} * @param {ExpressContext} context this includes the context passed from the apolloServer query * { sqlClient, hasPermissions, keycloakGrant, requestCache } * * @return {JSON} A JSON object that includes the billing costs, projects, and environments */ export const getBillingGroupCost: ResolverFn = async (root, args, context) => { const { models, hasPermission } = context; const { input: groupInput, month: yearMonth } = args; if (R.isEmpty(groupInput)) { throw new Error('You must provide a billing group name or id'); } await hasPermission('group', 'viewAll'); return await models.GroupModel.billingGroupCost(groupInput, yearMonth); }; /** * Get the costs for costs for all billing groups * * @param {obj} root The rootValue passed from the Apollo server configuration. * @param {obj} args {month: string} * @param {ExpressContext} context this includes the context passed from the apolloServer query * { sqlClient, hasPermissions, keycloakGrant, requestCache } * * @return {JSON} A JSON object */ export const getAllBillingGroupsCost: ResolverFn = async ( root, args, context ) => { const { models, hasPermission } = context; const { input: groupInput, month: yearMonth } = args; if (R.isEmpty(groupInput)) { throw new Error('You must provide a billing group name or id'); } await hasPermission('group', 'viewAll'); return await models.GroupModel.allBillingGroupCosts(yearMonth); }; export const removeGroupsFromProject: ResolverFn = async ( _root, { input: { project: projectInput, groups: groupsInput } }, { models, sqlClientPool, hasPermission } ) => { const project = await projectHelpers(sqlClientPool).getProjectByProjectInput( projectInput ); await hasPermission('project', 'removeGroup', { project: project.id }); if (R.isEmpty(groupsInput)) { throw new Error('You must provide groups'); } const groupsInputNotEmpty = R.filter(R.complement(R.isEmpty), groupsInput); if (R.isEmpty(groupsInputNotEmpty)) { throw new Error('One or more of your groups is missing an id or name'); } for (const groupInput of groupsInput) { const group = await models.GroupModel.loadGroupByIdOrName(groupInput); await models.GroupModel.removeProjectFromGroup(project.id, group); } const syncGroups = groupsInput.map(async groupInput => { const updatedGroup = await models.GroupModel.loadGroupByIdOrName( groupInput ); // @TODO: Load ProjectIDs of subgroups as well const projectIdsArray = await models.GroupModel.getProjectsFromGroupAndSubgroups( updatedGroup ); const projectIds = R.join(',')(projectIdsArray); OpendistroSecurityOperations(sqlClientPool, models.GroupModel).syncGroup( updatedGroup.name, projectIds ); }); try { await Promise.all(syncGroups); } catch (err) { throw new Error( `Could not sync groups with opendistro-security: ${err.message}` ); } return await projectHelpers(sqlClientPool).getProjectById(project.id); };
the_stack
import { ABSENT, arrayWith, objectLike, SynthUtils } from '@aws-cdk/assert-internal'; import '@aws-cdk/assert-internal/jest'; import { AutoScalingGroup } from '@aws-cdk/aws-autoscaling'; import { Certificate } from '@aws-cdk/aws-certificatemanager'; import * as ec2 from '@aws-cdk/aws-ec2'; import { MachineImage } from '@aws-cdk/aws-ec2'; import * as ecs from '@aws-cdk/aws-ecs'; import { AsgCapacityProvider } from '@aws-cdk/aws-ecs'; import { ApplicationLoadBalancer, ApplicationProtocol, ApplicationProtocolVersion, NetworkLoadBalancer, SslPolicy } from '@aws-cdk/aws-elasticloadbalancingv2'; import { PublicHostedZone } from '@aws-cdk/aws-route53'; import * as cloudmap from '@aws-cdk/aws-servicediscovery'; import * as cdk from '@aws-cdk/core'; import * as cxapi from '@aws-cdk/cx-api'; import * as ecsPatterns from '../../lib'; test('test ECS loadbalanced construct', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', { autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', { vpc, instanceType: new ec2.InstanceType('t2.micro'), machineImage: MachineImage.latestAmazonLinux(), }), })); // WHEN new ecsPatterns.ApplicationLoadBalancedEc2Service(stack, 'Service', { cluster, memoryLimitMiB: 1024, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('test'), environment: { TEST_ENVIRONMENT_VARIABLE1: 'test environment variable 1 value', TEST_ENVIRONMENT_VARIABLE2: 'test environment variable 2 value', }, dockerLabels: { label1: 'labelValue1', label2: 'labelValue2' }, }, desiredCount: 2, }); // THEN - stack contains a load balancer and a service expect(stack).toHaveResource('AWS::ElasticLoadBalancingV2::LoadBalancer'); expect(stack).toHaveResource('AWS::ECS::Service', { DesiredCount: 2, LaunchType: 'EC2', }); expect(stack).toHaveResourceLike('AWS::ECS::TaskDefinition', { ContainerDefinitions: [ { Environment: [ { Name: 'TEST_ENVIRONMENT_VARIABLE1', Value: 'test environment variable 1 value', }, { Name: 'TEST_ENVIRONMENT_VARIABLE2', Value: 'test environment variable 2 value', }, ], Memory: 1024, DockerLabels: { label1: 'labelValue1', label2: 'labelValue2', }, }, ], }); }); test('ApplicationLoadBalancedEc2Service desiredCount can be undefined when feature flag is set', () => { // GIVEN const stack = new cdk.Stack(); stack.node.setContext(cxapi.ECS_REMOVE_DEFAULT_DESIRED_COUNT, true); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', { autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', { vpc, instanceType: new ec2.InstanceType('t2.micro'), machineImage: MachineImage.latestAmazonLinux(), }), })); // WHEN new ecsPatterns.ApplicationLoadBalancedEc2Service(stack, 'Service', { cluster, memoryLimitMiB: 1024, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('test'), }, }); expect(stack).toHaveResource('AWS::ECS::Service', { DesiredCount: ABSENT, }); }); test('ApplicationLoadBalancedFargateService desiredCount can be undefined when feature flag is set', () => { // GIVEN const stack = new cdk.Stack(); stack.node.setContext(cxapi.ECS_REMOVE_DEFAULT_DESIRED_COUNT, true); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); // WHEN new ecsPatterns.ApplicationLoadBalancedFargateService(stack, 'Service', { cluster, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('test'), }, }); expect(stack).toHaveResource('AWS::ECS::Service', { DesiredCount: ABSENT, }); }); test('NetworkLoadBalancedEc2Service desiredCount can be undefined when feature flag is set', () => { // GIVEN const stack = new cdk.Stack(); stack.node.setContext(cxapi.ECS_REMOVE_DEFAULT_DESIRED_COUNT, true); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', { autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', { vpc, instanceType: new ec2.InstanceType('t2.micro'), machineImage: MachineImage.latestAmazonLinux(), }), })); // WHEN new ecsPatterns.NetworkLoadBalancedEc2Service(stack, 'Service', { cluster, memoryLimitMiB: 1024, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('test'), }, }); expect(stack).toHaveResource('AWS::ECS::Service', { DesiredCount: ABSENT, }); }); test('NetworkLoadBalancedFargateService desiredCount can be undefined when feature flag is set', () => { // GIVEN const stack = new cdk.Stack(); stack.node.setContext(cxapi.ECS_REMOVE_DEFAULT_DESIRED_COUNT, true); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); // WHEN new ecsPatterns.NetworkLoadBalancedFargateService(stack, 'Service', { cluster, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('test'), }, }); expect(stack).toHaveResource('AWS::ECS::Service', { DesiredCount: ABSENT, }); }); test('set vpc instead of cluster', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); // WHEN new ecsPatterns.ApplicationLoadBalancedEc2Service(stack, 'Service', { vpc, memoryLimitMiB: 1024, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('test'), environment: { TEST_ENVIRONMENT_VARIABLE1: 'test environment variable 1 value', TEST_ENVIRONMENT_VARIABLE2: 'test environment variable 2 value', }, }, desiredCount: 2, }); // THEN - stack does not contain a LaunchConfiguration\ const template = SynthUtils.synthesize(stack, { skipValidation: true }); expect(template).not.toHaveResource('AWS::AutoScaling::LaunchConfiguration'); expect(() => SynthUtils.synthesize(stack)).toThrow(); }); test('setting vpc and cluster throws error', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); // WHEN expect(() => new ecsPatterns.NetworkLoadBalancedEc2Service(stack, 'Service', { cluster, vpc, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('/aws/aws-example-app'), }, })).toThrow(); }); test('test ECS loadbalanced construct with memoryReservationMiB', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', { autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', { vpc, instanceType: new ec2.InstanceType('t2.micro'), machineImage: MachineImage.latestAmazonLinux(), }), })); // WHEN new ecsPatterns.ApplicationLoadBalancedEc2Service(stack, 'Service', { cluster, memoryReservationMiB: 1024, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('test'), }, }); // THEN - stack contains a load balancer and a service expect(stack).toHaveResource('AWS::ElasticLoadBalancingV2::LoadBalancer'); expect(stack).toHaveResourceLike('AWS::ECS::TaskDefinition', { ContainerDefinitions: [ { MemoryReservation: 1024, }, ], }); }); test('creates AWS Cloud Map service for Private DNS namespace with application load balanced ec2 service', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'MyVpc', {}); const cluster = new ecs.Cluster(stack, 'EcsCluster', { vpc }); cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', { autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', { vpc, instanceType: new ec2.InstanceType('t2.micro'), machineImage: MachineImage.latestAmazonLinux(), }), })); // WHEN cluster.addDefaultCloudMapNamespace({ name: 'foo.com', type: cloudmap.NamespaceType.DNS_PRIVATE, }); new ecsPatterns.ApplicationLoadBalancedEc2Service(stack, 'Service', { cluster, taskImageOptions: { containerPort: 8000, image: ecs.ContainerImage.fromRegistry('hello'), }, cloudMapOptions: { name: 'myApp', }, memoryLimitMiB: 512, }); // THEN expect(stack).toHaveResource('AWS::ECS::Service', { ServiceRegistries: [ { ContainerName: 'web', ContainerPort: 8000, RegistryArn: { 'Fn::GetAtt': [ 'ServiceCloudmapServiceDE76B29D', 'Arn', ], }, }, ], }); expect(stack).toHaveResource('AWS::ServiceDiscovery::Service', { DnsConfig: { DnsRecords: [ { TTL: 60, Type: 'SRV', }, ], NamespaceId: { 'Fn::GetAtt': [ 'EcsClusterDefaultServiceDiscoveryNamespaceB0971B2F', 'Id', ], }, RoutingPolicy: 'MULTIVALUE', }, HealthCheckCustomConfig: { FailureThreshold: 1, }, Name: 'myApp', NamespaceId: { 'Fn::GetAtt': [ 'EcsClusterDefaultServiceDiscoveryNamespaceB0971B2F', 'Id', ], }, }); }); test('creates AWS Cloud Map service for Private DNS namespace with network load balanced fargate service', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'MyVpc', {}); const cluster = new ecs.Cluster(stack, 'EcsCluster', { vpc }); cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', { autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', { vpc, instanceType: new ec2.InstanceType('t2.micro'), machineImage: MachineImage.latestAmazonLinux(), }), })); // WHEN cluster.addDefaultCloudMapNamespace({ name: 'foo.com', type: cloudmap.NamespaceType.DNS_PRIVATE, }); new ecsPatterns.NetworkLoadBalancedFargateService(stack, 'Service', { cluster, taskImageOptions: { containerPort: 8000, image: ecs.ContainerImage.fromRegistry('hello'), }, cloudMapOptions: { name: 'myApp', }, memoryLimitMiB: 512, }); // THEN expect(stack).toHaveResource('AWS::ECS::Service', { ServiceRegistries: [ { RegistryArn: { 'Fn::GetAtt': [ 'ServiceCloudmapServiceDE76B29D', 'Arn', ], }, }, ], }); expect(stack).toHaveResource('AWS::ServiceDiscovery::Service', { DnsConfig: { DnsRecords: [ { TTL: 60, Type: 'A', }, ], NamespaceId: { 'Fn::GetAtt': [ 'EcsClusterDefaultServiceDiscoveryNamespaceB0971B2F', 'Id', ], }, RoutingPolicy: 'MULTIVALUE', }, HealthCheckCustomConfig: { FailureThreshold: 1, }, Name: 'myApp', NamespaceId: { 'Fn::GetAtt': [ 'EcsClusterDefaultServiceDiscoveryNamespaceB0971B2F', 'Id', ], }, }); }); test('test Fargate loadbalanced construct', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); // WHEN new ecsPatterns.ApplicationLoadBalancedFargateService(stack, 'Service', { cluster, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('test'), environment: { TEST_ENVIRONMENT_VARIABLE1: 'test environment variable 1 value', TEST_ENVIRONMENT_VARIABLE2: 'test environment variable 2 value', }, dockerLabels: { label1: 'labelValue1', label2: 'labelValue2' }, }, desiredCount: 2, }); // THEN - stack contains a load balancer and a service expect(stack).toHaveResource('AWS::ElasticLoadBalancingV2::LoadBalancer'); expect(stack).toHaveResourceLike('AWS::ECS::TaskDefinition', { ContainerDefinitions: [ { Environment: [ { Name: 'TEST_ENVIRONMENT_VARIABLE1', Value: 'test environment variable 1 value', }, { Name: 'TEST_ENVIRONMENT_VARIABLE2', Value: 'test environment variable 2 value', }, ], LogConfiguration: { LogDriver: 'awslogs', Options: { 'awslogs-group': { Ref: 'ServiceTaskDefwebLogGroup2A898F61' }, 'awslogs-stream-prefix': 'Service', 'awslogs-region': { Ref: 'AWS::Region' }, }, }, DockerLabels: { label1: 'labelValue1', label2: 'labelValue2', }, }, ], }); expect(stack).toHaveResource('AWS::ECS::Service', { DesiredCount: 2, LaunchType: 'FARGATE', }); expect(stack).toHaveResource('AWS::ElasticLoadBalancingV2::Listener', { Port: 80, Protocol: 'HTTP', }); }); test('test Fargate loadbalanced construct opting out of log driver creation', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); // WHEN new ecsPatterns.ApplicationLoadBalancedFargateService(stack, 'Service', { cluster, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('test'), enableLogging: false, environment: { TEST_ENVIRONMENT_VARIABLE1: 'test environment variable 1 value', TEST_ENVIRONMENT_VARIABLE2: 'test environment variable 2 value', }, }, desiredCount: 2, }); // THEN - stack contains a load balancer and a service expect(stack).not.toHaveResource('AWS::ECS::TaskDefinition', { ContainerDefinitions: [ { Environment: [ { Name: 'TEST_ENVIRONMENT_VARIABLE1', Value: 'test environment variable 1 value', }, { Name: 'TEST_ENVIRONMENT_VARIABLE2', Value: 'test environment variable 2 value', }, ], LogConfiguration: { LogDriver: 'awslogs', Options: { 'awslogs-group': { Ref: 'ServiceTaskDefwebLogGroup2A898F61' }, 'awslogs-stream-prefix': 'Service', 'awslogs-region': { Ref: 'AWS::Region' }, }, }, }, ], }); }); test('test Fargate loadbalanced construct with TLS', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); const zone = new PublicHostedZone(stack, 'HostedZone', { zoneName: 'example.com' }); // WHEN new ecsPatterns.ApplicationLoadBalancedFargateService(stack, 'Service', { cluster, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('test'), }, domainName: 'api.example.com', domainZone: zone, certificate: Certificate.fromCertificateArn(stack, 'Cert', 'helloworld'), sslPolicy: SslPolicy.TLS12_EXT, }); // THEN - stack contains a load balancer and a service expect(stack).toHaveResource('AWS::ElasticLoadBalancingV2::LoadBalancer'); expect(stack).toHaveResource('AWS::ElasticLoadBalancingV2::Listener', { Port: 443, Protocol: 'HTTPS', Certificates: [{ CertificateArn: 'helloworld', }], SslPolicy: SslPolicy.TLS12_EXT, }); expect(stack).toHaveResource('AWS::ElasticLoadBalancingV2::TargetGroup', { Port: 80, Protocol: 'HTTP', TargetType: 'ip', VpcId: { Ref: 'VPCB9E5F0B4', }, }); expect(stack).toHaveResource('AWS::ECS::Service', { DesiredCount: 1, LaunchType: 'FARGATE', }); expect(stack).toHaveResource('AWS::Route53::RecordSet', { Name: 'api.example.com.', HostedZoneId: { Ref: 'HostedZoneDB99F866', }, Type: 'A', AliasTarget: { HostedZoneId: { 'Fn::GetAtt': ['ServiceLBE9A1ADBC', 'CanonicalHostedZoneID'] }, DNSName: { 'Fn::Join': ['', ['dualstack.', { 'Fn::GetAtt': ['ServiceLBE9A1ADBC', 'DNSName'] }]] }, }, }); }); test('test Fargateloadbalanced construct with TLS and default certificate', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); const zone = new PublicHostedZone(stack, 'HostedZone', { zoneName: 'example.com' }); // WHEN new ecsPatterns.ApplicationLoadBalancedFargateService(stack, 'Service', { cluster, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('test'), }, domainName: 'api.example.com', domainZone: zone, protocol: ApplicationProtocol.HTTPS, }); // THEN - stack contains a load balancer, a service, and a certificate expect(stack).toHaveResource('AWS::CertificateManager::Certificate', { DomainName: 'api.example.com', DomainValidationOptions: [ { DomainName: 'api.example.com', HostedZoneId: { Ref: 'HostedZoneDB99F866', }, }, ], ValidationMethod: 'DNS', }); expect(stack).toHaveResource('AWS::ElasticLoadBalancingV2::LoadBalancer'); expect(stack).toHaveResource('AWS::ElasticLoadBalancingV2::Listener', { Port: 443, Protocol: 'HTTPS', Certificates: [{ CertificateArn: { Ref: 'ServiceCertificateA7C65FE6', }, }], }); expect(stack).toHaveResource('AWS::ECS::Service', { DesiredCount: 1, LaunchType: 'FARGATE', }); expect(stack).toHaveResource('AWS::Route53::RecordSet', { Name: 'api.example.com.', HostedZoneId: { Ref: 'HostedZoneDB99F866', }, Type: 'A', AliasTarget: { HostedZoneId: { 'Fn::GetAtt': ['ServiceLBE9A1ADBC', 'CanonicalHostedZoneID'] }, DNSName: { 'Fn::Join': ['', ['dualstack.', { 'Fn::GetAtt': ['ServiceLBE9A1ADBC', 'DNSName'] }]] }, }, }); }); test('errors when setting domainName but not domainZone', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); // THEN expect(() => { new ecsPatterns.ApplicationLoadBalancedFargateService(stack, 'Service', { cluster, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('test'), }, domainName: 'api.example.com', }); }).toThrow(); }); test('errors when setting both HTTP protocol and certificate', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); // THEN expect(() => { new ecsPatterns.ApplicationLoadBalancedFargateService(stack, 'Service', { cluster, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('test'), }, protocol: ApplicationProtocol.HTTP, certificate: Certificate.fromCertificateArn(stack, 'Cert', 'helloworld'), }); }).toThrow(); }); test('errors when setting both HTTP protocol and redirectHTTP', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); // THEN expect(() => { new ecsPatterns.ApplicationLoadBalancedFargateService(stack, 'Service', { cluster, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('test'), }, protocol: ApplicationProtocol.HTTP, redirectHTTP: true, }); }).toThrow(); }); test('does not throw errors when not setting HTTPS protocol but certificate for redirectHTTP', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); const zone = new PublicHostedZone(stack, 'HostedZone', { zoneName: 'example.com' }); // THEN new ecsPatterns.ApplicationLoadBalancedFargateService(stack, 'Service', { cluster, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('test'), }, domainName: 'api.example.com', domainZone: zone, redirectHTTP: true, certificate: Certificate.fromCertificateArn(stack, 'Cert', 'helloworld'), }); }); test('errors when setting HTTPS protocol but not domain name', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); // THEN expect(() => { new ecsPatterns.ApplicationLoadBalancedFargateService(stack, 'Service', { cluster, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('test'), }, protocol: ApplicationProtocol.HTTPS, }); }).toThrow(); }); test('test Fargate loadbalanced construct with optional log driver input', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); // WHEN new ecsPatterns.ApplicationLoadBalancedFargateService(stack, 'Service', { cluster, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('test'), enableLogging: false, environment: { TEST_ENVIRONMENT_VARIABLE1: 'test environment variable 1 value', TEST_ENVIRONMENT_VARIABLE2: 'test environment variable 2 value', }, logDriver: new ecs.AwsLogDriver({ streamPrefix: 'TestStream', }), }, desiredCount: 2, }); // THEN - stack contains a load balancer and a service expect(stack).toHaveResourceLike('AWS::ECS::TaskDefinition', { ContainerDefinitions: [ { Environment: [ { Name: 'TEST_ENVIRONMENT_VARIABLE1', Value: 'test environment variable 1 value', }, { Name: 'TEST_ENVIRONMENT_VARIABLE2', Value: 'test environment variable 2 value', }, ], LogConfiguration: { LogDriver: 'awslogs', Options: { 'awslogs-group': { Ref: 'ServiceTaskDefwebLogGroup2A898F61' }, 'awslogs-stream-prefix': 'TestStream', 'awslogs-region': { Ref: 'AWS::Region' }, }, }, }, ], }); }); test('test Fargate loadbalanced construct with logging enabled', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); // WHEN new ecsPatterns.ApplicationLoadBalancedFargateService(stack, 'Service', { cluster, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('test'), enableLogging: true, environment: { TEST_ENVIRONMENT_VARIABLE1: 'test environment variable 1 value', TEST_ENVIRONMENT_VARIABLE2: 'test environment variable 2 value', }, }, desiredCount: 2, }); // THEN - stack contains a load balancer and a service expect(stack).toHaveResourceLike('AWS::ECS::TaskDefinition', { ContainerDefinitions: [ { Environment: [ { Name: 'TEST_ENVIRONMENT_VARIABLE1', Value: 'test environment variable 1 value', }, { Name: 'TEST_ENVIRONMENT_VARIABLE2', Value: 'test environment variable 2 value', }, ], LogConfiguration: { LogDriver: 'awslogs', Options: { 'awslogs-group': { Ref: 'ServiceTaskDefwebLogGroup2A898F61' }, 'awslogs-stream-prefix': 'Service', 'awslogs-region': { Ref: 'AWS::Region' }, }, }, }, ], }); }); test('test Fargate loadbalanced construct with both image and taskDefinition provided', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); const taskDefinition = new ecs.Ec2TaskDefinition(stack, 'Ec2TaskDef'); taskDefinition.addContainer('web', { image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'), memoryLimitMiB: 512, }); // WHEN expect(() => new ecsPatterns.ApplicationLoadBalancedFargateService(stack, 'Service', { cluster, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('test'), enableLogging: true, environment: { TEST_ENVIRONMENT_VARIABLE1: 'test environment variable 1 value', TEST_ENVIRONMENT_VARIABLE2: 'test environment variable 2 value', }, }, desiredCount: 2, taskDefinition, })).toThrow(); }); test('test Fargate application loadbalanced construct with taskDefinition provided', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); const taskDefinition = new ecs.FargateTaskDefinition(stack, 'FargateTaskDef'); const container = taskDefinition.addContainer('passedTaskDef', { image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'), memoryLimitMiB: 512, }); container.addPortMappings({ containerPort: 80, }); // WHEN new ecsPatterns.ApplicationLoadBalancedFargateService(stack, 'Service', { cluster, taskDefinition, desiredCount: 2, memoryLimitMiB: 1024, }); expect(stack).toHaveResourceLike('AWS::ECS::TaskDefinition', { ContainerDefinitions: [ { Image: 'amazon/amazon-ecs-sample', Memory: 512, Name: 'passedTaskDef', PortMappings: [ { ContainerPort: 80, Protocol: 'tcp', }, ], }, ], }); }); test('ALB - throws if desiredTaskCount is 0', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', { autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', { vpc, instanceType: new ec2.InstanceType('t2.micro'), machineImage: MachineImage.latestAmazonLinux(), }), })); // THEN expect(() => new ecsPatterns.ApplicationLoadBalancedEc2Service(stack, 'Service', { cluster, memoryLimitMiB: 1024, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('test'), }, desiredCount: 0, }), ).toThrow(/You must specify a desiredCount greater than 0/); }); test('NLB - throws if desiredTaskCount is 0', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', { autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', { vpc, instanceType: new ec2.InstanceType('t2.micro'), machineImage: MachineImage.latestAmazonLinux(), }), })); // THEN expect(() => new ecsPatterns.NetworkLoadBalancedEc2Service(stack, 'Service', { cluster, memoryLimitMiB: 1024, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('test'), }, desiredCount: 0, }), ).toThrow(/You must specify a desiredCount greater than 0/); }); test('ALBFargate - having *HealthyPercent properties', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); // WHEN new ecsPatterns.ApplicationLoadBalancedFargateService(stack, 'ALB123Service', { cluster, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'), }, minHealthyPercent: 100, maxHealthyPercent: 200, }); // THEN expect(stack).toHaveResourceLike('AWS::ECS::Service', { DeploymentConfiguration: { MinimumHealthyPercent: 100, MaximumPercent: 200, }, }); }); test('NLBFargate - having *HealthyPercent properties', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); // WHEN new ecsPatterns.NetworkLoadBalancedFargateService(stack, 'Service', { cluster, memoryLimitMiB: 1024, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'), }, desiredCount: 1, minHealthyPercent: 100, maxHealthyPercent: 200, }); // THEN expect(stack).toHaveResourceLike('AWS::ECS::Service', { DeploymentConfiguration: { MinimumHealthyPercent: 100, MaximumPercent: 200, }, }); }); test('ALB - having *HealthyPercent properties', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', { autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', { vpc, instanceType: new ec2.InstanceType('t2.micro'), machineImage: MachineImage.latestAmazonLinux(), }), })); // WHEN new ecsPatterns.ApplicationLoadBalancedEc2Service(stack, 'Service', { cluster, memoryLimitMiB: 1024, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'), }, desiredCount: 1, minHealthyPercent: 100, maxHealthyPercent: 200, }); // THEN expect(stack).toHaveResourceLike('AWS::ECS::Service', { DeploymentConfiguration: { MinimumHealthyPercent: 100, MaximumPercent: 200, }, }); }); test('ALB - includes provided protocol version properties', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', { autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', { vpc, instanceType: new ec2.InstanceType('t2.micro'), machineImage: MachineImage.latestAmazonLinux(), }), })); const zone = new PublicHostedZone(stack, 'HostedZone', { zoneName: 'example.com' }); // WHEN new ecsPatterns.ApplicationLoadBalancedEc2Service(stack, 'Service', { cluster, memoryLimitMiB: 1024, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'), }, desiredCount: 1, domainName: 'api.example.com', domainZone: zone, protocol: ApplicationProtocol.HTTPS, protocolVersion: ApplicationProtocolVersion.GRPC, }); // THEN expect(stack).toHaveResourceLike('AWS::ElasticLoadBalancingV2::TargetGroup', { ProtocolVersion: 'GRPC', }); }); test('NLB - having *HealthyPercent properties', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', { autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', { vpc, instanceType: new ec2.InstanceType('t2.micro'), machineImage: MachineImage.latestAmazonLinux(), }), })); // WHEN new ecsPatterns.NetworkLoadBalancedEc2Service(stack, 'Service', { cluster, memoryLimitMiB: 1024, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'), }, desiredCount: 1, minHealthyPercent: 100, maxHealthyPercent: 200, }); // THEN expect(stack).toHaveResourceLike('AWS::ECS::Service', { DeploymentConfiguration: { MinimumHealthyPercent: 100, MaximumPercent: 200, }, }); }); test('ALB - having deployment controller', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', { autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', { vpc, instanceType: new ec2.InstanceType('t2.micro'), machineImage: MachineImage.latestAmazonLinux(), }), })); // WHEN new ecsPatterns.ApplicationLoadBalancedEc2Service(stack, 'Service', { cluster, memoryLimitMiB: 1024, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'), }, deploymentController: { type: ecs.DeploymentControllerType.CODE_DEPLOY, }, }); // THEN expect(stack).toHaveResourceLike('AWS::ECS::Service', { DeploymentController: { Type: 'CODE_DEPLOY', }, }); }); test('NLB - having deployment controller', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', { autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', { vpc, instanceType: new ec2.InstanceType('t2.micro'), machineImage: MachineImage.latestAmazonLinux(), }), })); // WHEN new ecsPatterns.NetworkLoadBalancedEc2Service(stack, 'Service', { cluster, memoryLimitMiB: 1024, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'), }, deploymentController: { type: ecs.DeploymentControllerType.CODE_DEPLOY, }, }); // THEN expect(stack).toHaveResourceLike('AWS::ECS::Service', { DeploymentController: { Type: 'CODE_DEPLOY', }, }); }); test('ALB with circuit breaker', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', { autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', { vpc, instanceType: new ec2.InstanceType('t2.micro'), machineImage: MachineImage.latestAmazonLinux(), }), })); // WHEN new ecsPatterns.ApplicationLoadBalancedEc2Service(stack, 'Service', { cluster, memoryLimitMiB: 1024, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'), }, circuitBreaker: { rollback: true }, }); // THEN expect(stack).toHaveResourceLike('AWS::ECS::Service', { DeploymentConfiguration: { DeploymentCircuitBreaker: { Enable: true, Rollback: true, }, }, DeploymentController: { Type: 'ECS', }, }); }); test('NLB with circuit breaker', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', { autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', { vpc, instanceType: new ec2.InstanceType('t2.micro'), machineImage: MachineImage.latestAmazonLinux(), }), })); // WHEN new ecsPatterns.NetworkLoadBalancedEc2Service(stack, 'Service', { cluster, memoryLimitMiB: 1024, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'), }, circuitBreaker: { rollback: true }, }); // THEN expect(stack).toHaveResourceLike('AWS::ECS::Service', { DeploymentConfiguration: { DeploymentCircuitBreaker: { Enable: true, Rollback: true, }, }, DeploymentController: { Type: 'ECS', }, }); }); test('NetworkLoadbalancedEC2Service accepts previously created load balancer', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'Vpc'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc, clusterName: 'MyCluster' }); cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', { autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', { vpc, instanceType: new ec2.InstanceType('t2.micro'), machineImage: MachineImage.latestAmazonLinux(), }), })); const nlb = new NetworkLoadBalancer(stack, 'NLB', { vpc }); const taskDef = new ecs.Ec2TaskDefinition(stack, 'TaskDef'); const container = taskDef.addContainer('Container', { image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'), memoryLimitMiB: 1024, }); container.addPortMappings({ containerPort: 80 }); // WHEN new ecsPatterns.NetworkLoadBalancedEc2Service(stack, 'Service', { cluster, loadBalancer: nlb, taskDefinition: taskDef, }); // THEN expect(stack).toHaveResourceLike('AWS::ECS::Service', { LaunchType: 'EC2', }); expect(stack).toHaveResourceLike('AWS::ElasticLoadBalancingV2::LoadBalancer', { Type: 'network', }); }); test('NetworkLoadBalancedEC2Service accepts imported load balancer', () => { // GIVEN const stack = new cdk.Stack(); const nlbArn = 'arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188'; const vpc = new ec2.Vpc(stack, 'Vpc'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc, clusterName: 'MyCluster' }); cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', { autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', { vpc, instanceType: new ec2.InstanceType('t2.micro'), machineImage: MachineImage.latestAmazonLinux(), }), })); const nlb = NetworkLoadBalancer.fromNetworkLoadBalancerAttributes(stack, 'NLB', { loadBalancerArn: nlbArn, vpc, }); const taskDef = new ecs.Ec2TaskDefinition(stack, 'TaskDef'); const container = taskDef.addContainer('Container', { image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'), memoryLimitMiB: 1024, }); container.addPortMappings({ containerPort: 80, }); // WHEN new ecsPatterns.NetworkLoadBalancedEc2Service(stack, 'Service', { cluster, loadBalancer: nlb, desiredCount: 1, taskDefinition: taskDef, }); // THEN expect(stack).toHaveResourceLike('AWS::ECS::Service', { LaunchType: 'EC2', LoadBalancers: [{ ContainerName: 'Container', ContainerPort: 80 }], }); expect(stack).toHaveResourceLike('AWS::ElasticLoadBalancingV2::TargetGroup'); expect(stack).toHaveResourceLike('AWS::ElasticLoadBalancingV2::Listener', { LoadBalancerArn: nlb.loadBalancerArn, Port: 80, }); }); test('ApplicationLoadBalancedEC2Service accepts previously created load balancer', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'Vpc'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc, clusterName: 'MyCluster' }); cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', { autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', { vpc, instanceType: new ec2.InstanceType('t2.micro'), machineImage: MachineImage.latestAmazonLinux(), }), })); const sg = new ec2.SecurityGroup(stack, 'SG', { vpc }); const alb = new ApplicationLoadBalancer(stack, 'NLB', { vpc, securityGroup: sg, }); const taskDef = new ecs.Ec2TaskDefinition(stack, 'TaskDef'); const container = taskDef.addContainer('Container', { image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'), memoryLimitMiB: 1024, }); container.addPortMappings({ containerPort: 80 }); // WHEN new ecsPatterns.ApplicationLoadBalancedEc2Service(stack, 'Service', { cluster, loadBalancer: alb, taskDefinition: taskDef, }); // THEN expect(stack).toHaveResourceLike('AWS::ECS::Service', { LaunchType: 'EC2', }); expect(stack).toHaveResourceLike('AWS::ElasticLoadBalancingV2::LoadBalancer', { Type: 'application', }); }); test('ApplicationLoadBalancedEC2Service accepts imported load balancer', () => { // GIVEN const stack = new cdk.Stack(); const albArn = 'arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188'; const vpc = new ec2.Vpc(stack, 'Vpc'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc, clusterName: 'MyCluster' }); cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', { autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', { vpc, instanceType: new ec2.InstanceType('t2.micro'), machineImage: MachineImage.latestAmazonLinux(), }), })); const sg = new ec2.SecurityGroup(stack, 'SG', { vpc }); const alb = ApplicationLoadBalancer.fromApplicationLoadBalancerAttributes(stack, 'ALB', { loadBalancerArn: albArn, vpc, securityGroupId: sg.securityGroupId, loadBalancerDnsName: 'MyName', }); const taskDef = new ecs.Ec2TaskDefinition(stack, 'TaskDef'); const container = taskDef.addContainer('Container', { image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'), memoryLimitMiB: 1024, }); container.addPortMappings({ containerPort: 80, }); // WHEN new ecsPatterns.ApplicationLoadBalancedEc2Service(stack, 'Service', { cluster, loadBalancer: alb, taskDefinition: taskDef, }); // THEN expect(stack).toHaveResourceLike('AWS::ECS::Service', { LaunchType: 'EC2', LoadBalancers: [{ ContainerName: 'Container', ContainerPort: 80 }], }); expect(stack).toHaveResourceLike('AWS::ElasticLoadBalancingV2::TargetGroup'); expect(stack).toHaveResourceLike('AWS::ElasticLoadBalancingV2::Listener', { LoadBalancerArn: alb.loadBalancerArn, Port: 80, }); }); test('test ECS loadbalanced construct default/open security group', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', { autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', { vpc, instanceType: new ec2.InstanceType('t2.micro'), machineImage: MachineImage.latestAmazonLinux(), }), })); // WHEN new ecsPatterns.ApplicationLoadBalancedEc2Service(stack, 'Service', { cluster, memoryReservationMiB: 1024, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('test'), }, }); // THEN - Stack contains no ingress security group rules expect(stack).toHaveResourceLike('AWS::EC2::SecurityGroup', { SecurityGroupIngress: [{ CidrIp: '0.0.0.0/0', FromPort: 80, IpProtocol: 'tcp', ToPort: 80, }], }); }); test('test ECS loadbalanced construct closed security group', () => { // GIVEN const stack = new cdk.Stack(); const vpc = new ec2.Vpc(stack, 'VPC'); const cluster = new ecs.Cluster(stack, 'Cluster', { vpc }); cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', { autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', { vpc, instanceType: new ec2.InstanceType('t2.micro'), machineImage: MachineImage.latestAmazonLinux(), }), })); const zone = new PublicHostedZone(stack, 'HostedZone', { zoneName: 'example.com' }); // WHEN new ecsPatterns.ApplicationLoadBalancedEc2Service(stack, 'Service', { cluster, memoryReservationMiB: 1024, taskImageOptions: { image: ecs.ContainerImage.fromRegistry('test'), }, domainName: 'api.example.com', domainZone: zone, certificate: Certificate.fromCertificateArn(stack, 'Cert', 'helloworld'), openListener: false, redirectHTTP: true, }); // THEN - Stack contains no ingress security group rules expect(stack).not.toHaveResourceLike('AWS::EC2::SecurityGroup', { SecurityGroupIngress: arrayWith(objectLike({})), }); });
the_stack
import gql from "lib/gql" import { GraphQLSchema } from "graphql" import moment from "moment" import { defineCustomLocale, isExisty } from "lib/helpers" import { normalizeImageData, getDefault } from "schema/v2/image" import { formatMarkdownValue } from "schema/v2/fields/markdown" import Format from "schema/v2/input_fields/format" const LocaleEnViewingRoomRelativeShort = "en-viewing-room-relative-short" defineCustomLocale(LocaleEnViewingRoomRelativeShort, { parentLocale: "en", relativeTime: { future: "soon", s: "", ss: "", m: "", mm: "", h: "", hh: "", d: "", dd: "", M: "", MM: "", y: "", yy: "", }, }) const LocaleEnViewingRoomRelativeLong = "en-viewing-room-relative-long" defineCustomLocale(LocaleEnViewingRoomRelativeLong, { parentLocale: "en", relativeTime: { s: "%d second", ss: "%d seconds", m: "%d minute", mm: "%d minutes", h: "%d hour", hh: "%d hours", d: "%d day", dd: "%d days", M: "%d month", MM: "%d months", y: "%d year", yy: "%d years", }, }) export const gravityStitchingEnvironment = ( localSchema: GraphQLSchema, gravitySchema: GraphQLSchema & { transforms: any } ) => { return { // The SDL used to declare how to stitch an object extensionSchema: gql` extend type Me { secondFactors(kinds: [SecondFactorKind]): [SecondFactor] addressConnection( first: Int last: Int after: String before: String ): UserAddressConnection } extend type ViewingRoom { artworksConnection( first: Int last: Int after: String before: String ): ArtworkConnection partnerArtworksConnection( first: Int last: Int after: String before: String ): ArtworkConnection distanceToOpen(short: Boolean! = false): String distanceToClose(short: Boolean! = false): String partner: Partner } extend type ArtistSeries { artists(page: Int, size: Int): [Artist] image: Image artworksConnection(first: Int, after: String): ArtworkConnection descriptionFormatted(format: Format): String """ A formatted string that shows the number of available works or (as a fallback) the number of works in general. """ artworksCountMessage: String } extend type Partner { viewingRoomsConnection( first: Int after: String statuses: [ViewingRoomStatusEnum!] ): ViewingRoomsConnection } extend type Show { viewingRoomsConnection: ViewingRoomsConnection } extend type Artist { artistSeriesConnection( first: Int last: Int after: String before: String ): ArtistSeriesConnection } extend type Artwork { artistSeriesConnection( first: Int last: Int after: String before: String ): ArtistSeriesConnection } extend type Viewer { viewingRoomsConnection( first: Int after: String statuses: [ViewingRoomStatusEnum!] partnerID: ID ): ViewingRoomsConnection } `, resolvers: { Me: { secondFactors: { resolve: (_parent, args, context, info) => { return info.mergeInfo.delegateToSchema({ schema: gravitySchema, operation: "query", fieldName: "_unused_gravity_secondFactors", args: args, context, info, }) }, }, addressConnection: { fragment: gql` ... on Me { __typename } `, resolve: (_parent, args, context, info) => { return info.mergeInfo.delegateToSchema({ schema: gravitySchema, operation: "query", fieldName: "_unused_gravity_userAddressConnection", args: { ...args, userId: context.userID }, context, info, }) }, }, }, ArtistSeries: { artworksConnection: { fragment: gql` ... on ArtistSeries { artworkIDs } `, resolve: async ({ artworkIDs: ids }, _args, context, info) => { // Exclude the current artwork in a series so that lists of // other artworks in the same series don't show the artwork. const filteredIDs = context.currentArtworkID ? ids.filter((id) => id !== context.currentArtworkID) : ids return await info.mergeInfo.delegateToSchema({ args: { ids: filteredIDs, ..._args, }, schema: localSchema, operation: "query", fieldName: "artworks", context, info, }) }, }, descriptionFormatted: { fragment: gql` ... on ArtistSeries { description } `, resolve: async ({ description }, { format }) => { if (!isExisty(description) || typeof description !== "string") return null const { type: formatType } = Format const desiredFormat = formatType ?.getValues() ?.find((e) => e.name === format)?.value return formatMarkdownValue(description, desiredFormat) }, }, artworksCountMessage: { fragment: gql` ... on ArtistSeries { forSaleArtworksCount artworksCount } `, resolve: async ({ forSaleArtworksCount, artworksCount }) => { let artworksCountMessage if (forSaleArtworksCount) { artworksCountMessage = `${forSaleArtworksCount} available` } else { artworksCountMessage = `${artworksCount} ${ artworksCount === 1 ? "work" : "works" }` } return artworksCountMessage }, }, image: { fragment: gql` ... on ArtistSeries { image_url: imageURL original_height: imageHeight original_width: imageWidth representativeArtworkID } `, resolve: async ( { representativeArtworkID, image_url, original_height, original_width, }, args, context, info ) => { if (image_url) { context.imageData = { image_url, original_width, original_height, } } else if (representativeArtworkID) { const { artworkLoader } = context const { images } = await artworkLoader(representativeArtworkID) context.imageData = normalizeImageData(getDefault(images)) } return info.mergeInfo.delegateToSchema({ args, schema: localSchema, operation: "query", fieldName: "_do_not_use_image", context, info, }) }, }, artists: { fragment: gql` ... on ArtistSeries { artistIDs internalID } `, resolve: ({ artistIDs: ids, internalID }, args, context, info) => { if (ids.length === 0) { return [] } context.currentArtistSeriesInternalID = internalID return info.mergeInfo.delegateToSchema({ schema: localSchema, operation: "query", fieldName: "artists", args: { ids, ...args, }, context, info, }) }, }, }, ViewingRoom: { artworksConnection: { fragment: gql` ... on ViewingRoom { artworkIDs } `, resolve: ({ artworkIDs: ids }, args, context, info) => { // qs ignores empty array/object and prevents us from sending `?array[]=`. // This is a workaround to map an empty array to `[null]` so it gets treated // as an empty string. // https://github.com/ljharb/qs/issues/362 // // Note that we can't easily change this globally as there are multiple places // clients are sending params of empty array but expecting Gravity to return // non-empty data. This only fixes the issue for viewing room artworks. if (ids.length === 0) { ids = [null] } return info.mergeInfo.delegateToSchema({ schema: localSchema, operation: "query", fieldName: "artworks", args: { ids, respectParamsOrder: true, ...args, }, context, info, }) }, }, partnerArtworksConnection: { fragment: gql` ... on ViewingRoom { internalID partnerID } `, resolve: ( { internalID: viewingRoomID, partnerID }, args, context, info ) => { return info.mergeInfo.delegateToSchema({ schema: localSchema, operation: "query", fieldName: "partnerArtworks", args: { viewingRoomID, partnerID, ...args, }, context, info, }) }, }, distanceToOpen: { fragment: gql` ... on ViewingRoom { startAt } `, resolve: ( { startAt: _startAt }: { startAt: string | null }, { short = false }: { short?: boolean } ) => { if (_startAt === null) { return null } const startAt = moment(_startAt) const now = moment() if (startAt < now) { return null } if (!short && startAt > now.clone().add(30, "days")) { return null } const distance = moment.duration(startAt.diff(now)) return distance .locale( short ? LocaleEnViewingRoomRelativeShort : LocaleEnViewingRoomRelativeLong ) .humanize(short, { ss: 1, d: 31 }) }, }, distanceToClose: { fragment: gql` ... on ViewingRoom { startAt endAt } `, resolve: ( { startAt: _startAt, endAt: _endAt, }: { startAt: string | null; endAt: string | null }, { short = false }: { short?: boolean } ) => { if (_startAt === null || _endAt === null) { return null } const startAt = moment(_startAt) const endAt = moment(_endAt) const now = moment() if (startAt > now) { return null } if (endAt < now) { return null } if (short) { if (endAt > now.clone().add(5, "days")) { return null } } else { if (endAt > now.clone().add(30, "days")) { return null } } return `${moment .duration(endAt.diff(now)) .locale(LocaleEnViewingRoomRelativeLong) .humanize(false, { ss: 1, d: 31 })}` }, }, partner: { fragment: gql` ... on ViewingRoom { partnerID } `, resolve: ({ partnerID: id }, _args, context, info) => { return info.mergeInfo.delegateToSchema({ schema: localSchema, operation: "query", fieldName: "partner", args: { id, }, context, info, }) }, }, }, Viewer: { viewingRoomsConnection: { fragment: ` ... on Viewer { __typename }`, resolve: (_parent, args, context, info) => { return info.mergeInfo.delegateToSchema({ schema: gravitySchema, operation: "query", fieldName: "_unused_gravity_viewingRoomsConnection", args, context, info, }) }, }, }, Partner: { viewingRoomsConnection: { fragment: gql` ... on Partner { internalID } `, resolve: ({ internalID: partnerID }, args, context, info) => { return info.mergeInfo.delegateToSchema({ schema: gravitySchema, operation: "query", fieldName: "_unused_gravity_viewingRoomsConnection", args: { partnerID, ...args, }, context, info, }) }, }, }, Show: { viewingRoomsConnection: { fragment: gql` ... on Show { viewingRoomIDs } `, resolve: ({ viewingRoomIDs: ids }, _args, context, info) => { if (ids.length === 0) return null return info.mergeInfo.delegateToSchema({ schema: gravitySchema, operation: "query", fieldName: "_unused_gravity_viewingRoomsConnection", args: { ids, }, context, info, }) }, }, }, Artist: { artistSeriesConnection: { fragment: gql` ... on Artist { internalID } `, resolve: ({ internalID: artistID }, args, context, info) => { return info.mergeInfo.delegateToSchema({ schema: gravitySchema, operation: "query", fieldName: "artistSeriesConnection", args: { artistID, ...args, // Exclude the current artist series so that lists of // artist series by the artist don't include the current series // if there is one. ...(!!context.currentArtistSeriesInternalID && { excludeIDs: [context.currentArtistSeriesInternalID], }), }, context, info, }) }, }, }, Artwork: { artistSeriesConnection: { fragment: gql` ... on Artwork { internalID } `, resolve: ({ internalID: artworkID }, args, context, info) => { context.currentArtworkID = artworkID return info.mergeInfo.delegateToSchema({ schema: gravitySchema, operation: "query", fieldName: "artistSeriesConnection", args: { artworkID, ...args, }, context, info, }) }, }, }, }, } }
the_stack
import { noop } from "lodash"; import { v1 as uuid } from "uuid"; import { pureMerge } from "coral-common/utils"; import { GQLResolver, GQLUSER_ROLE, GQLUSER_STATUS, QueryToSettingsResolver, QueryToUsersResolver, } from "coral-framework/schema"; import { act, createQueryResolverStub, createResolversStub, CreateTestRendererParams, replaceHistoryLocation, wait, waitForElement, waitUntilThrow, within, } from "coral-framework/testHelpers"; import create from "../create"; import { communityUsers, disabledEmail, disabledLocalAuth, disabledLocalAuthAdminTargetFilter, disabledLocalRegistration, emptyCommunityUsers, settings, settingsWithMultisite, siteConnection, sites, users, } from "../fixtures"; const viewer = users.admins[0]; beforeEach(async () => { replaceHistoryLocation("http://localhost/admin/community"); }); const createTestRenderer = async ( params: CreateTestRendererParams<GQLResolver> = {} ) => { const { testRenderer } = create({ ...params, resolvers: pureMerge( createResolversStub<GQLResolver>({ Query: { settings: () => settings, users: ({ variables }) => { expectAndFail(variables.role).toBeFalsy(); return communityUsers; }, viewer: () => viewer, sites: () => siteConnection, }, }), params.resolvers ), initLocalState: (localRecord, source, environment) => { if (params.initLocalState) { params.initLocalState(localRecord, source, environment); } }, }); const container = await waitForElement(() => within(testRenderer.root).getByTestID("community-container") ); return { testRenderer, container }; }; it("renders community", async () => { const { container } = await createTestRenderer(); expect(within(container).toJSON()).toMatchSnapshot(); }); it("renders empty community", async () => { const { container } = await createTestRenderer({ resolvers: { Query: { users: createQueryResolverStub<QueryToUsersResolver>( () => emptyCommunityUsers ), }, }, }); expect(within(container).toJSON()).toMatchSnapshot(); }); it("renders the invite button when clicked", async () => { const { container } = await createTestRenderer(); await act(async () => within(container).getByTestID("invite-users-button").props.onClick() ); expect(within(container).getByTestID("invite-users-modal")).toBeDefined(); }); it("renders with invite button when viewed with admin user", async () => { const admin = users.admins[0]; const { container } = await createTestRenderer({ resolvers: createResolversStub<GQLResolver>({ Query: { viewer: () => admin, }, }), }); expect(within(container).queryByTestID("invite-users")).toBeDefined(); }); it("renders without invite button when viewed with non-admin user", async () => { const moderator = users.moderators[0]; const { container } = await createTestRenderer({ resolvers: createResolversStub<GQLResolver>({ Query: { viewer: () => moderator, }, }), }); expect(within(container).queryByTestID("invite-users")).toBeNull(); }); it("renders without invite button when email disabled", async () => { const { container } = await createTestRenderer({ resolvers: createResolversStub<GQLResolver>({ Query: { settings: createQueryResolverStub<QueryToSettingsResolver>( () => disabledEmail ), }, }), }); expect(within(container).queryByTestID("invite-users")).toBeNull(); }); it("renders without invite button when admin target filter disabled", async () => { const { container } = await createTestRenderer({ resolvers: createResolversStub<GQLResolver>({ Query: { settings: createQueryResolverStub<QueryToSettingsResolver>( () => disabledLocalAuthAdminTargetFilter ), }, }), }); expect(within(container).queryByTestID("invite-users")).toBeNull(); }); it("renders without invite button when local auth disabled", async () => { const { container } = await createTestRenderer({ resolvers: createResolversStub<GQLResolver>({ Query: { settings: createQueryResolverStub<QueryToSettingsResolver>( () => disabledLocalAuth ), }, }), }); expect(within(container).queryByTestID("invite-users")).toBeNull(); }); it("renders without invite button when local auth registration disabled", async () => { const { container } = await createTestRenderer({ resolvers: createResolversStub<GQLResolver>({ Query: { settings: createQueryResolverStub<QueryToSettingsResolver>( () => disabledLocalRegistration ), }, }), }); expect(within(container).queryByTestID("invite-users")).toBeNull(); }); it("filter by role", async () => { const { container } = await createTestRenderer({ resolvers: createResolversStub<GQLResolver>({ Query: { users: ({ variables, callCount }) => { switch (callCount) { case 0: return communityUsers; default: expectAndFail(variables.role).toBe(GQLUSER_ROLE.COMMENTER); return emptyCommunityUsers; } }, }, }), }); const selectField = within(container).getByLabelText("Search by role"); const commentersOption = within(selectField).getByText("Commenters"); await act(async () => { selectField.props.onChange({ target: { value: commentersOption.props.value.toString() }, }); await waitForElement(() => within(container).getByText("We could not find anyone", { exact: false }) ); }); }); it("can't change viewer role", async () => { const { container } = await createTestRenderer(); const viewerRow = within(container).getByText(viewer.username!, { selector: "tr", }); expect(() => within(viewerRow).getByLabelText("Change role")).toThrow(); }); it("change user role", async () => { const user = users.commenters[0]; const resolvers = createResolversStub<GQLResolver>({ Mutation: { updateUserRole: ({ variables }) => { expectAndFail(variables).toMatchObject({ userID: user.id, role: GQLUSER_ROLE.STAFF, }); const userRecord = pureMerge<typeof user>(user, { role: variables.role, }); return { user: userRecord, }; }, }, }); const { container } = await createTestRenderer({ resolvers, }); const userRow = within(container).getByText(user.username!, { selector: "tr", }); act(() => { within(userRow).getByLabelText("Change role").props.onClick(); }); const popup = within(userRow).getByLabelText( "A dropdown to change the user role" ); act(() => { within(popup).getByText("Staff", { selector: "button" }).props.onClick(); }); expect(resolvers.Mutation!.updateUserRole!.called).toBe(true); }); it("change user role to Site Moderator and add sites to moderate", async () => { const user = users.commenters[0]; const resolvers = createResolversStub<GQLResolver>({ Mutation: { updateUserRole: ({ variables }) => { expectAndFail(variables).toMatchObject({ userID: user.id, role: GQLUSER_ROLE.MODERATOR, }); const userRecord = pureMerge<typeof user>(user, { role: variables.role, }); return { user: userRecord, }; }, updateUserModerationScopes: ({ variables }) => { expectAndFail(variables).toMatchObject({ moderationScopes: { siteIDs: ["site-1"], }, userID: user.id, }); const userRecord = pureMerge<typeof user>(user, { moderationScopes: { scoped: true, sites: [sites[0]], }, role: GQLUSER_ROLE.MODERATOR, }); return { user: userRecord, }; }, }, Query: { settings: () => settingsWithMultisite, sites: () => siteConnection, }, }); const { container } = await createTestRenderer({ resolvers, }); const userRow = within(container).getByText(user.username!, { selector: "tr", }); act(() => { within(userRow).getByLabelText("Change role").props.onClick(); }); const popup = within(userRow).getByLabelText( "A dropdown to change the user role" ); act(() => { within(popup) .getByText("Site Moderator", { selector: "button" }) .props.onClick(); }); const modal = within(container).getByTestID("site-moderator-modal"); // The submit button should be disabled until at least 1 site is selected expect( within(modal).getByTestID("site-moderator-modal-submitButton").props .disabled ).toBe(true); const siteSearchField = within(modal).getByTestID("site-search-textField"); act(() => siteSearchField.props.onChange({ target: { value: "Test" }, }) ); const siteSearchButton = within(modal).getByTestID("site-search-button"); act(() => { siteSearchButton.props.onClick({ preventDefault: noop }); }); // Add site to add site moderator permissions for await act(async () => { await waitForElement(() => within(modal).getByTestID("site-search-list")); within(modal).getByText("Test Site").props.onClick(); }); await act(async () => { within(modal).getByType("form").props.onSubmit(); }); expect(resolvers.Mutation!.updateUserRole!.called).toBe(true); expect(resolvers.Mutation!.updateUserModerationScopes!.called).toBe(true); }); it("can't change role as a moderator", async () => { const moderator = users.moderators[0]; const { container } = await createTestRenderer({ resolvers: createResolversStub<GQLResolver>({ Query: { viewer: () => moderator, }, }), }); expect(() => within(container).getByLabelText("Change role")).toThrow(); }); it("load more", async () => { const { container } = await createTestRenderer({ resolvers: createResolversStub<GQLResolver>({ Query: { users: ({ callCount }) => { switch (callCount) { case 0: return { edges: [ { node: viewer, cursor: viewer.createdAt, }, { node: users.commenters[0], cursor: users.commenters[0].createdAt, }, ], pageInfo: { endCursor: users.commenters[0].createdAt, hasNextPage: true, }, }; default: return { edges: [ { node: users.commenters[1], cursor: users.commenters[1].createdAt, }, ], pageInfo: { endCursor: users.commenters[1].createdAt, hasNextPage: false, }, }; } }, }, }), }); const loadMore = within(container).getByText("Load More"); await act(async () => { loadMore.props.onClick(); // Wait for load more to disappear. await waitUntilThrow(() => within(container).getByText("Load More")); }); // Make sure third user was added. within(container).getByText(users.commenters[1].username!); }); it("filter by search", async () => { const { container } = await createTestRenderer({ resolvers: createResolversStub<GQLResolver>({ Query: { users: ({ variables, callCount }) => { switch (callCount) { case 0: return communityUsers; default: expectAndFail(variables.query).toBe("search"); return emptyCommunityUsers; } }, }, }), }); const searchField = within(container).getByLabelText("Search by username", { exact: false, }); const form = within(searchField).getParentByType("form"); await act(async () => { searchField.props.onChange({ target: { value: "search" }, }); form.props.onSubmit(); await waitForElement(() => within(container).getByText("could not find anyone", { exact: false }) ); }); }); it("filter by status", async () => { const { container } = await createTestRenderer({ resolvers: createResolversStub<GQLResolver>({ Query: { users: ({ variables, callCount }) => { switch (callCount) { case 0: return communityUsers; default: expectAndFail(variables.status).toBe("BANNED"); return emptyCommunityUsers; } }, }, }), }); const statusField = within(container).getByLabelText( "Search by user status", { exact: false, } ); const bannedOption = within(statusField).getByText("Banned"); await act(async () => { statusField.props.onChange({ target: { value: bannedOption.props.value.toString() }, }); await waitForElement(() => within(container).getByText("We could not find anyone", { exact: false }) ); }); }); it("can't change staff, moderator and admin status", async () => { const { container } = await createTestRenderer(); ["Admin", "Moderator", "Staff"].forEach((role) => { const viewerRow = within(container).getByText(role, { selector: "tr", }); expect(() => within(viewerRow).getByLabelText("Change user status") ).toThrow(); }); }); it("suspend user", async () => { const user = users.commenters[0]; const resolvers = createResolversStub<GQLResolver>({ Mutation: { suspendUser: ({ variables }) => { expectAndFail(variables).toMatchObject({ userID: user.id, }); const userRecord = pureMerge<typeof user>(user, { status: { current: user.status.current.concat(GQLUSER_STATUS.SUSPENDED), suspension: { active: true }, }, }); return { user: userRecord, }; }, }, }); const { container, testRenderer } = await createTestRenderer({ resolvers, }); const userRow = within(container).getByText(user.username!, { selector: "tr", }); act(() => { within(userRow).getByLabelText("Change user status").props.onClick(); }); const popup = within(userRow).getByLabelText( "A dropdown to change the user status" ); act(() => { within(popup).getByText("Suspend", { selector: "button" }).props.onClick(); }); const modal = within(testRenderer.root).getByLabelText("Suspend", { exact: false, }); act(() => { within(modal).getByType("form").props.onSubmit(); }); within(userRow).getByText("Suspended"); expect(resolvers.Mutation!.suspendUser!.called).toBe(true); }); it("remove user suspension", async () => { const user = users.suspendedCommenter; const resolvers = createResolversStub<GQLResolver>({ Mutation: { removeUserSuspension: ({ variables }) => { expectAndFail(variables).toMatchObject({ userID: user.id, }); const userRecord = pureMerge<typeof user>(user, { status: { current: [GQLUSER_STATUS.ACTIVE], suspension: { active: false }, }, }); return { user: userRecord, }; }, }, Query: { users: () => ({ edges: [ { node: user, cursor: user.createdAt, }, ], pageInfo: { endCursor: null, hasNextPage: false }, }), }, }); const { container } = await createTestRenderer({ resolvers, }); const userRow = within(container).getByText(user.username!, { selector: "tr", }); act(() => { within(userRow).getByLabelText("Change user status").props.onClick(); }); const popup = within(userRow).getByLabelText( "A dropdown to change the user status" ); act(() => { within(popup) .getByText("Remove suspension", { selector: "button" }) .props.onClick(); }); expect(resolvers.Mutation!.removeUserSuspension!.called).toBe(true); await waitForElement(() => within(userRow).getByText("Active")); }); it("suspend user with custom timeout", async () => { const user = users.commenters[0]; const resolvers = createResolversStub<GQLResolver>({ Mutation: { suspendUser: ({ variables }) => { expectAndFail(variables).toMatchObject({ userID: user.id, timeout: 604800, }); const userRecord = pureMerge<typeof user>(user, { status: { current: user.status.current.concat(GQLUSER_STATUS.SUSPENDED), suspension: { active: true }, }, }); return { user: userRecord, }; }, }, }); const { container, testRenderer } = await createTestRenderer({ resolvers, }); const userRow = within(container).getByText(user.username!, { selector: "tr", }); act(() => { within(userRow).getByLabelText("Change user status").props.onClick(); }); const popup = within(userRow).getByLabelText( "A dropdown to change the user status" ); act(() => { within(popup).getByText("Suspend", { selector: "button" }).props.onClick(); }); const modal = within(testRenderer.root).getByLabelText("Suspend", { exact: false, }); const changedDuration = within(modal).getByID("duration-604800"); act(() => { changedDuration.props.onChange(changedDuration.props.value.toString()); }); act(() => { within(modal).getByType("form").props.onSubmit(); }); within(userRow).getByText("Suspended"); expect(resolvers.Mutation!.suspendUser!.called).toBe(true); }); it("suspend user with custom message", async () => { const user = users.commenters[0]; const resolvers = createResolversStub<GQLResolver>({ Mutation: { suspendUser: ({ variables }) => { expectAndFail(variables).toMatchObject({ userID: user.id, message: "YOU WERE SUSPENDED FOR BEHAVING BADLY", }); const userRecord = pureMerge<typeof user>(user, { status: { current: user.status.current.concat(GQLUSER_STATUS.SUSPENDED), suspension: { active: true }, }, }); return { user: userRecord, }; }, }, }); const { container, testRenderer } = await createTestRenderer({ resolvers, }); const userRow = within(container).getByText(user.username!, { selector: "tr", }); act(() => { within(userRow).getByLabelText("Change user status").props.onClick(); }); const popup = within(userRow).getByLabelText( "A dropdown to change the user status" ); act(() => { within(popup).getByText("Suspend", { selector: "button" }).props.onClick(); }); const modal = within(testRenderer.root).getByLabelText("Suspend", { exact: false, }); const toggleEdit = within(modal).getByID("suspendModal-editMessage"); act(() => { toggleEdit.props.onChange(true); }); act(() => { within(modal) .getByID("suspendModal-message") .props.onChange("YOU WERE SUSPENDED FOR BEHAVING BADLY"); }); act(() => { within(modal).getByType("form").props.onSubmit(); }); within(userRow).getByText("Suspended"); expect(resolvers.Mutation!.suspendUser!.called).toBe(true); }); it("bans user from all sites", async () => { const user = users.commenters[0]; const resolvers = createResolversStub<GQLResolver>({ Mutation: { banUser: ({ variables }) => { expectAndFail(variables).toMatchObject({ userID: user.id, }); const userRecord = pureMerge<typeof user>(user, { status: { current: user.status.current.concat(GQLUSER_STATUS.BANNED), ban: { active: true }, }, }); return { user: userRecord, }; }, }, Query: { settings: () => settingsWithMultisite, sites: () => siteConnection, }, }); const { container, testRenderer } = await createTestRenderer({ resolvers, }); const userRow = within(container).getByText(user.username!, { selector: "tr", }); act(() => { within(userRow).getByLabelText("Change user status").props.onClick(); }); const dropdown = within(userRow).getByLabelText( "A dropdown to change the user status" ); act(() => { within(dropdown) .getByText("Manage ban", { selector: "button", exact: false }) .props.onClick(); }); const modal = within(testRenderer.root).getByLabelText( "Are you sure you want to ban", { exact: false, } ); act(() => { within(modal).getByLabelText("All sites").props.onChange(); }); act(() => { within(modal).getByType("form").props.onSubmit(); }); within(userRow).getByText("Banned", { exact: false }); expect(resolvers.Mutation!.banUser!.called).toBe(true); }); it("ban user with custom message", async () => { const user = users.commenters[0]; const resolvers = createResolversStub<GQLResolver>({ Mutation: { banUser: ({ variables }) => { expectAndFail(variables).toMatchObject({ userID: user.id, message: "YOU WERE BANNED FOR BREAKING THE RULES", }); const userRecord = pureMerge<typeof user>(user, { status: { current: user.status.current.concat(GQLUSER_STATUS.BANNED), ban: { active: true }, }, }); return { user: userRecord, }; }, }, Query: { settings: () => settingsWithMultisite, sites: () => siteConnection, }, }); const { container, testRenderer } = await createTestRenderer({ resolvers, }); const userRow = within(container).getByText(user.username!, { selector: "tr", }); act(() => { within(userRow).getByLabelText("Change user status").props.onClick(); }); const dropdown = within(userRow).getByLabelText( "A dropdown to change the user status" ); act(() => { within(dropdown) .getByText("Manage ban", { selector: "button", exact: false }) .props.onClick(); }); const modal = within(testRenderer.root).getByLabelText( "Are you sure you want to ban", { exact: false, } ); const toggleMessage = within(modal).getByID("banModal-showMessage"); act(() => { toggleMessage.props.onChange({ target: { checked: true, }, }); }); act(() => { within(modal) .getByID("banModal-message") .props.onChange({ target: { value: "YOU WERE BANNED FOR BREAKING THE RULES", }, }); }); act(() => { within(modal).getByType("form").props.onSubmit(); }); within(userRow).getByText("Banned", { exact: false }); expect(resolvers.Mutation!.banUser!.called).toBe(true); }); it("remove user ban from all sites", async () => { const user = users.bannedCommenter; const resolvers = createResolversStub<GQLResolver>({ Mutation: { removeUserBan: ({ variables }) => { expectAndFail(variables).toMatchObject({ userID: user.id, }); const userRecord = pureMerge<typeof user>(user, { status: { current: user.status.current.filter( (s) => s !== GQLUSER_STATUS.BANNED ), ban: { active: false }, }, }); return { user: userRecord, }; }, }, Query: { settings: () => settingsWithMultisite, users: () => ({ edges: [ { node: user, cursor: user.createdAt, }, ], pageInfo: { endCursor: null, hasNextPage: false }, }), }, }); const { container } = await createTestRenderer({ resolvers, }); const userRow = within(container).getByText(user.username!, { selector: "tr", }); act(() => { within(userRow).getByLabelText("Change user status").props.onClick(); }); const dropdown = within(userRow).getByLabelText( "A dropdown to change the user status" ); act(() => { within(dropdown) .getByText("Manage Ban", { selector: "button", exact: false }) .props.onClick(); }); const modal = within(userRow).getByLabelText( "Are you sure you want to unban", { exact: false } ); act(() => { within(modal).getByLabelText("No sites", { exact: false }).props.onChange(); }); act(() => { within(modal).getByType("form").props.onSubmit(); }); within(userRow).getByText("Active"); expect(resolvers.Mutation!.removeUserBan!.called).toBe(true); }); it("send user a moderation message", async () => { const user = users.commenters[0]; const resolvers = createResolversStub<GQLResolver>({ Mutation: { sendModMessage: ({ variables }) => { expectAndFail(variables).toMatchObject({ userID: user.id, message: "Just wanted to send a friendly reminder about our comment guidelines.", }); const userRecord = pureMerge<typeof user>(user, { status: { modMessage: { active: true }, }, }); return { user: userRecord, }; }, }, }); const { container, testRenderer } = await createTestRenderer({ resolvers, }); const userRow = within(container).getByText(user.username!, { selector: "tr", }); act(() => { within(userRow).getByLabelText("Change user status").props.onClick(); }); const popup = within(userRow).getByLabelText( "A dropdown to change the user status" ); act(() => { within(popup).getByText("Message", { selector: "button" }).props.onClick(); }); const modal = within(testRenderer.root).getByLabelText("Message", { exact: false, }); act(() => { within(modal) .getByTestID("modMessageModal-message") .props.onChange( "Just wanted to send a friendly reminder about our comment guidelines." ); }); act(() => { within(modal).getByType("form").props.onSubmit(); }); // Sending the user a moderation message should not change their status within(userRow).getByText("Active"); expect(resolvers.Mutation!.sendModMessage!.called).toBe(true); }); it("invites user", async () => { const resolvers = createResolversStub<GQLResolver>({ Mutation: { inviteUsers: ({ variables }) => ({ invites: variables.emails.map((email, idx) => ({ id: uuid(), email, })), }), }, }); const { container } = await createTestRenderer({ resolvers }); // Find the invite button. const inviteButton = within(container).getByTestID("invite-users-button"); // Let's click the button. act(() => inviteButton.props.onClick()); // Find the form. const modal = within(container).getByTestID("invite-users-modal"); const form = within(modal).getByType("form"); // Find the first email field. const field = within(form).getByTestID("invite-users-email.0"); // Submit the form. await act(async () => { field.props.onChange("test@email.com"); return form.props.onSubmit(); }); await wait(() => { expect(resolvers.Mutation!.inviteUsers!.called).toBe(true); }); }); it("ban user across specific sites", async () => { const user = users.commenters[0]; const resolvers = createResolversStub<GQLResolver>({ Query: { settings: () => settingsWithMultisite, site: ({ variables, callCount }) => { switch (callCount) { case 0: expectAndFail(variables.id).toBe("site-1"); return sites[0]; case 1: expectAndFail(variables.id).toBe("site-2"); return sites[1]; default: return siteConnection; } }, }, Mutation: { updateUserBan: ({ variables }) => { expectAndFail(variables).toMatchObject({ userID: user.id, }); const userRecord = pureMerge<typeof user>(user, { status: { ban: { sites: [{ id: sites[1].id }] }, }, }); return { user: userRecord, }; }, }, }); const { container, testRenderer } = await createTestRenderer({ resolvers, }); const userRow = within(container).getByText(user.username!, { selector: "tr", }); act(() => { within(userRow).getByLabelText("Change user status").props.onClick(); }); const popup = within(userRow).getByLabelText( "A dropdown to change the user status" ); act(() => { within(popup) .getByText("Manage Ban", { selector: "button", exact: false }) .props.onClick(); }); const modal = within(testRenderer.root).getByLabelText( "Are you sure you want to ban", { exact: false, } ); act(() => { within(modal).getByLabelText("Specific sites").props.onChange(); }); const siteSearchField = within(modal).getByTestID("site-search-textField"); act(() => siteSearchField.props.onChange({ target: { value: "Test" }, }) ); const siteSearchButton = within(modal).getByTestID("site-search-button"); act(() => { siteSearchButton.props.onClick({ preventDefault: noop }); }); // Add site to ban on await act(async () => { await waitForElement(() => within(modal).getByTestID("site-search-list")); within(modal).getByText("Test Site").props.onClick(); }); const testSiteCheckbox = within(modal).getAllByTestID( "user-status-selected-site" ); expect(testSiteCheckbox).toHaveLength(1); expect(testSiteCheckbox[0].props.checked).toEqual(true); // Add another site to ban on act(() => siteSearchField.props.onChange({ target: { value: "Another" }, }) ); act(() => { siteSearchButton.props.onClick({ preventDefault: noop }); }); await act(async () => { await waitForElement(() => within(modal).getByTestID("site-search-list")); within(modal).getByText("Second Site").props.onClick(); }); expect( within(modal).getAllByTestID("user-status-selected-site") ).toHaveLength(2); // Remove a site to ban on act(() => { within(modal) .getAllByTestID("user-status-selected-site")[0] .props.onChange(); }); // Submit ban and see that user is correctly banned across selected site await act(async () => { within(modal).getByType("form").props.onSubmit(); await waitForElement(() => within(userRow).getByText("Banned (1)")); }); expect(resolvers.Mutation!.updateUserBan!.called).toBe(true); });
the_stack
* Unit tests for indexed_db.ts. */ import * as tf from '../index'; import {BROWSER_ENVS, describeWithFlags, runWithLock} from '../jasmine_util'; import {expectArrayBuffersEqual} from '../test_util'; import {browserIndexedDB, BrowserIndexedDB, BrowserIndexedDBManager, deleteDatabase, indexedDBRouter} from './indexed_db'; describeWithFlags('IndexedDB', BROWSER_ENVS, () => { // Test data. const modelTopology1: {} = { 'class_name': 'Sequential', 'keras_version': '2.1.4', 'config': [{ 'class_name': 'Dense', 'config': { 'kernel_initializer': { 'class_name': 'VarianceScaling', 'config': { 'distribution': 'uniform', 'scale': 1.0, 'seed': null, 'mode': 'fan_avg' } }, 'name': 'dense', 'kernel_constraint': null, 'bias_regularizer': null, 'bias_constraint': null, 'dtype': 'float32', 'activation': 'linear', 'trainable': true, 'kernel_regularizer': null, 'bias_initializer': {'class_name': 'Zeros', 'config': {}}, 'units': 1, 'batch_input_shape': [null, 3], 'use_bias': true, 'activity_regularizer': null } }], 'backend': 'tensorflow' }; const weightSpecs1: tf.io.WeightsManifestEntry[] = [ { name: 'dense/kernel', shape: [3, 1], dtype: 'float32', }, { name: 'dense/bias', shape: [1], dtype: 'float32', } ]; const weightData1 = new ArrayBuffer(16); const artifacts1: tf.io.ModelArtifacts = { modelTopology: modelTopology1, weightSpecs: weightSpecs1, weightData: weightData1, format: 'layers-model', generatedBy: 'TensorFlow.js v0.0.0', convertedBy: null, modelInitializer: {} }; const weightSpecs2: tf.io.WeightsManifestEntry[] = [ { name: 'dense/new_kernel', shape: [5, 1], dtype: 'float32', }, { name: 'dense/new_bias', shape: [1], dtype: 'float32', } ]; beforeEach(deleteDatabase); afterEach(deleteDatabase); it('Save-load round trip', runWithLock(async () => { const testStartDate = new Date(); const handler = tf.io.getSaveHandlers('indexeddb://FooModel')[0]; const saveResult = await handler.save(artifacts1); expect(saveResult.modelArtifactsInfo.dateSaved.getTime()) .toBeGreaterThanOrEqual(testStartDate.getTime()); // Note: The following two assertions work only because there is no // non-ASCII characters in `modelTopology1` and `weightSpecs1`. expect(saveResult.modelArtifactsInfo.modelTopologyBytes) .toEqual(JSON.stringify(modelTopology1).length); expect(saveResult.modelArtifactsInfo.weightSpecsBytes) .toEqual(JSON.stringify(weightSpecs1).length); expect(saveResult.modelArtifactsInfo.weightDataBytes) .toEqual(weightData1.byteLength); const loadedArtifacts = await handler.load(); expect(loadedArtifacts.modelTopology).toEqual(modelTopology1); expect(loadedArtifacts.weightSpecs).toEqual(weightSpecs1); expect(loadedArtifacts.format).toEqual('layers-model'); expect(loadedArtifacts.generatedBy).toEqual('TensorFlow.js v0.0.0'); expect(loadedArtifacts.convertedBy).toEqual(null); expect(loadedArtifacts.modelInitializer).toEqual({}); expectArrayBuffersEqual(loadedArtifacts.weightData, weightData1); })); it('Save two models and load one', runWithLock(async () => { const weightData2 = new ArrayBuffer(24); const artifacts2: tf.io.ModelArtifacts = { modelTopology: modelTopology1, weightSpecs: weightSpecs2, weightData: weightData2, }; const handler1 = tf.io.getSaveHandlers('indexeddb://Model/1')[0]; const saveResult1 = await handler1.save(artifacts1); // Note: The following two assertions work only because there is no // non-ASCII characters in `modelTopology1` and `weightSpecs1`. expect(saveResult1.modelArtifactsInfo.modelTopologyBytes) .toEqual(JSON.stringify(modelTopology1).length); expect(saveResult1.modelArtifactsInfo.weightSpecsBytes) .toEqual(JSON.stringify(weightSpecs1).length); expect(saveResult1.modelArtifactsInfo.weightDataBytes) .toEqual(weightData1.byteLength); const handler2 = tf.io.getSaveHandlers('indexeddb://Model/2')[0]; const saveResult2 = await handler2.save(artifacts2); expect(saveResult2.modelArtifactsInfo.dateSaved.getTime()) .toBeGreaterThanOrEqual( saveResult1.modelArtifactsInfo.dateSaved.getTime()); // Note: The following two assertions work only because there is // no non-ASCII characters in `modelTopology1` and // `weightSpecs1`. expect(saveResult2.modelArtifactsInfo.modelTopologyBytes) .toEqual(JSON.stringify(modelTopology1).length); expect(saveResult2.modelArtifactsInfo.weightSpecsBytes) .toEqual(JSON.stringify(weightSpecs2).length); expect(saveResult2.modelArtifactsInfo.weightDataBytes) .toEqual(weightData2.byteLength); const loadedArtifacts = await handler1.load(); expect(loadedArtifacts.modelTopology).toEqual(modelTopology1); expect(loadedArtifacts.weightSpecs).toEqual(weightSpecs1); expectArrayBuffersEqual(loadedArtifacts.weightData, weightData1); })); it('Loading nonexistent model fails', runWithLock(async () => { const handler = tf.io.getSaveHandlers('indexeddb://NonexistentModel')[0]; try { await handler.load(); fail('Loading nonexistent model from IndexedDB succeeded unexpectly'); } catch (err) { expect(err.message) .toEqual( 'Cannot find model with path \'NonexistentModel\' in IndexedDB.'); } })); it('Null, undefined or empty modelPath throws Error', () => { expect(() => browserIndexedDB(null)) .toThrowError( /IndexedDB, modelPath must not be null, undefined or empty/); expect(() => browserIndexedDB(undefined)) .toThrowError( /IndexedDB, modelPath must not be null, undefined or empty/); expect(() => browserIndexedDB('')) .toThrowError( /IndexedDB, modelPath must not be null, undefined or empty./); }); it('router', () => { expect(indexedDBRouter('indexeddb://bar') instanceof BrowserIndexedDB) .toEqual(true); expect(indexedDBRouter('localstorage://bar')).toBeNull(); expect(indexedDBRouter('qux')).toBeNull(); }); it('Manager: List models: 0 result', runWithLock(async () => { // Before any model is saved, listModels should return empty result. const models = await new BrowserIndexedDBManager().listModels(); expect(models).toEqual({}); })); it('Manager: List models: 1 result', runWithLock(async () => { const handler = tf.io.getSaveHandlers('indexeddb://baz/QuxModel')[0]; const saveResult = await handler.save(artifacts1); // After successful saving, there should be one model. const models = await new BrowserIndexedDBManager().listModels(); expect(Object.keys(models).length).toEqual(1); expect(models['baz/QuxModel'].modelTopologyType) .toEqual(saveResult.modelArtifactsInfo.modelTopologyType); expect(models['baz/QuxModel'].modelTopologyBytes) .toEqual(saveResult.modelArtifactsInfo.modelTopologyBytes); expect(models['baz/QuxModel'].weightSpecsBytes) .toEqual(saveResult.modelArtifactsInfo.weightSpecsBytes); expect(models['baz/QuxModel'].weightDataBytes) .toEqual(saveResult.modelArtifactsInfo.weightDataBytes); })); it('Manager: List models: 2 results', runWithLock(async () => { // First, save a model. const handler1 = tf.io.getSaveHandlers('indexeddb://QuxModel')[0]; const saveResult1 = await handler1.save(artifacts1); // Then, save the model under another path. const handler2 = tf.io.getSaveHandlers('indexeddb://repeat/QuxModel')[0]; const saveResult2 = await handler2.save(artifacts1); // After successful saving, there should be two models. const models = await new BrowserIndexedDBManager().listModels(); expect(Object.keys(models).length).toEqual(2); expect(models['QuxModel'].modelTopologyType) .toEqual(saveResult1.modelArtifactsInfo.modelTopologyType); expect(models['QuxModel'].modelTopologyBytes) .toEqual(saveResult1.modelArtifactsInfo.modelTopologyBytes); expect(models['QuxModel'].weightSpecsBytes) .toEqual(saveResult1.modelArtifactsInfo.weightSpecsBytes); expect(models['QuxModel'].weightDataBytes) .toEqual(saveResult1.modelArtifactsInfo.weightDataBytes); expect(models['repeat/QuxModel'].modelTopologyType) .toEqual(saveResult2.modelArtifactsInfo.modelTopologyType); expect(models['repeat/QuxModel'].modelTopologyBytes) .toEqual(saveResult2.modelArtifactsInfo.modelTopologyBytes); expect(models['repeat/QuxModel'].weightSpecsBytes) .toEqual(saveResult2.modelArtifactsInfo.weightSpecsBytes); expect(models['repeat/QuxModel'].weightDataBytes) .toEqual(saveResult2.modelArtifactsInfo.weightDataBytes); })); it('Manager: Successful removeModel', runWithLock(async () => { // First, save a model. const handler1 = tf.io.getSaveHandlers('indexeddb://QuxModel')[0]; await handler1.save(artifacts1); // Then, save the model under another path. const handler2 = tf.io.getSaveHandlers('indexeddb://repeat/QuxModel')[0]; await handler2.save(artifacts1); // After successful saving, delete the first save, and then // `listModel` should give only one result. const manager = new BrowserIndexedDBManager(); await manager.removeModel('QuxModel'); const models = await manager.listModels(); expect(Object.keys(models)).toEqual(['repeat/QuxModel']); })); it('Manager: Successful removeModel with URL scheme', runWithLock(async () => { // First, save a model. const handler1 = tf.io.getSaveHandlers('indexeddb://QuxModel')[0]; await handler1.save(artifacts1); // Then, save the model under another path. const handler2 = tf.io.getSaveHandlers('indexeddb://repeat/QuxModel')[0]; await handler2.save(artifacts1); // After successful saving, delete the first save, and then // `listModel` should give only one result. const manager = new BrowserIndexedDBManager(); // Delete a model specified with a path that includes the // indexeddb:// scheme prefix should work. manager.removeModel('indexeddb://QuxModel'); const models = await manager.listModels(); expect(Object.keys(models)).toEqual(['repeat/QuxModel']); })); it('Manager: Failed removeModel', runWithLock(async () => { try { // Attempt to delete a nonexistent model is expected to fail. await new BrowserIndexedDBManager().removeModel('nonexistent'); fail('Deleting nonexistent model succeeded unexpectedly.'); } catch (err) { expect(err.message) .toEqual('Cannot find model with path \'nonexistent\' in IndexedDB.'); } })); });
the_stack
import * as path from 'path' import * as cp from 'child_process' import * as fs from 'fs-extra' import packager, { OsxNotarizeOptions, OsxSignOptions, Options, } from 'electron-packager' import frontMatter from 'front-matter' import { externals } from '../app/webpack.common' interface IChooseALicense { readonly title: string readonly nickname?: string readonly featured?: boolean readonly hidden?: boolean } export interface ILicense { readonly name: string readonly featured: boolean readonly body: string readonly hidden: boolean } import { getBundleID, getProductName } from '../app/package-info' import { getChannel, getDistRoot, getExecutableName, isPublishable, getIconFileName, } from './dist-info' import { isCircleCI, isGitHubActions } from './build-platforms' import { updateLicenseDump } from './licenses/update-license-dump' import { verifyInjectedSassVariables } from './validate-sass/validate-all' const projectRoot = path.join(__dirname, '..') const entitlementsPath = `${projectRoot}/script/entitlement.plist` const extendInfoPath = `${projectRoot}/script/info.plist` const outRoot = path.join(projectRoot, 'out') const isPublishableBuild = isPublishable() const isDevelopmentBuild = getChannel() === 'development' console.log(`Building for ${getChannel()}…`) console.log('Removing old distribution…') fs.removeSync(getDistRoot()) console.log('Copying dependencies…') copyDependencies() console.log('Packaging emoji…') copyEmoji() console.log('Copying static resources…') copyStaticResources() console.log('Parsing license metadata…') generateLicenseMetadata(outRoot) moveAnalysisFiles() if (isGitHubActions() && process.platform === 'darwin' && isPublishableBuild) { console.log('Setting up keychain…') cp.execSync(path.join(__dirname, 'setup-macos-keychain')) } verifyInjectedSassVariables(outRoot) .catch(err => { console.error( 'Error verifying the Sass variables in the rendered app. This is fatal for a published build.' ) if (!isDevelopmentBuild) { process.exit(1) } }) .then(() => { console.log('Updating our licenses dump…') return updateLicenseDump(projectRoot, outRoot).catch(err => { console.error( 'Error updating the license dump. This is fatal for a published build.' ) console.error(err) if (!isDevelopmentBuild) { process.exit(1) } }) }) .then(() => { console.log('Packaging…') return packageApp() }) .catch(err => { console.error(err) process.exit(1) }) .then(appPaths => { console.log(`Built to ${appPaths}`) }) /** * The additional packager options not included in the existing typing. * * See https://github.com/desktop/desktop/issues/2429 for some history on this. */ interface IPackageAdditionalOptions { readonly protocols: ReadonlyArray<{ readonly name: string readonly schemes: ReadonlyArray<string> }> readonly osxSign: OsxSignOptions & { readonly hardenedRuntime?: boolean } } function packageApp() { // get notarization deets, unless we're not going to publish this const notarizationCredentials = isPublishableBuild ? getNotarizationCredentials() : undefined if ( isPublishableBuild && (isCircleCI() || isGitHubActions()) && process.platform === 'darwin' && notarizationCredentials === undefined ) { // we can't publish a mac build without these throw new Error( 'Unable to retreive appleId and/or appleIdPassword to notarize macOS build' ) } const options: Options & IPackageAdditionalOptions = { name: getExecutableName(), platform: 'darwin', arch: 'x64', asar: false, // TODO: Probably wanna enable this down the road. out: getDistRoot(), icon: path.join(projectRoot, 'app', 'static', 'logos', getIconFileName()), dir: outRoot, overwrite: true, tmpdir: false, derefSymlinks: false, prune: false, // We'll prune them ourselves below. ignore: [ new RegExp('/node_modules/electron($|/)'), new RegExp('/node_modules/electron-packager($|/)'), new RegExp('/\\.git($|/)'), new RegExp('/node_modules/\\.bin($|/)'), ], appCopyright: 'Copyright © 2019 Mathieu Dutour.', // macOS appBundleId: getBundleID(), appCategoryType: 'public.app-category.developer-tools', darwinDarkModeSupport: true, osxSign: { entitlements: entitlementsPath, 'entitlements-inherit': entitlementsPath, 'gatekeeper-assess': false, type: isPublishableBuild ? 'distribution' : 'development', }, osxNotarize: notarizationCredentials, protocols: [ { name: getBundleID(), schemes: [ !isDevelopmentBuild ? 'x-kactus-auth' : 'x-kactus-dev-auth', 'x-kactus-client', 'x-github-client', 'github-mac', 'kactus', ], }, ], extendInfo: extendInfoPath, } return packager(options) } function removeAndCopy(source: string, destination: string) { fs.removeSync(destination) fs.copySync(source, destination) } function copyEmoji() { const emojiImages = path.join(projectRoot, 'gemoji', 'images', 'emoji') const emojiImagesDestination = path.join(outRoot, 'emoji') removeAndCopy(emojiImages, emojiImagesDestination) const emojiJSON = path.join(projectRoot, 'gemoji', 'db', 'emoji.json') const emojiJSONDestination = path.join(outRoot, 'emoji.json') removeAndCopy(emojiJSON, emojiJSONDestination) } function copyStaticResources() { const dirName = process.platform const platformSpecific = path.join(projectRoot, 'app', 'static', dirName) const common = path.join(projectRoot, 'app', 'static', 'common') const destination = path.join(outRoot, 'static') fs.removeSync(destination) if (fs.existsSync(platformSpecific)) { fs.copySync(platformSpecific, destination) } fs.copySync(common, destination, { overwrite: false }) } function moveAnalysisFiles() { const rendererReport = 'renderer.report.html' const analysisSource = path.join(outRoot, rendererReport) if (fs.existsSync(analysisSource)) { const distRoot = getDistRoot() const destination = path.join(distRoot, rendererReport) fs.mkdirpSync(distRoot) // there's no moveSync API here, so let's do it the old fashioned way // // unlinkSync below ensures that the analysis file isn't bundled into // the app by accident fs.copySync(analysisSource, destination, { overwrite: true }) fs.unlinkSync(analysisSource) } } function copyDependencies() { const originalPackage: Package = require(path.join( projectRoot, 'app', 'package.json' )) const oldDependencies = originalPackage.dependencies const newDependencies: PackageLookup = {} for (const name of Object.keys(oldDependencies)) { const spec = oldDependencies[name] if (externals.indexOf(name) !== -1) { newDependencies[name] = spec } } const oldDevDependencies = originalPackage.devDependencies const newDevDependencies: PackageLookup = {} if (isDevelopmentBuild) { for (const name of Object.keys(oldDevDependencies)) { const spec = oldDevDependencies[name] if (externals.indexOf(name) !== -1) { newDevDependencies[name] = spec } } } // The product name changes depending on whether it's a prod build or dev // build, so that we can have them running side by side. const updatedPackage = Object.assign({}, originalPackage, { productName: getProductName(), dependencies: newDependencies, devDependencies: newDevDependencies, }) if (!isDevelopmentBuild) { delete updatedPackage.devDependencies } fs.writeFileSync( path.join(outRoot, 'package.json'), JSON.stringify(updatedPackage) ) fs.removeSync(path.resolve(outRoot, 'node_modules')) if ( Object.keys(newDependencies).length || Object.keys(newDevDependencies).length ) { console.log(' Installing dependencies via npm…') cp.execSync('npm install', { cwd: outRoot, env: process.env }) } console.log(' Copying desktop-trampoline…') const desktopTrampolineDir = path.resolve(outRoot, 'desktop-trampoline') const desktopTrampolineFile = process.platform === 'win32' ? 'desktop-trampoline.exe' : 'desktop-trampoline' fs.removeSync(desktopTrampolineDir) fs.mkdirSync(desktopTrampolineDir) fs.copySync( path.resolve( projectRoot, 'app/node_modules/desktop-trampoline/build/Release', desktopTrampolineFile ), path.resolve(desktopTrampolineDir, desktopTrampolineFile) ) console.log(' Copying git environment…') const gitDir = path.resolve(outRoot, 'git') fs.removeSync(gitDir) fs.mkdirpSync(gitDir) fs.copySync(path.resolve(projectRoot, 'app/node_modules/dugite/git'), gitDir) console.log(' Copying app-path binary…') const appPathMain = path.resolve(outRoot, 'main') fs.removeSync(appPathMain) fs.copySync( path.resolve(projectRoot, 'app/node_modules/app-path/main'), appPathMain ) } function generateLicenseMetadata(outRoot: string) { const chooseALicense = path.join(outRoot, 'static', 'choosealicense.com') const licensesDir = path.join(chooseALicense, '_licenses') const files = fs.readdirSync(licensesDir) const licenses = new Array<ILicense>() for (const file of files) { const fullPath = path.join(licensesDir, file) const contents = fs.readFileSync(fullPath, 'utf8') const result = frontMatter<IChooseALicense>(contents) const licenseText = result.body.trim() // ensure that any license file created in the app does not trigger the // "no newline at end of file" warning when viewing diffs const licenseTextWithNewLine = `${licenseText}\n` const license: ILicense = { name: result.attributes.nickname || result.attributes.title, featured: result.attributes.featured || false, hidden: result.attributes.hidden === undefined || result.attributes.hidden, body: licenseTextWithNewLine, } if (!license.hidden) { licenses.push(license) } } const licensePayload = path.join(outRoot, 'static', 'available-licenses.json') const text = JSON.stringify(licenses) fs.writeFileSync(licensePayload, text, 'utf8') // embed the license alongside the generated license payload const chooseALicenseLicense = path.join(chooseALicense, 'LICENSE.md') const licenseDestination = path.join( outRoot, 'static', 'LICENSE.choosealicense.md' ) const licenseText = fs.readFileSync(chooseALicenseLicense, 'utf8') const licenseWithHeader = `Kactus uses licensing information provided by choosealicense.com. The bundle in available-licenses.json has been generated from a source list provided at https://github.com/github/choosealicense.com, which is made available under the below license: ------------ ${licenseText}` fs.writeFileSync(licenseDestination, licenseWithHeader, 'utf8') // sweep up the choosealicense directory as the important bits have been bundled in the app fs.removeSync(chooseALicense) } function getNotarizationCredentials(): OsxNotarizeOptions | undefined { const appleId = process.env.APPLE_ID const appleIdPassword = process.env.APPLE_ID_PASSWORD if (appleId === undefined || appleIdPassword === undefined) { return undefined } return { ascProvider: process.env.APPLE_TEAM, appleId, appleIdPassword, } }
the_stack
import * as xlsx from "xlsx"; import { defaultValueTransFuncMap } from "./default-value-func-map"; import { Logger } from "./loger"; import { forEachHorizontalSheet, forEachVerticalSheet, isCSV, isEmptyCell, readTableData, readTableFile } from "./table-utils"; declare global { interface ITableParserConfig { /**自定义值转换方法字典 */ customValueTransFuncMap?: ValueTransFuncMap; } interface ITableConvertConfig { /**解析配置 */ parserConfig?: ITableParserConfig; } interface ITableField { /**配置表中注释值 */ text: string; /**配置表中类型值 */ originType: string; /**配置表中字段名值 */ originFieldName: string; /**解析后的类型值 */ type?: string; /**解析后的字段名值 */ fieldName?: string; /**对象的子字段名 */ subFieldName?: string; /**多列对象 */ isMutiColObj?: boolean; } interface ITableFirstCellValue { tableNameInSheet: string; tableType: TableType; } interface ITableDefine { /**配置表名 */ tableName: string; /**配置表类型 默认两种: vertical 和 horizontal*/ tableType: string; /**遍历开始行 */ startRow: number; /**遍历开始列 */ startCol: string; /**垂直表字段定义 */ verticalFieldDefine: IVerticalFieldDefine; /**横向表字段定义 */ horizontalFieldDefine: IHorizontalFieldDefine; } interface IVerticalFieldDefine { /**类型行 */ typeCol: string; /**字段名行 */ fieldCol: string; /**注释行 */ textCol: string; } interface IHorizontalFieldDefine { /**类型行 */ typeRow: number; /**字段名行 */ fieldRow: number; /**注释行 */ textRow: number; } /** * 字段字典 * key是列originFieldName * value是字段对象 */ type TableFieldMap = { [key: string]: ITableField }; /** * 表格的一行或者一列 * key为字段名值,value为表格的一格 */ type TableRowOrCol = { [key: string]: ITableCell }; /** * 表格的一格 */ interface ITableCell { /**字段对象 */ field: ITableField; /**值 */ value: any; } /** * 表格行或列的字典 * key为行索引,value为表格的一行 */ type TableRowOrColMap = { [key: string]: TableRowOrCol }; /** * 表格行或列值数组 * key主键,value是值数组 */ type RowOrColValuesMap = { [key: string]: any[] }; interface ITableValues { /**字段名数组 */ fields: string[]; /**表格值数组 */ rowOrColValuesMap: RowOrColValuesMap; } /** * 解析结果 */ interface ITableParseResult { /**配置表定义 */ tableDefine?: ITableDefine; /**当前分表名 */ curSheetName?: string; /**字段字典 */ fieldMap?: TableFieldMap; // /**表格行或列的字典 */ // rowOrColMap: TableRowOrColMap /**单个表格对象 */ /**key是主键值,value是一行对象 */ tableObj?: { [key: string]: any }; /**当前行或列对象 */ curRowOrColObj?: any; /**主键值 */ mainKeyFieldName?: string; } /**值转换结果 */ interface ITransValueResult { error?: any; value?: any; } /**值转换方法 */ type ValueTransFunc = (fieldItem: ITableField, cellValue: any) => ITransValueResult; /** * 值转换方法字典 * key是类型key * value是方法 */ type ValueTransFuncMap = { [key: string]: ValueTransFunc }; } /** * 配置表类型 * 按照字段扩展方向定 */ export enum TableType { /**字段垂直扩展 */ vertical = "vertical", /**字段横向扩展 */ horizontal = "horizontal" } export class DefaultTableParser implements ITableParser { getTableDefine(fileInfo: IFileInfo, workBook: xlsx.WorkBook): ITableDefine { let cellKey: string; let cellObj: xlsx.CellObject; const sheetNames = workBook.SheetNames; let sheet: xlsx.Sheet; let firstCanParseSheet: xlsx.Sheet; //第一个格子的值tableNameInSheet(表名),tableType:表格类型 let firstCellValue: ITableFirstCellValue; let firstCellObj: xlsx.CellObject; const tableDefine: Partial<ITableDefine> = {}; for (let i = 0; i < sheetNames.length; i++) { sheet = workBook.Sheets[sheetNames[i]]; firstCellObj = sheet["A" + 1]; if (!isEmptyCell(firstCellObj)) { firstCanParseSheet = sheet; firstCellValue = this._getFirstCellValue(firstCellObj); if (!tableDefine.tableName) { tableDefine.tableName = firstCellValue.tableNameInSheet; tableDefine.tableType = firstCellValue.tableType; } if (firstCellValue && firstCellValue.tableNameInSheet === tableDefine.tableName) { break; } } } if (!tableDefine.tableName || !tableDefine.tableType) { return null; } if (tableDefine.tableType === TableType.vertical) { tableDefine.verticalFieldDefine = {} as any; const verticalFieldDefine = tableDefine.verticalFieldDefine; verticalFieldDefine.textCol = "A"; verticalFieldDefine.typeCol = "B"; verticalFieldDefine.fieldCol = "C"; tableDefine.startCol = "D"; tableDefine.startRow = 2; } else if (tableDefine.tableType === TableType.horizontal) { tableDefine.horizontalFieldDefine = {} as any; const horizontalFieldDefine: IHorizontalFieldDefine = tableDefine.horizontalFieldDefine; horizontalFieldDefine.textRow = 1; for (let i = 1; i < 100; i++) { cellKey = "A" + i; cellObj = firstCanParseSheet[cellKey]; if (isEmptyCell(cellObj) || cellObj.v === "NO" || cellObj.v === "END" || cellObj.v === "START") { tableDefine.startRow = i; } else if (cellObj.v === "CLIENT") { horizontalFieldDefine.fieldRow = i; } else if (cellObj.v === "TYPE") { horizontalFieldDefine.typeRow = i; } if (tableDefine.startRow && horizontalFieldDefine.fieldRow && horizontalFieldDefine.typeRow) break; } tableDefine.startCol = "B"; } return tableDefine as any; } private _getFirstCellValue(firstCellObj: xlsx.CellObject): ITableFirstCellValue { if (!firstCellObj) return; const cellValues = (firstCellObj.v as string).split(":"); let tableNameInSheet: string; let tableType: TableType; if (cellValues.length > 1) { tableNameInSheet = cellValues[1]; tableType = cellValues[0] === "V" ? TableType.vertical : TableType.horizontal; } else { tableNameInSheet = cellValues[0]; tableType = TableType.horizontal; } return { tableNameInSheet: tableNameInSheet, tableType: tableType }; } /** * 判断表格是否能解析 * @param sheet */ checkSheetCanParse(tableDefine: ITableDefine, sheet: xlsx.Sheet, sheetName: string): boolean { //如果这个表个第一格值不等于表名,则不解析 const firstCellObj: xlsx.CellObject = sheet["A" + 1]; const firstCellValue = this._getFirstCellValue(firstCellObj); if (firstCellObj && tableDefine) { if (firstCellValue.tableNameInSheet !== tableDefine.tableName) { return false; } return true; } else { return false; } } /** * 表行结束判断 * @param tableDefine * @param sheet * @param row */ isSheetRowEnd(tableDefine: ITableDefine, sheet: xlsx.Sheet, row: number): boolean { // if (tableDefine.tableType === TableType.vertical) { // } else if (tableDefine.tableType === TableType.horizontal) { // } //判断上一行的标志是否为END if (row > 1) { row = row - 1; const cellObj: xlsx.CellObject = sheet["A" + row]; return cellObj && cellObj.v === "END"; } else { return false; } } /** * 表列结束判断 * @param tableDefine * @param sheet * @param colKey */ isSheetColEnd(tableDefine: ITableDefine, sheet: xlsx.Sheet, colKey: string): boolean { //判断这一列第一行是否为空 const firstCellObj: xlsx.CellObject = sheet[colKey + 1]; // const typeCellObj: xlsx.CellObject = sheet[colKey + tableFile.tableDefine.typeRow]; return isEmptyCell(firstCellObj); } /** * 检查行是否需要解析 * @param tableDefine * @param sheet * @param rowIndex */ checkRowNeedParse(tableDefine: ITableDefine, sheet: xlsx.Sheet, rowIndex: number): boolean { const cellObj: xlsx.CellObject = sheet["A" + rowIndex]; if (cellObj && cellObj.v === "NO") { return false; } return true; } /** * 解析横向表格的单个格子 * @param tableParseResult * @param sheet * @param colKey * @param rowIndex * @param isNewRowOrCol 是否为新的一行或者一列 */ parseHorizontalCell( valueTransFuncMap: ValueTransFuncMap, tableParseResult: ITableParseResult, sheet: xlsx.Sheet, colKey: string, rowIndex: number, isNewRowOrCol: boolean ): void { const fieldInfo = this.getHorizontalTableField(tableParseResult, sheet, colKey, rowIndex); if (!fieldInfo) return; const cell: xlsx.CellObject = sheet[colKey + rowIndex]; if (isEmptyCell(cell)) { return; } const transResult = this.transValue(valueTransFuncMap, tableParseResult, fieldInfo, cell.v); if (transResult.error) { tableParseResult.hasError = true; Logger.log( `!!!!!!!!!!!!!!!!!![-----解析错误-----]!!!!!!!!!!!!!!!!!!!!!!!!!\n` + `[sheetName|分表名]=> ${tableParseResult.curSheetName}\n` + `[row|行]=> ${rowIndex}\n` + `[col|列]=> ${colKey}\n` + `[field|字段]=> ${fieldInfo.originFieldName}\n` + `[type|类型]=> ${fieldInfo.originType}\n` + `[error|错误]=> ${ typeof transResult.error === "string" ? transResult.error : transResult.error.message }\n`, "error" ); // Logger.log(transResult.error, "error"); } const transedValue = transResult.value; let mainKeyFieldName: string = tableParseResult.mainKeyFieldName; if (!mainKeyFieldName) { //第一个字段就是主键 mainKeyFieldName = fieldInfo.fieldName; tableParseResult.mainKeyFieldName = fieldInfo.fieldName; tableParseResult.tableObj = {}; } let rowOrColObj: any = tableParseResult.curRowOrColObj; if (isNewRowOrCol) { //新的一行 rowOrColObj = {}; tableParseResult.curRowOrColObj = tableParseResult.tableObj[transedValue] = rowOrColObj; } if (fieldInfo.isMutiColObj) { let subObj = rowOrColObj[fieldInfo.fieldName]; if (!subObj) { subObj = {}; rowOrColObj[fieldInfo.fieldName] = subObj; } subObj[fieldInfo.subFieldName] = transedValue; } else { rowOrColObj[fieldInfo.fieldName] = transedValue; } } /** * 解析纵向表格的单个格子 * @param valueTransFuncMap * @param tableParseResult * @param sheet * @param colKey * @param rowIndex * @param isNewRowOrCol 是否为新的一行或者一列 */ parseVerticalCell( valueTransFuncMap: ValueTransFuncMap, tableParseResult: ITableParseResult, sheet: xlsx.Sheet, colKey: string, rowIndex: number, isNewRowOrCol: boolean ): void { const fieldInfo = this.getVerticalTableField(tableParseResult, sheet, colKey, rowIndex); if (!fieldInfo) return; const cell: xlsx.CellObject = sheet[colKey + rowIndex]; if (isEmptyCell(cell)) { return; } const transResult = this.transValue(valueTransFuncMap, tableParseResult, fieldInfo, cell.v); if (transResult.error) { Logger.log( `!!!!!!!!!!!!!!!!!![-----ParseError|解析错误-----]!!!!!!!!!!!!!!!!!!!!!!!!!\n` + `[sheetName|分表名]=> ${tableParseResult.curSheetName}\n` + `[row|行]=> ${rowIndex}\n` + `[col|列]=> ${colKey}\n` + `[field|字段]=> ${fieldInfo.originFieldName}\n` + `[type|类型]=> ${fieldInfo.originType}\n` + `[error|错误]=> ${ typeof transResult.error === "string" ? transResult.error : transResult.error.message }\n` + `!!!!!!!!!!!!!!!!!![-----ParseError|解析错误-----]!!!!!!!!!!!!!!!!!!!!!!!!!\n`, "error" ); } const transedValue = transResult.value; if (!tableParseResult.tableObj) { tableParseResult.tableObj = {}; } if (fieldInfo.isMutiColObj) { let subObj = tableParseResult.tableObj[fieldInfo.fieldName]; if (!subObj) { subObj = {}; tableParseResult.tableObj[fieldInfo.fieldName] = subObj; } subObj[fieldInfo.subFieldName] = transedValue; } else { tableParseResult.tableObj[fieldInfo.fieldName] = transedValue; } } /** * 解析出横向表的字段对象 * @param tableParseResult * @param sheet * @param colKey * @param rowIndex */ getHorizontalTableField( tableParseResult: ITableParseResult, sheet: xlsx.Sheet, colKey: string, rowIndex: number ): ITableField { const tableDefine = tableParseResult.tableDefine; let tableFieldMap = tableParseResult.fieldMap; if (!tableFieldMap) { tableFieldMap = {}; tableParseResult.fieldMap = tableFieldMap; } const horizontalFieldDefine = tableDefine.horizontalFieldDefine; const fieldCell = sheet[colKey + horizontalFieldDefine.fieldRow]; let originFieldName: string; if (!isEmptyCell(fieldCell)) { originFieldName = fieldCell.v as string; } if (!originFieldName) return null; let field: ITableField = {} as any; //缓存 if (tableFieldMap[originFieldName] !== undefined) { return tableFieldMap[originFieldName]; } //注释 const textCell: xlsx.CellObject = sheet[colKey + horizontalFieldDefine.textRow]; if (!isEmptyCell(textCell)) { field.text = textCell.v as string; } //类型 let isObjType: boolean = false; const typeCell = sheet[colKey + horizontalFieldDefine.typeRow]; if (isEmptyCell(typeCell)) { return null; } else { field.originType = typeCell.v as string; if (field.originType.includes("mf:")) { const typeStrs = field.originType.split(":"); if (typeStrs.length < 3) { return null; } field.type = typeStrs[2]; isObjType = true; } else { field.type = field.originType; } } field.isMutiColObj = isObjType; //字段名 field.originFieldName = originFieldName; if (isObjType) { const fieldStrs = field.originFieldName.split(":"); if (fieldStrs.length < 2) { return null; } field.fieldName = fieldStrs[0]; field.subFieldName = fieldStrs[1]; } else { field.fieldName = field.originFieldName; } tableFieldMap[originFieldName] = field; return field; } /** * 解析出纵向表的字段类型对象 * @param tableParseResult * @param sheet * @param colKey * @param rowIndex * @returns */ getVerticalTableField( tableParseResult: ITableParseResult, sheet: xlsx.Sheet, colKey: string, rowIndex: number ): ITableField { const tableDefine = tableParseResult.tableDefine; let tableFieldMap = tableParseResult.fieldMap; if (!tableFieldMap) { tableFieldMap = {}; tableParseResult.fieldMap = tableFieldMap; } const verticalFieldDefine = tableDefine.verticalFieldDefine; const fieldNameCell: xlsx.CellObject = sheet[verticalFieldDefine.fieldCol + rowIndex]; let originFieldName: string; if (!isEmptyCell(fieldNameCell)) { originFieldName = fieldNameCell.v as string; } if (!originFieldName) return null; if (tableFieldMap[originFieldName] !== undefined) { return tableFieldMap[originFieldName]; } let field: ITableField = {} as any; const textCell: xlsx.CellObject = sheet[verticalFieldDefine.textCol + rowIndex]; //注释 if (!isEmptyCell(textCell)) { field.text = textCell.v as string; } let isObjType: boolean = false; //类型 const typeCell: xlsx.CellObject = sheet[verticalFieldDefine.typeCol + rowIndex]; if (isEmptyCell(typeCell)) { return null; } else { //处理类型 field.originType = typeCell.v as string; if (field.originType.includes("mf:")) { const typeStrs = field.originType.split(":"); if (typeStrs.length < 3) { return null; } field.type = typeStrs[2]; isObjType = true; } else { field.type = field.originType; } } field.isMutiColObj = isObjType; field.originFieldName = originFieldName; if (isObjType) { const fieldStrs = field.originFieldName.split(":"); if (fieldStrs.length < 2) { return null; } field.fieldName = fieldStrs[0]; field.subFieldName = fieldStrs[1]; } else { field.fieldName = field.originFieldName; } tableFieldMap[originFieldName] = field; return field; } /** * 检查列是否需要解析 * @param tableDefine * @param sheet * @param colKey */ checkColNeedParse(tableDefine: ITableDefine, sheet: xlsx.Sheet, colKey: string): boolean { // 如果类型或者则不需要解析 if (tableDefine.tableType === TableType.vertical) { const cellObj: xlsx.CellObject = sheet[colKey + 1]; if (isEmptyCell(cellObj)) { return false; } else { return true; } } else if (tableDefine.tableType === TableType.horizontal) { const horizontalFieldDefine = tableDefine.horizontalFieldDefine; const typeCellObj: xlsx.CellObject = sheet[colKey + horizontalFieldDefine.typeRow]; const fieldCellObj: xlsx.CellObject = sheet[colKey + horizontalFieldDefine.fieldRow]; if (isEmptyCell(typeCellObj) || isEmptyCell(fieldCellObj)) { return false; } else { return true; } } } /** * 转换表格的值 * @param parseResult * @param fieldItem * @param cellValue */ public transValue( valueTransFuncMap: ValueTransFuncMap, parseResult: ITableParseResult, fieldItem: ITableField, cellValue: any ): ITransValueResult { let transResult: ITransValueResult; let transFunc = valueTransFuncMap[fieldItem.type]; if (!transFunc) { transFunc = valueTransFuncMap["json"]; } transResult = transFunc(fieldItem, cellValue); return transResult; } /** * 解析配置表文件 * @param convertConfig 解析配置 * @param fileInfo 文件信息 * @param parseResult 解析结果 */ public parseTableFile( convertConfig: ITableConvertConfig, fileInfo: IFileInfo, parseResult: ITableParseResult ): ITableParseResult { fileInfo.fileData = isCSV(fileInfo.fileExtName) ? (fileInfo.fileData as Buffer).toString() : fileInfo.fileData; const workbook = readTableData(fileInfo); if (!workbook.SheetNames.length) return; let valueTransFuncMap = convertConfig?.parserConfig?.customValueTransFuncMap; if (!valueTransFuncMap) { valueTransFuncMap = defaultValueTransFuncMap; } else { valueTransFuncMap = Object.assign(valueTransFuncMap, defaultValueTransFuncMap); } const sheetNames = workbook.SheetNames; const tableDefine: ITableDefine = this.getTableDefine(fileInfo, workbook); if (!tableDefine) { Logger.log(`表格不规范,跳过解析,路径:${fileInfo.filePath}`, "warn"); return; } let sheetName: string; let sheet: xlsx.Sheet; const isSheetRowEnd = this.isSheetRowEnd.bind(null, tableDefine); const isSheetColEnd = this.isSheetColEnd.bind(null, tableDefine); const isSkipSheetRow = (sheet: xlsx.Sheet, rowIndex: number) => { return !this.checkRowNeedParse(tableDefine, sheet, rowIndex); }; const isSkipSheetCol = (sheet: xlsx.Sheet, colKey: string) => { return !this.checkColNeedParse(tableDefine, sheet, colKey); }; let cellObj: xlsx.CellObject; parseResult.tableDefine = tableDefine; Logger.log(`[parseTable|解析文件]=> ${fileInfo.filePath}`); for (let i = 0; i < sheetNames.length; i++) { sheetName = sheetNames[i]; sheet = workbook.Sheets[sheetName]; if (!this.checkSheetCanParse(tableDefine, sheet, sheetName)) { continue; } parseResult.curSheetName = sheetName; Logger.log(`|=[parseSheet|解析分表]=> ${sheetName}`); if (tableDefine.tableType === TableType.horizontal) { let lastRowIndex: number; forEachHorizontalSheet( sheet, tableDefine.startRow, tableDefine.startCol, (sheet, colKey: string, rowIndex: number) => { let isNewRowOrCol = false; if (lastRowIndex !== rowIndex) { lastRowIndex = rowIndex; isNewRowOrCol = true; } cellObj = sheet[colKey + rowIndex]; this.parseHorizontalCell( valueTransFuncMap, parseResult, sheet, colKey, rowIndex, isNewRowOrCol ); }, isSheetRowEnd, isSheetColEnd, isSkipSheetRow, isSkipSheetCol ); } else if (tableDefine.tableType === TableType.vertical) { let lastColKey: string; forEachVerticalSheet( sheet, tableDefine.startRow, tableDefine.startCol, (sheet, colKey: string, rowIndex: number) => { let isNewRowOrCol = false; if (lastColKey !== colKey) { lastColKey = colKey; isNewRowOrCol = true; } cellObj = sheet[colKey + rowIndex]; if (!isEmptyCell(cellObj)) { this.parseVerticalCell( valueTransFuncMap, parseResult, sheet, colKey, rowIndex, isNewRowOrCol ); } }, isSheetRowEnd, isSheetColEnd, isSkipSheetRow, isSkipSheetCol ); } } return parseResult as any; } }
the_stack
import { LayoutViewer, DocumentHelper } from '../index'; import { TextSearchResults } from './text-search-results'; import { TextSearchResult } from './text-search-result'; import { createElement, isNullOrUndefined, L10n, classList } from '@syncfusion/ej2-base'; import { FindOption } from '../../base/types'; import { TextPosition } from '../selection/selection-helper'; import { HelperMethods } from '../editor/editor-helper'; import { CheckBox } from '@syncfusion/ej2-buttons'; import { Tab, SelectEventArgs, TabItemModel } from '@syncfusion/ej2-navigations'; /** * Options Pane class. */ export class OptionsPane { private documentHelper: DocumentHelper; /** * @private */ public optionsPane: HTMLElement; /** * @private */ public isOptionsPaneShow: boolean = false; private resultsListBlock: HTMLElement; private messageDiv: HTMLElement; private results: TextSearchResults; private searchInput: HTMLInputElement; private searchDiv: HTMLElement; private searchTextBoxContainer: HTMLElement; private replaceWith: HTMLInputElement; private findDiv: HTMLElement; private replaceDiv: HTMLElement; private replaceButton: HTMLElement; private replaceAllButton: HTMLElement; private occurrenceDiv: HTMLElement; private findOption: FindOption = 'None'; private matchCase: CheckBox = undefined; private wholeWord: CheckBox = undefined; // private regular: CheckBox = undefined; private searchText: string = 'Navigation'; private resultsText: string = 'Results'; private messageDivText: string = 'No matches'; private replaceButtonText: string = 'Replace'; private replaceAllButtonText: string = 'Replace All'; private focusedIndex: number = -1; private focusedElement: HTMLElement[] = []; private resultContainer: HTMLElement; private navigateToPreviousResult: HTMLElement; private navigateToNextResult: HTMLElement; private closeButton: HTMLElement; private isOptionsPane: boolean = true; private findTab: HTMLElement; private findTabButton: HTMLElement; private replaceTabButton: HTMLElement; private searchIcon: HTMLSpanElement; private matchDiv: HTMLElement; private replacePaneText: string = 'Replace'; private findPaneText: string = 'Find'; private matchDivReplaceText: string = 'No matches'; private matchInput: HTMLInputElement; private wholeInput: HTMLInputElement; private regularInput: HTMLInputElement; /** * @private */ public tabInstance: Tab = undefined; private findTabContentDiv: HTMLElement; private replaceTabContentDiv: HTMLElement; /** * @private */ public isReplace: boolean = false; private localeValue: L10n; public constructor(documentHelper: DocumentHelper) { this.documentHelper = documentHelper; } private get viewer(): LayoutViewer { return this.documentHelper.owner.viewer; } private getModuleName(): string { return 'OptionsPane'; } /** * Initialize the options pane. * * @private * @param {L10n} localeValue - Specifies the localization based on culture. * @param {boolean} isRtl - Specifies the Rtl. * @returns {void} */ /* eslint-disable */ public initOptionsPane(localeValue: L10n, isRtl?: boolean): void { let viewer: LayoutViewer = this.viewer; this.localeValue = localeValue; this.optionsPane = createElement('div', { className: 'e-de-op', styles: 'display:none;' }); this.optionsPane.addEventListener('keydown', this.onKeyDownOnOptionPane); this.searchDiv = createElement('div', { className: this.documentHelper.owner.containerId + '_searchDiv e-de-op-header', innerHTML: localeValue.getConstant(this.searchText) }); this.optionsPane.appendChild(this.searchDiv); this.closeButton = createElement('button', { className: 'e-de-op-close-button e-de-close-icon e-de-op-icon-btn e-btn e-flat e-icon-btn', id: 'close', attrs: { type: 'button' } }); this.optionsPane.appendChild(this.closeButton); let closeSpan: HTMLSpanElement = createElement('span', { className: 'e-de-op-close-icon e-de-close-icon e-btn-icon e-icons' }); this.closeButton.appendChild(closeSpan); this.focusedElement.push(this.closeButton); //Find tab header this.findTab = createElement('div', { id: this.documentHelper.owner.containerId + '_findTabDiv', className: 'e-de-op-tab' }); this.optionsPane.appendChild(this.findTab); this.findTabButton = createElement('div', { innerHTML: localeValue.getConstant(this.findPaneText) }); this.replaceTabButton = createElement('div', { innerHTML: localeValue.getConstant(this.replacePaneText) }); let findTabContent: HTMLElement = createElement('div'); this.findTabContentDiv = createElement('div', { className: 'e-de-search-tab-content' }); this.searchTextBoxContainer = createElement('div', { className: 'e-input-group e-de-op-input-group' }); this.findTabContentDiv.appendChild(this.searchTextBoxContainer); this.searchInput = createElement('input', { className: 'e-input e-de-search-input', id: this.documentHelper.owner.containerId + '_option_search_text_box', attrs: { placeholder: localeValue.getConstant('Search for') } }) as HTMLInputElement; this.searchTextBoxContainer.appendChild(this.searchInput); this.searchIcon = createElement('span', { className: 'e-de-op-icon e-de-op-search-icon e-input-group-icon e-icon', id: this.documentHelper.owner.containerId + '_search-icon' }); this.searchIcon.tabIndex = 0; this.searchTextBoxContainer.appendChild(this.searchIcon); this.focusedElement.push(this.searchIcon); this.navigateToPreviousResult = createElement('span', { className: 'e-de-op-icon e-de-op-nav-btn e-arrow-up e-spin-up e-btn-icon e-icon e-input-group-icon' }); this.navigateToPreviousResult.tabIndex = 0; this.searchTextBoxContainer.appendChild(this.navigateToPreviousResult); this.focusedElement.push(this.navigateToPreviousResult); this.navigateToNextResult = createElement('span', { className: 'e-de-op-icon e-de-op-nav-btn e-arrow-down e-spin-down e-btn-icon e-icon e-input-group-icon' }); this.navigateToNextResult.tabIndex = 0; this.searchTextBoxContainer.appendChild(this.navigateToNextResult); this.focusedElement.push(this.navigateToNextResult); let div: HTMLElement = createElement('div', { className: 'e-de-op-more-less' }); this.matchInput = createElement('input', { attrs: { type: 'checkbox' }, id: this.documentHelper.owner.containerId + '_matchCase' }) as HTMLInputElement; div.appendChild(this.matchInput); this.matchCase = new CheckBox({ label: localeValue.getConstant('Match case'), enableRtl: isRtl, checked: false, change: this.matchChange.bind(this) }); this.matchCase.appendTo(this.matchInput); this.focusedElement.push(this.matchInput); this.matchInput.tabIndex = 0; let wholeWordLabel: string; if (isRtl) { wholeWordLabel = '_e-de-rtl'; } else { wholeWordLabel = '_e-de-ltr'; } this.wholeInput = createElement('input', { attrs: { type: 'checkbox' }, id: this.documentHelper.owner.containerId + '_wholeWord' + wholeWordLabel }) as HTMLInputElement; div.appendChild(this.wholeInput); this.wholeWord = new CheckBox({ label: localeValue.getConstant('Whole words'), enableRtl: isRtl, checked: false, change: this.wholeWordsChange.bind(this) }); this.wholeWord.appendTo(this.wholeInput); this.focusedElement.push(this.wholeInput); this.wholeInput.tabIndex = 0; this.findTabContentDiv.appendChild(div); //Replace tab let replaceTabContent: HTMLElement = createElement('div'); this.replaceTabContentDiv = createElement('div', { className: 'e-de-op-replacetabcontentdiv', styles: 'display:none;' }); this.findTabContentDiv.appendChild(this.replaceTabContentDiv); this.createReplacePane(isRtl); this.findDiv = createElement('div', { className: 'findDiv', styles: 'display:block;' }); findTabContent.appendChild(this.findTabContentDiv); this.resultContainer = createElement('div', { styles: 'width:85%;display:block;', className: 'e-de-op-result-container' }); this.findDiv.appendChild(this.resultContainer); this.messageDiv = createElement('div', { className: this.documentHelper.owner.containerId + '_messageDiv e-de-op-msg', innerHTML: this.localeValue.getConstant(this.messageDivText), id: this.documentHelper.owner.containerId + '_search_status' }); this.resultContainer.appendChild(this.messageDiv); this.resultsListBlock = createElement('div', { id: this.documentHelper.owner.containerId + '_list_box_container', styles: 'display:none;width:270px;list-style:none;padding-right:5px;overflow:auto;', className: 'e-de-result-list-block' }); this.findDiv.appendChild(this.resultsListBlock); this.findTabContentDiv.appendChild(this.findDiv); let items: TabItemModel[] = [ { header: { text: this.findTabButton }, content: findTabContent }, { header: { text: this.replaceTabButton }, content: replaceTabContent }] as TabItemModel[]; this.tabInstance = new Tab({ items: items, enableRtl: isRtl, selected: this.selectedTabItem.bind(this) }); this.tabInstance.isStringTemplate = true; this.tabInstance.appendTo(this.findTab); this.onWireEvents(); if (isRtl) { this.optionsPane.classList.add('e-de-rtl'); this.closeButton.classList.add('e-de-rtl'); this.searchDiv.classList.add('e-de-rtl'); } } private createReplacePane(isRtl?: boolean): void { this.replaceDiv = createElement('div'); this.replaceTabContentDiv.appendChild(this.replaceDiv); this.replaceWith = createElement('input', { className: 'e-de-op-replacewith e-input', attrs: { placeholder: this.localeValue.getConstant('Replace with') } }) as HTMLInputElement; this.replaceDiv.appendChild(this.replaceWith); let replaceButtonDivTextAlign: string; let replaceButtonMargin: string; if (isRtl) { replaceButtonDivTextAlign = 'text-align:left'; replaceButtonMargin = 'margin-left:10px'; } else { replaceButtonDivTextAlign = 'text-align:right'; replaceButtonMargin = 'margin-right:10px'; } let replaceButtonDiv: HTMLElement = createElement('div', { styles: replaceButtonDivTextAlign, className: 'e-de-op-dlg-footer' }); this.replaceDiv.appendChild(replaceButtonDiv); this.replaceButton = createElement('button', { className: 'e-control e-btn e-flat e-replace', styles: replaceButtonMargin, innerHTML: this.localeValue.getConstant(this.replaceButtonText), attrs: { type: 'button' } }); replaceButtonDiv.appendChild(this.replaceButton); this.replaceAllButton = createElement('button', { className: 'e-control e-btn e-flat e-replaceall', innerHTML: this.localeValue.getConstant(this.replaceAllButtonText), attrs: { type: 'button' } }); replaceButtonDiv.appendChild(this.replaceAllButton); this.matchDiv = createElement('div', { styles: 'display:none;padding-top:10px;' }); this.replaceDiv.appendChild(this.matchDiv); let emptyDiv6: HTMLElement = createElement('div', { className: 'e-de-op-search-replacediv' }); this.replaceDiv.appendChild(emptyDiv6); this.occurrenceDiv = createElement('div', { styles: 'display:none;' }); this.replaceDiv.appendChild(this.occurrenceDiv); } private selectedTabItem(args: SelectEventArgs): void { let contentParent: Element = this.findTab.getElementsByClassName('e-content').item(0); if (args.previousIndex !== args.selectedIndex) { let previousTab: Element = contentParent.children[0]; let nextTab: Element = contentParent.children[1]; let element: HTMLElement = previousTab.firstElementChild as HTMLElement; if (element) { if (element.parentElement) { element.parentElement.removeChild(element); } nextTab.appendChild(element); } } let selectedElement: Element = contentParent.children[0]; if (!isNullOrUndefined(selectedElement)) { if (args.selectedIndex === 0) { this.isOptionsPane = true; this.onFindPane(); } else { this.isOptionsPane = false; this.onReplacePane(); } } } /** * @returns {void} */ private searchOptionChange = (): void => { this.clearSearchResultItems(); this.documentHelper.owner.searchModule.clearSearchHighlight(); let inputText: string = this.searchInput.value; if (inputText === '') { return; } let pattern: RegExp = this.documentHelper.owner.searchModule.textSearch.stringToRegex(inputText, this.findOption); let endSelection: TextPosition = this.documentHelper.selection.end; let selectionIndex: string = endSelection.getHierarchicalIndexInternal(); this.results = this.documentHelper.owner.searchModule.textSearch.findAll(pattern, this.findOption, selectionIndex); if (this.results != null && this.results.length > 0) { this.navigateSearchResult(false); } else { this.viewer.renderVisiblePages(); this.messageDiv.innerHTML = this.localeValue.getConstant('No matches'); this.resultContainer.style.display = 'block'; this.resultsListBlock.style.display = 'none'; this.clearFocusElement(); this.resultsListBlock.innerHTML = ''; } } private navigateSearchResult(navigate: boolean): void { if (navigate) { this.documentHelper.owner.searchModule.navigate(this.results.innerList[this.results.currentIndex]); } this.documentHelper.owner.searchModule.highlight(this.results); this.documentHelper.owner.searchModule.addFindResultView(this.results); this.resultsListBlock.style.display = 'block'; this.resultContainer.style.display = 'block'; let lists: string[] = this.documentHelper.owner.findResultsList; let text: string = ''; for (let i: number = 0; i < lists.length; i++) { text += lists[i]; } this.clearFocusElement(); this.resultsListBlock.innerHTML = text; for (let i: number = 0; i < this.resultsListBlock.children.length; i++) { this.focusedElement.push(this.resultsListBlock.children[i] as HTMLElement); } let currentIndexValue: number = this.results.currentIndex; this.messageDiv.innerHTML = this.localeValue.getConstant('Result') + ' ' + (currentIndexValue + 1) + ' ' + this.localeValue.getConstant('of') + ' ' + this.resultsListBlock.children.length; let listElement: HTMLElement = this.resultsListBlock.children[currentIndexValue] as HTMLElement; if (listElement.classList.contains('e-de-search-result-item')) { listElement.classList.remove('e-de-search-result-item'); listElement.classList.add('e-de-search-result-hglt'); listElement.children[0].classList.add('e-de-op-search-word-text'); this.scrollToPosition(listElement); } } /** * Apply find option based on whole words value. * * @private * @returns {void} */ public wholeWordsChange(): void { if (this.matchInput.checked && this.wholeInput.checked) { this.findOption = 'CaseSensitiveWholeWord'; } else if (this.matchInput.checked && !(this.wholeInput.checked)) { this.findOption = 'CaseSensitive'; } else if (!(this.matchInput.checked) && this.wholeInput.checked) { this.findOption = 'WholeWord'; } else { this.findOption = 'None'; } this.searchOptionChange(); } /** * Apply find option based on match value. * * @private * @returns {void} */ public matchChange(): void { if (this.matchInput.checked && this.wholeInput.checked) { this.findOption = 'CaseSensitiveWholeWord'; } else if (!(this.matchInput.checked) && this.wholeInput.checked) { this.findOption = 'WholeWord'; } else if (this.matchInput.checked && !(this.wholeInput.checked)) { this.findOption = 'CaseSensitive'; } else { this.findOption = 'None'; } this.searchOptionChange(); } // /** // * Apply find options based on regular value. // * @param {ChangeEventArgs} args - Specifies the search options value. // * @private // */ // public regularChange = (args: ChangeEventArgs): void => { // if (args.checked) { // this.matchCase.element.parentElement.parentElement.classList.add('e-checkbox-disabled'); // this.wholeWord.element.parentElement.parentElement.classList.add('e-checkbox-disabled'); // this.matchCase.checked = false; // this.wholeWord.checked = false; // this.findOption = 'None'; // this.onKeyDownInternal(); // } else { // this.matchCase.element.parentElement.parentElement.classList.remove('e-checkbox-disabled'); // this.wholeWord.element.parentElement.parentElement.classList.remove('e-checkbox-disabled'); // } // } /* eslint-enable @typescript-eslint/no-explicit-any */ /** * Binding events from the element when optins pane creation. * * @private * @returns {void} */ public onWireEvents(): void { this.searchIcon.addEventListener('click', this.searchIconClickInternal); this.navigateToNextResult.addEventListener('click', this.navigateNextResultButtonClick); this.navigateToPreviousResult.addEventListener('click', this.navigatePreviousResultButtonClick); this.searchInput.addEventListener('keydown', this.onKeyDown); this.searchInput.addEventListener('keyup', this.onEnableDisableReplaceButton); this.resultsListBlock.addEventListener('click', this.resultListBlockClick); this.closeButton.addEventListener('click', this.close); this.replaceButton.addEventListener('click', this.onReplaceButtonClick); this.replaceAllButton.addEventListener('click', this.onReplaceAllButtonClick); } /** * Fires on key down actions done. * * @private * @returns {void} */ public onKeyDownInternal(): void { let inputElement: HTMLInputElement = document.getElementById(this.documentHelper.owner.containerId + '_option_search_text_box') as HTMLInputElement; inputElement.blur(); let text: string = inputElement.value; if (text === '') { return; } if (text.length >= 1 && this.searchIcon.classList.contains('e-de-op-search-icon')) { this.searchIcon.classList.add('e-de-op-search-close-icon'); this.searchIcon.classList.remove('e-de-op-search-icon'); } let height: number = this.isOptionsPane ? 215 : 292; let resultsContainerHeight: number = this.documentHelper.owner.getDocumentEditorElement().offsetHeight - height; this.clearSearchResultItems(); this.documentHelper.owner.searchModule.clearSearchHighlight(); let pattern: RegExp = this.documentHelper.owner.searchModule.textSearch.stringToRegex(text, this.findOption); let endSelection: TextPosition = this.documentHelper.selection.end; let index: string = endSelection.getHierarchicalIndexInternal(); this.results = this.documentHelper.owner.searchModule.textSearch.findAll(pattern, this.findOption, index); let results: TextSearchResults = this.results; if (isNullOrUndefined(results)) { this.viewer.renderVisiblePages(); } if (results != null && results.length > 0) { if ((this.focusedElement.indexOf(this.navigateToPreviousResult) === -1) && this.isOptionsPane) { this.focusedElement.push(this.navigateToPreviousResult); } if ((this.focusedElement.indexOf(this.navigateToNextResult) === -1) && this.isOptionsPane) { this.focusedElement.push(this.navigateToNextResult); } this.documentHelper.owner.searchModule.navigate(this.results.innerList[this.results.currentIndex]); this.documentHelper.owner.searchModule.highlight(results); this.documentHelper.owner.searchModule.addFindResultView(results); // if (this.isOptionsPane) { this.resultsListBlock.style.display = 'block'; this.resultsListBlock.style.height = resultsContainerHeight + 'px'; this.resultContainer.style.display = 'block'; let list: string[] = this.documentHelper.owner.findResultsList; let text: string = ''; this.clearFocusElement(); this.resultsListBlock.innerHTML = ''; for (let i: number = 0; i < list.length; i++) { text += list[i]; } this.resultsListBlock.innerHTML = text; for (let i: number = 0; i < this.resultsListBlock.children.length; i++) { this.focusedElement.push(this.resultsListBlock.children[i] as HTMLElement); } let lists: HTMLCollection = this.resultsListBlock.children; let currentIndex: number = this.results.currentIndex; this.messageDiv.innerHTML = this.localeValue.getConstant('Result') + ' ' + (currentIndex + 1) + ' ' + this.localeValue.getConstant('of') + ' ' + this.resultsListBlock.children.length; let listElement: HTMLElement = this.resultsListBlock.children[currentIndex] as HTMLElement; if (listElement.classList.contains('e-de-search-result-item')) { listElement.classList.remove('e-de-search-result-item'); listElement.classList.add('e-de-search-result-hglt'); listElement.children[0].classList.add('e-de-op-search-word-text'); } this.navigateToNextResult.focus(); this.focusedIndex = this.focusedElement.indexOf(this.navigateToNextResult); this.getMessageDivHeight(); // } else { //this.focusedIndex = 4; // } } else { this.messageDiv.innerHTML = this.localeValue.getConstant('No matches'); this.resultContainer.style.display = 'block'; this.resultsListBlock.style.display = 'none'; this.clearFocusElement(); this.resultsListBlock.innerHTML = ''; } } /** * Enable find pane only. * * @private * @returns {void} */ public onFindPane(): void { this.replaceDiv.style.display = 'none'; this.occurrenceDiv.style.display = 'none'; if (!isNullOrUndefined(this.results) && this.results.length === 0) { this.resultsListBlock.innerHTML = ''; this.resultsListBlock.style.display = 'none'; this.messageDiv.innerHTML = this.localeValue.getConstant('No matches'); } let height: number = this.isOptionsPane ? 215 : 292; let resultsContainerHeight: number = this.documentHelper.owner.getDocumentEditorElement().offsetHeight - height; this.resultsListBlock.style.height = resultsContainerHeight + 'px'; this.replaceTabContentDiv.style.display = 'none'; this.findDiv.style.display = 'block'; this.messageDiv.style.display = 'block'; this.focusedElement = []; this.focusedElement.push(this.closeButton, this.searchInput, this.searchIcon, this.navigateToPreviousResult, this.navigateToNextResult, this.matchInput, this.wholeInput); this.focusedIndex = 1; this.searchInput.select(); this.getMessageDivHeight(); } private getMessageDivHeight(): void { if (!this.isOptionsPane && this.messageDiv.classList.contains('e-de-op-msg')) { this.messageDiv.classList.add('e-de-op-replace-messagediv'); this.messageDiv.classList.remove('e-de-op-msg'); } else if (this.isOptionsPane && this.messageDiv.classList.contains('e-de-op-replace-messagediv')) { this.messageDiv.classList.add('e-de-op-msg'); this.messageDiv.classList.remove('e-de-op-replace-messagediv'); } } /** * @returns {void} */ private onEnableDisableReplaceButton = (): void => { if (this.searchInput.value.length !== 0) { (this.replaceButton as HTMLButtonElement).disabled = false; (this.replaceAllButton as HTMLButtonElement).disabled = false; } else { (this.replaceButton as HTMLButtonElement).disabled = true; (this.replaceAllButton as HTMLButtonElement).disabled = true; } } /** * Enable replace pane only. * * @private * @returns {void} */ public onReplacePane(): void { this.findDiv.style.display = 'block'; this.replaceDiv.style.display = 'block'; this.replaceTabContentDiv.style.display = 'block'; let height: number = this.isOptionsPane ? 215 : 292; let resultsContainerHeight: number = this.documentHelper.owner.getDocumentEditorElement().offsetHeight - height; this.resultsListBlock.style.height = resultsContainerHeight + 'px'; this.isOptionsPane = false; if (this.searchInput.value.length !== 0) { (this.replaceButton as HTMLButtonElement).disabled = false; (this.replaceAllButton as HTMLButtonElement).disabled = false; } else { (this.replaceButton as HTMLButtonElement).disabled = true; (this.replaceAllButton as HTMLButtonElement).disabled = true; } this.focusedElement = []; this.focusedElement.push(this.closeButton, this.searchInput, this.searchIcon, this.navigateToPreviousResult, this.navigateToNextResult, this.matchInput, this.wholeInput, this.replaceWith, this.replaceButton, this.replaceAllButton); this.focusedIndex = 1; if (this.searchInput.value === '') { this.searchInput.select(); } else { this.replaceWith.select(); } this.getMessageDivHeight(); } /** * Fires on key down on options pane. * * @private * @param {KeyboardEvent} event - Specifies the focus of current element. * @returns {void} */ public onKeyDownOnOptionPane = (event: KeyboardEvent): void => { // if (event.keyCode === 70) { // event.preventDefault(); // return; // } if (event.keyCode === 9) { event.preventDefault(); let focusIndex: number = undefined; if (event.shiftKey) { focusIndex = (this.focusedIndex === 0 || isNullOrUndefined(this.focusedIndex)) ? this.focusedElement.length - 1 : this.focusedIndex - 1; } else { focusIndex = (this.focusedElement.length - 1 === this.focusedIndex || isNullOrUndefined(this.focusedIndex)) ? 0 : this.focusedIndex + 1; } let element: HTMLElement = this.focusedElement[focusIndex]; element.focus(); if (element instanceof HTMLInputElement) { element.select(); } this.focusedIndex = focusIndex; if (element instanceof HTMLLIElement) { this.scrollToPosition(element); } } else if (event.keyCode === 13) { this.hideMatchDiv(); if (event.target !== this.searchInput && event.target !== this.closeButton) { event.preventDefault(); let index: number = this.focusedElement.indexOf(event.target as HTMLElement); if (index !== -1) { let list: HTMLLIElement = this.focusedElement[index] as HTMLLIElement; list.click(); list.focus(); this.focusedIndex = index; } } } else if (event.keyCode === 40 || event.keyCode === 38) { if (this.resultsListBlock.style.display !== 'none') { let index: number; let element: HTMLElement; if (event.keyCode === 40) { if (this.focusedIndex > 7) { if (this.focusedIndex + 1 < this.focusedElement.length) { element = this.focusedElement[this.focusedIndex + 1]; element.focus(); this.focusedIndex = this.focusedIndex + 1; } } else { index = (this.focusedElement.length - this.resultsListBlock.children.length) + this.results.currentIndex + 1; if (index < this.focusedElement.length) { element = this.focusedElement[index]; element.focus(); this.focusedIndex = index; } } } else { if (this.focusedIndex > 6) { index = this.focusedIndex - 1; element = this.focusedElement[index]; element.focus(); this.focusedIndex = index; } } } } } /** * Fires on replace. * * @private * @returns {void} */ public onReplaceButtonClick = (): void => { let optionsPane: HTMLElement = this.optionsPane; let findText: string = this.searchInput.value; let replaceText: string = this.replaceWith.value; let results: TextSearchResults = this.documentHelper.owner.searchModule.textSearchResults; if (findText !== '' && !isNullOrUndefined(findText)) { if (this.documentHelper.owner.selection != null) { let selectionText: string = this.documentHelper.owner.selection.text; if (!this.documentHelper.owner.selection.isEmpty) { if (this.documentHelper.owner.selection.isForward) { this.documentHelper.owner.selection.selectContent(this.documentHelper.owner.selection.start, true); } else { this.documentHelper.owner.selection.selectContent(this.documentHelper.owner.selection.end, true); } } if (!isNullOrUndefined(results) && !isNullOrUndefined(results.currentSearchResult)) { let result: TextSearchResult = results.currentSearchResult; this.documentHelper.owner.searchModule.navigate(result); if (result.text === selectionText) { let replace: string = isNullOrUndefined(replaceText) ? '' : replaceText; this.documentHelper.owner.searchModule.replace(replace, result, results); let pattern: RegExp = this.documentHelper.owner.searchModule.textSearch.stringToRegex(findText, this.findOption); let endSelection: TextPosition = this.documentHelper.selection.end; let index: string = endSelection.getHierarchicalIndexInternal(); this.results = this.documentHelper.owner.searchModule.textSearch.findAll(pattern, this.findOption, index); if (!isNullOrUndefined(this.results) && !isNullOrUndefined(this.results.currentSearchResult)) { this.documentHelper.owner.searchModule.navigate(this.results.currentSearchResult); } else { this.messageDiv.style.display = 'block'; this.messageDiv.innerHTML = this.localeValue.getConstant(this.matchDivReplaceText); } this.documentHelper.owner.findResultsList = []; if (!isNullOrUndefined(this.results) && this.results.innerList.length > 0) { this.navigateSearchResult(true); } else { this.resultsListBlock.innerHTML = ''; } } else { this.documentHelper.owner.search.findAll(findText, this.findOption); } } else { this.documentHelper.owner.search.findAll(findText, this.findOption); this.messageDiv.style.display = 'block'; this.messageDiv.innerHTML = this.localeValue.getConstant(this.matchDivReplaceText); } } } } /** * Fires on replace all. * * @private * @returns {void} */ public onReplaceAllButtonClick = (): void => { this.replaceAll(); this.resultsListBlock.style.display = 'none'; this.messageDiv.innerHTML = ''; } /** * Replace all. * * @private * @returns {void} */ public replaceAll(): void { let optionsPane: HTMLElement = this.optionsPane; let findText: string = this.searchInput.value; let replaceText: string = this.replaceWith.value; if (findText !== '' && !isNullOrUndefined(findText)) { let pattern: RegExp = this.documentHelper.owner.searchModule.textSearch.stringToRegex(findText, this.findOption); let endSelection: TextPosition = this.documentHelper.selection.end; let index: string = endSelection.getHierarchicalIndexInternal(); let results: TextSearchResults = this.documentHelper.owner.searchModule.textSearch.findAll(pattern, this.findOption, index); let replace: string = isNullOrUndefined(replaceText) ? '' : replaceText; let count: number = isNullOrUndefined(results) ? 0 : results.length; this.documentHelper.owner.searchModule.replaceAll(replace, results); this.matchDiv.style.display = 'block'; this.matchDiv.innerHTML = this.localeValue.getConstant('All Done') + '!'; this.occurrenceDiv.style.display = 'block'; this.occurrenceDiv.innerHTML = this.localeValue.getConstant('We replaced all') + ' ' + count + ' ' + this.localeValue.getConstant('instances') + ' ' + this.localeValue.getConstant('of') + ' "' + findText + '" ' + this.localeValue.getConstant('with') + ' "' + replaceText + '" '; } } private hideMatchDiv(): void { this.matchDiv.style.display = 'none'; this.occurrenceDiv.style.display = 'none'; } /** * Fires on search icon. * * @private * @returns {void} */ public searchIconClickInternal = (): void => { /* eslint-disable @typescript-eslint/no-explicit-any */ let inputElement: any = document.getElementById(this.documentHelper.owner.containerId + '_option_search_text_box'); /* eslint-enable @typescript-eslint/no-explicit-any */ let text: string = inputElement.value; if (text === '') { return; } this.hideMatchDiv(); if (this.searchIcon.classList.contains('e-de-op-search-close-icon')) { this.searchIcon.classList.add('e-de-op-search-icon'); this.searchIcon.classList.remove('e-de-op-search-close-icon'); inputElement.value = ''; this.messageDiv.innerHTML = this.localeValue.getConstant('No matches'); this.resultContainer.style.display = 'block'; this.resultsListBlock.style.display = 'none'; this.matchDiv.style.display = 'none'; this.occurrenceDiv.style.display = 'none'; this.onEnableDisableReplaceButton(); this.clearFocusElement(); this.resultsListBlock.innerHTML = ''; this.clearSearchResultItems(); this.documentHelper.owner.searchModule.clearSearchHighlight(); this.viewer.renderVisiblePages(); return; } if (this.searchIcon.classList.contains('e-de-op-search-icon') && text.length >= 1) { this.searchIcon.classList.add('e-de-op-search-close-icon'); this.searchIcon.classList.remove('e-de-op-search-icon'); this.onEnableDisableReplaceButton(); } this.clearSearchResultItems(); this.documentHelper.owner.searchModule.clearSearchHighlight(); let patterns: RegExp = this.documentHelper.owner.searchModule.textSearch.stringToRegex(text, this.findOption); let endSelection: TextPosition = this.documentHelper.selection.end; let index: string = endSelection.getHierarchicalIndexInternal(); this.results = this.documentHelper.owner.searchModule.textSearch.findAll(patterns, this.findOption, index); if (this.results != null && this.results.length > 0) { let start: TextPosition = this.results.innerList[this.results.currentIndex].start; let end: TextPosition = this.results.innerList[this.results.currentIndex].end; this.documentHelper.scrollToPosition(start, end, true); this.navigateSearchResult(false); this.getMessageDivHeight(); let height: number = this.isOptionsPane ? 215 : 292; let resultsContainerHeight: number = this.documentHelper.owner.getDocumentEditorElement().offsetHeight - height; this.resultsListBlock.style.height = resultsContainerHeight + 'px'; } else { this.messageDiv.innerHTML = this.localeValue.getConstant('No matches'); this.resultContainer.style.display = 'block'; this.resultsListBlock.style.display = 'none'; this.clearFocusElement(); this.resultsListBlock.innerHTML = ''; } } /** * Fires on getting next results. * * @private * @returns {void} */ public navigateNextResultButtonClick = (): void => { if (document.getElementById(this.documentHelper.owner.containerId + '_list_box_container') != null && document.getElementById(this.documentHelper.owner.containerId + '_list_box_container').style.display !== 'none') { let selectionEnd: TextPosition = this.documentHelper.owner.selection.end; let nextResult: TextSearchResult; let currentIndex: number = 0; if (selectionEnd.isExistAfter(this.results.currentSearchResult.start)) { currentIndex = this.results.currentIndex; } for (let i: number = currentIndex; i < this.results.length; i++) { let result: TextSearchResult = this.results.innerList[i]; if (selectionEnd.isExistBefore(result.start) || selectionEnd.isAtSamePosition(result.start)) { nextResult = result; this.results.currentIndex = i; break; } } if (isNullOrUndefined(nextResult)) { this.results.currentIndex = 0; nextResult = this.results.innerList[0]; } this.messageDiv.innerHTML = this.localeValue.getConstant('Result') + ' ' + (this.results.currentIndex + 1) + ' ' + this.localeValue.getConstant('of') + ' ' + this.resultsListBlock.children.length; this.updateListItems(nextResult); this.focusedIndex = this.focusedElement.indexOf(this.navigateToNextResult); } } private updateListItems(textSearchResult: TextSearchResult): void { let searchElements: HTMLCollectionOf<Element> = this.resultsListBlock.getElementsByClassName('e-de-search-result-hglt'); for (let j: number = 0; j < searchElements.length; j++) { let list: HTMLElement = searchElements[j] as HTMLElement; classList(list, ['e-de-search-result-item'], ['e-de-search-result-hglt']); classList(list.children[0], [], ['e-de-op-search-word-text']); } let listElement: HTMLElement = this.resultsListBlock.children[this.results.currentIndex] as HTMLElement; classList(listElement, ['e-de-search-result-hglt'], ['e-de-search-result-item']); classList(listElement.children[0], ['e-de-op-search-word-text'], []); this.scrollToPosition(listElement); this.documentHelper.owner.searchModule.navigate(textSearchResult); this.documentHelper.owner.searchModule.highlight(this.results); } /** * Fires on getting previous results. * * @private * @returns {void} */ public navigatePreviousResultButtonClick = (): void => { if (document.getElementById(this.documentHelper.owner.containerId + '_list_box_container') != null && document.getElementById(this.documentHelper.owner.containerId + '_list_box_container').style.display !== 'none') { let previousResult: TextSearchResult; let selectionStart: TextPosition = this.documentHelper.owner.selection.start; let currentIndex: number = this.results.currentIndex; if (selectionStart.isExistAfter(this.results.currentSearchResult.start)) { currentIndex = this.results.length - 1; } for (let i: number = currentIndex; i >= 0; i--) { let result: TextSearchResult = this.results.innerList[i]; if (selectionStart.isExistAfter(result.start) || this.documentHelper.owner.selection.end.isAtSamePosition(result.start)) { previousResult = result; this.results.currentIndex = i; break; } } if (isNullOrUndefined(previousResult)) { this.results.currentIndex = this.results.length - 1; previousResult = this.results.innerList[this.results.currentIndex]; } this.messageDiv.innerHTML = this.localeValue.getConstant('Result') + ' ' + (this.results.currentIndex + 1) + ' ' + this.localeValue.getConstant('of') + ' ' + this.resultsListBlock.children.length; this.updateListItems(previousResult); this.focusedIndex = this.focusedElement.indexOf(this.navigateToPreviousResult); } } /** * Scrolls to position. * * @private * @param {HTMLElement} list - Specifies the list element. * @returns {void} */ public scrollToPosition(list: HTMLElement): void { let rect: ClientRect = list.getBoundingClientRect(); let top: number; if (rect.top > 0) { top = rect.top - list.parentElement.getBoundingClientRect().top; if ((list.parentElement.offsetHeight - top) <= list.offsetHeight) { if (Math.ceil(top + list.offsetHeight) === list.parentElement.scrollHeight) { list.parentElement.scrollTop = top; } list.parentElement.scrollTop = list.parentElement.scrollTop + (list.parentElement.offsetHeight / 100) * 30; } else if (top < 0) { list.parentElement.scrollTop = list.parentElement.scrollTop - (list.parentElement.offsetHeight / 100) * 30; } } else { list.parentElement.scrollTop = 0; } } /** * Fires on key down * * @private * @param {KeyboardEvent} event - Speficies key down actions. * @returns {void} */ public onKeyDown = (event: KeyboardEvent): void => { let code: number = event.which || event.keyCode; if (code === 13 && event.keyCode !== 9 && event.keyCode !== 40) { event.preventDefault(); this.findDiv.style.height = ''; this.onKeyDownInternal(); } else if (code === 8 && (this.searchInput.value.length === 0)) { this.resultContainer.style.display = 'block'; } else if (event.keyCode !== 9 && event.keyCode !== 40 && event.keyCode !== 27) { this.documentHelper.owner.searchModule.clearSearchHighlight(); this.clearSearchResultItems(); this.viewer.renderVisiblePages(); this.resultsListBlock.style.display = 'none'; this.messageDiv.innerHTML = this.localeValue.getConstant('No matches'); this.resultContainer.style.display = 'none'; this.clearFocusElement(); this.resultsListBlock.innerHTML = ''; if (this.searchIcon.classList.contains('e-de-op-search-close-icon')) { this.searchIcon.classList.add('e-de-op-search-icon'); this.searchIcon.classList.remove('e-de-op-search-close-icon'); } } else if (code === 27 && event.keyCode === 27) { this.showHideOptionsPane(false); } } /** * Clear the focus elements. * * @private * @returns {void} */ public clearFocusElement(): void { for (let i: number = 0; i < this.resultsListBlock.children.length; i++) { let index: number = this.focusedElement.indexOf(this.resultsListBlock.children[i] as HTMLElement); if (index !== -1) { this.focusedElement.splice(index, 1); } } this.focusedIndex = 1; } /** * Close the optios pane. * * @private * @returns {void} */ public close = (): void => { this.clearFocusElement(); this.showHideOptionsPane(false); this.resultsListBlock.innerHTML = ''; this.focusedIndex = 1; this.isOptionsPane = true; } /** * Fires on results list block. * * @private * @param {MouseEvent} args - Specifies which list was clicked. * @returns {void} */ public resultListBlockClick = (args: MouseEvent): void => { let currentlist: EventTarget = args.target; let element: HTMLCollection = this.resultsListBlock.children; let index: number = 0; for (let i: number = 0; i < element.length; i++) { let list: HTMLElement = element[i] as HTMLElement; if (list.classList.contains('e-de-search-result-hglt')) { list.classList.remove('e-de-search-result-hglt'); list.children[0].classList.remove('e-de-op-search-word-text'); list.classList.add('e-de-search-result-item'); } } let list: HTMLElement; for (let i: number = 0; i < element.length; i++) { if (currentlist === element[i]) { index = i; list = element[i] as HTMLElement; if (list.classList.contains('e-de-search-result-item')) { list.classList.remove('e-de-search-result-item'); list.classList.add('e-de-search-result-hglt'); list.children[0].classList.add('e-de-op-search-word-text'); this.focusedIndex = this.focusedElement.indexOf(list); } } } let currentelement: TextSearchResult = this.results.innerList[index]; this.results.currentIndex = index; this.messageDiv.innerHTML = this.localeValue.getConstant('Result') + ' ' + (index + 1) + ' ' + this.localeValue.getConstant('of') + ' ' + this.resultsListBlock.children.length; this.documentHelper.owner.searchModule.navigate(currentelement); this.documentHelper.owner.searchModule.highlight(this.results); if (list) { list.focus(); } } /** * Show or hide option pane based on boolean value. * * @private * @param {boolean} show - Specifies showing or hiding the options pane. * @returns {void} */ public showHideOptionsPane(show: boolean): void { if (!isNullOrUndefined(this.documentHelper.owner.selectionModule)) { if (show) { this.localeValue = new L10n('documenteditor', this.documentHelper.owner.defaultLocale); this.localeValue.setLocale(this.documentHelper.owner.locale); if (isNullOrUndefined(this.optionsPane)) { this.initOptionsPane(this.localeValue, this.documentHelper.owner.enableRtl); //Add Option Pane let isRtl: boolean = this.documentHelper.owner.enableRtl; let optionsPaneContainerStyle: string; if (isRtl) { optionsPaneContainerStyle = 'display:inline-flex;direction:rtl;'; } else { optionsPaneContainerStyle = 'display:inline-flex;'; } this.documentHelper.optionsPaneContainer.setAttribute('style', optionsPaneContainerStyle); this.documentHelper.optionsPaneContainer.insertBefore(this.documentHelper.owner.optionsPaneModule.optionsPane, this.documentHelper.viewerContainer); } this.optionsPane.style.display = 'block'; if (this.documentHelper.owner.isReadOnlyMode) { this.tabInstance.hideTab(1); } else { this.tabInstance.hideTab(1, false); } if (this.isReplace && !this.documentHelper.owner.isReadOnlyMode) { this.tabInstance.select(1); this.isReplace = false; this.isOptionsPane = false; } else { this.tabInstance.select(0); } this.searchDiv.innerHTML = this.localeValue.getConstant(this.searchText); this.isOptionsPaneShow = true; let textBox: HTMLInputElement = document.getElementById(this.documentHelper.owner.getDocumentEditorElement().id + '_option_search_text_box') as HTMLInputElement; let selectedText: string = this.documentHelper.owner.selection.text; if (!isNullOrUndefined(selectedText)) { let char: string[] = ['\v', '\r']; let index: number = HelperMethods.indexOfAny(selectedText, char); selectedText = index < 0 ? selectedText : selectedText.substring(0, index); } textBox.value = selectedText; textBox.select(); this.messageDiv.innerHTML = ''; if (this.searchIcon.classList.contains('e-de-op-search-close-icon')) { this.searchIcon.classList.add('e-de-op-search-icon'); this.searchIcon.classList.remove('e-de-op-search-close-icon'); } this.documentHelper.selection.caret.style.display = 'none'; this.focusedIndex = 1; this.focusedElement = []; if (this.isOptionsPane) { this.focusedElement.push(this.closeButton, this.searchInput, this.searchIcon, this.navigateToPreviousResult, this.navigateToNextResult, this.matchInput, this.wholeInput); } else { this.focusedElement.push(this.closeButton, this.searchInput, this.searchIcon, this.navigateToPreviousResult, this.navigateToNextResult, this.matchInput, this.wholeInput, this.replaceWith, this.replaceButton, this.replaceAllButton); } this.documentHelper.updateViewerSize(); } else { if (!isNullOrUndefined(this.optionsPane)) { this.clearSearchResultItems(); this.documentHelper.owner.searchModule.clearSearchHighlight(); this.isOptionsPaneShow = false; let resultListBox: HTMLElement = document.getElementById(this.documentHelper.owner.containerId + '_list_box_container'); let message: HTMLElement = document.getElementById(this.documentHelper.owner.containerId + '_search_status'); if (!isNullOrUndefined(resultListBox) && !isNullOrUndefined(message)) { resultListBox.style.display = 'none'; this.clearFocusElement(); resultListBox.innerHTML = ''; message.innerHTML = this.localeValue.getConstant('No matches'); } } this.documentHelper.updateViewerSize(); if (!isNullOrUndefined(this.optionsPane)) { if (this.optionsPane.style.display !== 'none') { this.documentHelper.selection.updateCaretPosition(); this.optionsPane.style.display = 'none'; } } this.documentHelper.updateFocus(); this.documentHelper.selection.caret.style.display = 'block'; } } } /** * Clears search results. * * @private * @returns {void} */ public clearSearchResultItems(): void { if (!isNullOrUndefined(this.documentHelper.owner.findResultsList)) { this.documentHelper.owner.findResultsList = []; } } /** * Dispose the internal objects which are maintained. * * @private * @returns {void} */ public destroy(): void { if (this.optionsPane) { this.optionsPane.innerHTML = ''; this.optionsPane = undefined; } if (this.resultsListBlock) { this.resultsListBlock.innerHTML = ''; this.resultsListBlock = undefined; } if (this.messageDiv) { this.messageDiv.innerHTML = ''; this.messageDiv = undefined; } if (this.resultContainer) { this.resultContainer.innerHTML = ''; } this.resultContainer = undefined; if (this.searchInput) { this.searchInput.value = ''; this.searchInput = undefined; } if (this.searchDiv) { this.searchDiv.innerHTML = ''; this.searchDiv = undefined; } if (this.searchTextBoxContainer) { this.searchTextBoxContainer.innerHTML = ''; this.searchTextBoxContainer = undefined; } if (this.replaceWith) { this.replaceWith.innerHTML = ''; this.replaceWith = undefined; } if (this.findDiv) { this.findDiv.innerHTML = ''; this.findDiv = undefined; } if (this.replaceButton) { this.replaceButton.innerHTML = ''; this.replaceButton = undefined; } if (this.replaceAllButton) { this.replaceAllButton.innerHTML = ''; this.replaceAllButton = undefined; } if (this.matchInput) { this.matchInput.innerHTML = ''; this.matchCase = undefined; } if (this.wholeInput) { this.wholeInput.innerHTML = ''; this.wholeWord = undefined; } // if (this.regularInput) { // this.regularInput.innerHTML = ''; // this.regular = undefined; // } if (!isNullOrUndefined(this.results)) { this.results.destroy(); } if (this.focusedElement) { this.focusedElement = []; } this.focusedElement = undefined; this.destroyInternal(); } /** * Dispose the internal objects which are maintained. * * @returns {void} */ private destroyInternal(): void { if (this.searchText) { this.searchText = undefined; } if (this.resultsText) { this.resultsText = undefined; } if (this.messageDivText) { this.messageDivText = undefined; } if (this.replaceButtonText) { this.replaceButtonText = undefined; } if (this.replaceAllButtonText) { this.replaceAllButtonText = undefined; } } }
the_stack
import { Injectable } from '@angular/core'; import { CoreSites } from '@services/sites'; import { CoreSite, CoreSiteWSPreSets } from '@classes/site'; import { CoreError } from '@classes/errors/error'; import { makeSingleton, Translate } from '@singletons'; import { CoreWSExternalWarning } from '@services/ws'; import { CoreCourses } from '@features/courses/services/courses'; const ROOT_CACHE_KEY = 'mmGroups:'; /* * Service to handle groups. */ @Injectable({ providedIn: 'root' }) export class CoreGroupsProvider { // Group mode constants. static readonly NOGROUPS = 0; static readonly SEPARATEGROUPS = 1; static readonly VISIBLEGROUPS = 2; /** * Check if group mode of an activity is enabled. * * @param cmId Course module ID. * @param siteId Site ID. If not defined, current site. * @param ignoreCache True if it should ignore cached data (it will always fail in offline or server down). * @return Promise resolved with true if the activity has groups, resolved with false otherwise. */ async activityHasGroups(cmId: number, siteId?: string, ignoreCache?: boolean): Promise<boolean> { try { const groupmode = await this.getActivityGroupMode(cmId, siteId, ignoreCache); return groupmode === CoreGroupsProvider.SEPARATEGROUPS || groupmode === CoreGroupsProvider.VISIBLEGROUPS; } catch (error) { return false; } } /** * Get the groups allowed in an activity. * * @param cmId Course module ID. * @param userId User ID. If not defined, use current user. * @param siteId Site ID. If not defined, current site. * @param ignoreCache True if it should ignore cached data (it will always fail in offline or server down). * @return Promise resolved when the groups are retrieved. */ async getActivityAllowedGroups( cmId: number, userId?: number, siteId?: string, ignoreCache?: boolean, ): Promise<CoreGroupGetActivityAllowedGroupsWSResponse> { const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); const params: CoreGroupGetActivityAllowedGroupsWSParams = { cmid: cmId, userid: userId, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getActivityAllowedGroupsCacheKey(cmId, userId), updateFrequency: CoreSite.FREQUENCY_RARELY, }; if (ignoreCache) { preSets.getFromCache = false; preSets.emergencyCache = false; } const response: CoreGroupGetActivityAllowedGroupsWSResponse = await site.read('core_group_get_activity_allowed_groups', params, preSets); if (!response || !response.groups) { throw new CoreError('Activity allowed groups not found.'); } return response; } /** * Get cache key for group mode WS calls. * * @param cmId Course module ID. * @param userId User ID. * @return Cache key. */ protected getActivityAllowedGroupsCacheKey(cmId: number, userId: number): string { return ROOT_CACHE_KEY + 'allowedgroups:' + cmId + ':' + userId; } /** * Get the groups allowed in an activity if they are allowed. * * @param cmId Course module ID. * @param userId User ID. If not defined, use current user. * @param siteId Site ID. If not defined, current site. * @param ignoreCache True if it should ignore cached data (it will always fail in offline or server down). * @return Promise resolved when the groups are retrieved. If not allowed, empty array will be returned. */ async getActivityAllowedGroupsIfEnabled(cmId: number, userId?: number, siteId?: string, ignoreCache?: boolean): Promise<CoreGroupGetActivityAllowedGroupsWSResponse> { siteId = siteId || CoreSites.getCurrentSiteId(); // Get real groupmode, in case it's forced by the course. const hasGroups = await this.activityHasGroups(cmId, siteId, ignoreCache); if (hasGroups) { // Get the groups available for the user. return this.getActivityAllowedGroups(cmId, userId, siteId, ignoreCache); } return { groups: [], }; } /** * Helper function to get activity group info (group mode and list of groups). * * @param cmId Course module ID. * @param addAllParts Deprecated. * @param userId User ID. If not defined, use current user. * @param siteId Site ID. If not defined, current site. * @param ignoreCache True if it should ignore cached data (it will always fail in offline or server down). * @return Promise resolved with the group info. */ async getActivityGroupInfo( cmId: number, addAllParts?: boolean, userId?: number, siteId?: string, ignoreCache?: boolean, ): Promise<CoreGroupInfo> { const groupInfo: CoreGroupInfo = { groups: [], defaultGroupId: 0, canAccessAllGroups: false, }; const groupMode = await this.getActivityGroupMode(cmId, siteId, ignoreCache); groupInfo.separateGroups = groupMode === CoreGroupsProvider.SEPARATEGROUPS; groupInfo.visibleGroups = groupMode === CoreGroupsProvider.VISIBLEGROUPS; let result: CoreGroupGetActivityAllowedGroupsWSResponse; if (groupInfo.separateGroups || groupInfo.visibleGroups) { result = await this.getActivityAllowedGroups(cmId, userId, siteId, ignoreCache); groupInfo.canAccessAllGroups = !!result.canaccessallgroups; } else { result = { groups: [], }; } if (result.groups.length <= 0) { groupInfo.separateGroups = false; groupInfo.visibleGroups = false; groupInfo.defaultGroupId = 0; } else { if (result.canaccessallgroups || groupInfo.visibleGroups) { groupInfo.groups!.push({ id: 0, name: Translate.instant('core.allparticipants') }); groupInfo.defaultGroupId = 0; } else { groupInfo.defaultGroupId = result.groups[0].id; } groupInfo.groups = groupInfo.groups!.concat(result.groups); } return groupInfo; } /** * Get the group mode of an activity. * * @param cmId Course module ID. * @param siteId Site ID. If not defined, current site. * @param ignoreCache True if it should ignore cached data (it will always fail in offline or server down). * @return Promise resolved when the group mode is retrieved. */ async getActivityGroupMode(cmId: number, siteId?: string, ignoreCache?: boolean): Promise<number> { const site = await CoreSites.getSite(siteId); const params: CoreGroupGetActivityGroupmodeWSParams = { cmid: cmId, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getActivityGroupModeCacheKey(cmId), updateFrequency: CoreSite.FREQUENCY_RARELY, }; if (ignoreCache) { preSets.getFromCache = false; preSets.emergencyCache = false; } const response: CoreGroupGetActivityGroupModeWSResponse = await site.read('core_group_get_activity_groupmode', params, preSets); if (!response || response.groupmode === undefined) { throw new CoreError('Activity group mode not found.'); } return response.groupmode; } /** * Get cache key for group mode WS calls. * * @param cmId Course module ID. * @return Cache key. */ protected getActivityGroupModeCacheKey(cmId: number): string { return ROOT_CACHE_KEY + 'groupmode:' + cmId; } /** * Get user groups in all the user enrolled courses. * * @param siteId Site to get the groups from. If not defined, use current site. * @return Promise resolved when the groups are retrieved. */ async getAllUserGroups(siteId?: string): Promise<CoreGroup[]> { const site = await CoreSites.getSite(siteId); siteId = siteId || site.getId(); if (site.isVersionGreaterEqualThan('3.6')) { return this.getUserGroupsInCourse(0, siteId); } const courses = <CoreCourseBase[]> await CoreCourses.getUserCourses(false, siteId); courses.push({ id: site.getSiteHomeId() }); // Add site home. return this.getUserGroups(courses, siteId); } /** * Get user groups in all the supplied courses. * * @param courses List of courses or course ids to get the groups from. * @param siteId Site to get the groups from. If not defined, use current site. * @param userId ID of the user. If not defined, use the userId related to siteId. * @return Promise resolved when the groups are retrieved. */ async getUserGroups(courses: CoreCourseBase[] | number[], siteId?: string, userId?: number): Promise<CoreGroup[]> { // Get all courses one by one. const promises = this.getCourseIds(courses).map((courseId) => this.getUserGroupsInCourse(courseId, siteId, userId)); const courseGroups = await Promise.all(promises); return (<CoreGroup[]>[]).concat(...courseGroups); } /** * Get user groups in a course. * * @param courseId ID of the course. 0 to get all enrolled courses groups (Moodle version > 3.6). * @param siteId Site to get the groups from. If not defined, use current site. * @param userId ID of the user. If not defined, use ID related to siteid. * @return Promise resolved when the groups are retrieved. */ async getUserGroupsInCourse(courseId: number, siteId?: string, userId?: number): Promise<CoreGroup[]> { const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); const data: CoreGroupGetCourseUserGroupsWSParams = { userid: userId, courseid: courseId, }; const preSets = { cacheKey: this.getUserGroupsInCourseCacheKey(courseId, userId), updateFrequency: CoreSite.FREQUENCY_RARELY, }; const response: CoreGroupGetCourseUserGroupsWSResponse = await site.read('core_group_get_course_user_groups', data, preSets); if (!response || !response.groups) { throw new CoreError('User groups in course not found.'); } return response.groups; } /** * Get prefix cache key for user groups in course WS calls. * * @return Prefix Cache key. */ protected getUserGroupsInCoursePrefixCacheKey(): string { return ROOT_CACHE_KEY + 'courseGroups:'; } /** * Get cache key for user groups in course WS calls. * * @param courseId Course ID. * @param userId User ID. * @return Cache key. */ protected getUserGroupsInCourseCacheKey(courseId: number, userId: number): string { return this.getUserGroupsInCoursePrefixCacheKey() + courseId + ':' + userId; } /** * Invalidates activity allowed groups. * * @param cmId Course module ID. * @param userId User ID. If not defined, use current user. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateActivityAllowedGroups(cmId: number, userId?: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); await site.invalidateWsCacheForKey(this.getActivityAllowedGroupsCacheKey(cmId, userId)); } /** * Invalidates activity group mode. * * @param cmId Course module ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateActivityGroupMode(cmId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getActivityGroupModeCacheKey(cmId)); } /** * Invalidates all activity group info: mode and allowed groups. * * @param cmId Course module ID. * @param userId User ID. If not defined, use current user. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateActivityGroupInfo(cmId: number, userId?: number, siteId?: string): Promise<void> { const promises = <Promise<void>[]>[]; promises.push(this.invalidateActivityAllowedGroups(cmId, userId, siteId)); promises.push(this.invalidateActivityGroupMode(cmId, siteId)); await Promise.all(promises); } /** * Invalidates user groups in all user enrolled courses. * * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateAllUserGroups(siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); if (site.isVersionGreaterEqualThan('3.6')) { return this.invalidateUserGroupsInCourse(0, siteId); } await site.invalidateWsCacheForKeyStartingWith(this.getUserGroupsInCoursePrefixCacheKey()); } /** * Invalidates user groups in courses. * * @param courses List of courses or course ids. * @param siteId Site ID. If not defined, current site. * @param userId User ID. If not defined, use current user. * @return Promise resolved when the data is invalidated. */ async invalidateUserGroups(courses: CoreCourseBase[] | number[], siteId?: string, userId?: number): Promise<void> { const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); const promises = this.getCourseIds(courses).map((courseId) => this.invalidateUserGroupsInCourse(courseId, site.id, userId)); await Promise.all(promises); } /** * Invalidates user groups in course. * * @param courseId ID of the course. 0 to get all enrolled courses groups (Moodle version > 3.6). * @param siteId Site ID. If not defined, current site. * @param userId User ID. If not defined, use current user. * @return Promise resolved when the data is invalidated. */ async invalidateUserGroupsInCourse(courseId: number, siteId?: string, userId?: number): Promise<void> { const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); await site.invalidateWsCacheForKey(this.getUserGroupsInCourseCacheKey(courseId, userId)); } /** * Validate a group ID. If the group is not visible by the user, it will return the first group ID. * * @param groupId Group ID to validate. * @param groupInfo Group info. * @return Group ID to use. */ validateGroupId(groupId = 0, groupInfo: CoreGroupInfo): number { if (groupId > 0 && groupInfo && groupInfo.groups && groupInfo.groups.length > 0) { // Check if the group is in the list of groups. if (groupInfo.groups.some((group) => groupId == group.id)) { return groupId; } } return groupInfo.defaultGroupId; } protected getCourseIds(courses: CoreCourseBase[] | number[]): number[] { return courses.length > 0 && typeof courses[0] === 'object' ? (courses as CoreCourseBase[]).map((course) => course.id) : courses as number[]; } } export const CoreGroups = makeSingleton(CoreGroupsProvider); /** * Specific group info. */ export type CoreGroup = { id: number; // Group ID. name: string; // Multilang compatible name, course unique'. description?: string; // Group description text. descriptionformat?: number; // Description format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN). idnumber?: string; // Id number. courseid?: number; // Coure Id. }; /** * Group info for an activity. */ export type CoreGroupInfo = { /** * List of groups. */ groups?: CoreGroup[]; /** * Whether it's separate groups. */ separateGroups?: boolean; /** * Whether it's visible groups. */ visibleGroups?: boolean; /** * The group ID to use by default. If all participants is visible, 0 will be used. First group ID otherwise. */ defaultGroupId: number; /** * Whether the user has the capability to access all groups in the context. */ canAccessAllGroups: boolean; }; /** * WS core_group_get_activity_allowed_groups response type. */ export type CoreGroupGetActivityAllowedGroupsWSResponse = { groups: CoreGroup[]; // List of groups. canaccessallgroups?: boolean; // Whether the user will be able to access all the activity groups. warnings?: CoreWSExternalWarning[]; }; /** * Params of core_group_get_activity_groupmode WS. */ type CoreGroupGetActivityGroupmodeWSParams = { cmid: number; // Course module id. }; /** * Result of WS core_group_get_activity_groupmode. */ export type CoreGroupGetActivityGroupModeWSResponse = { groupmode: number; // Group mode: 0 for no groups, 1 for separate groups, 2 for visible groups. warnings?: CoreWSExternalWarning[]; }; /** * Params of core_group_get_activity_allowed_groups WS. */ type CoreGroupGetActivityAllowedGroupsWSParams = { cmid: number; // Course module id. userid?: number; // Id of user, empty for current user. }; /** * Params of core_group_get_course_user_groups WS. */ type CoreGroupGetCourseUserGroupsWSParams = { courseid?: number; // Id of course (empty or 0 for all the courses where the user is enrolled). userid?: number; // Id of user (empty or 0 for current user). groupingid?: number; // Returns only groups in the specified grouping. }; /** * Result of WS core_group_get_course_user_groups. */ export type CoreGroupGetCourseUserGroupsWSResponse = { groups: { id: number; // Group record id. name: string; // Multilang compatible name, course unique. description: string; // Group description text. descriptionformat: number; // Description format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN). idnumber: string; // Id number. courseid?: number; // Course id. }[]; warnings?: CoreWSExternalWarning[]; };
the_stack
import { decrypt, decryptSafely, encrypt, encryptSafely, getEncryptionPublicKey, } from './encryption'; describe('encryption', function () { const bob = { ethereumPrivateKey: '7e5374ec2ef0d91761a6e72fdf8f6ac665519bfdf6da0a2329cf0d804514b816', encryptionPrivateKey: 'flN07C7w2Rdhpucv349qxmVRm/322gojKc8NgEUUuBY=', encryptionPublicKey: 'C5YMNdqE4kLgxQhJO1MfuQcHP5hjVSXzamzd/TxlR0U=', }; const secretMessage = 'My name is Satoshi Buterin'; const encryptedData = { version: 'x25519-xsalsa20-poly1305', nonce: '1dvWO7uOnBnO7iNDJ9kO9pTasLuKNlej', ephemPublicKey: 'FBH1/pAEHOOW14Lu3FWkgV3qOEcuL78Zy+qW1RwzMXQ=', ciphertext: 'f8kBcl/NCyf3sybfbwAKk/np2Bzt9lRVkZejr6uh5FgnNlH/ic62DZzy', }; it("Getting bob's encryptionPublicKey", async function () { const result = await getEncryptionPublicKey(bob.ethereumPrivateKey); expect(result).toBe(bob.encryptionPublicKey); }); // encryption test it("Alice encrypts message with bob's encryptionPublicKey", async function () { const result = await encrypt({ publicKey: bob.encryptionPublicKey, data: secretMessage, version: 'x25519-xsalsa20-poly1305', }); expect(result.ciphertext).toHaveLength(56); expect(result.ephemPublicKey).toHaveLength(44); expect(result.nonce).toHaveLength(32); expect(result.version).toBe('x25519-xsalsa20-poly1305'); }); // safe encryption test it("Alice encryptsSafely message with bob's encryptionPublicKey", async function () { const version = 'x25519-xsalsa20-poly1305'; const result = await encryptSafely({ publicKey: bob.encryptionPublicKey, data: secretMessage, version, }); expect(result.ciphertext).toHaveLength(2732); expect(result.ephemPublicKey).toHaveLength(44); expect(result.nonce).toHaveLength(32); expect(result.version).toBe('x25519-xsalsa20-poly1305'); }); // safe decryption test it('Bob decryptSafely message that Alice encryptSafely for him', async function () { const version = 'x25519-xsalsa20-poly1305'; const result = await encryptSafely({ publicKey: bob.encryptionPublicKey, data: secretMessage, version, }); const plaintext = decryptSafely({ encryptedData: result, privateKey: bob.ethereumPrivateKey, }); expect(plaintext).toBe(secretMessage); }); // decryption test it('Bob decrypts message that Alice sent to him', function () { const result = decrypt({ encryptedData, privateKey: bob.ethereumPrivateKey, }); expect(result).toBe(secretMessage); }); it('Decryption failed because version is wrong or missing', function () { const badVersionData = { version: 'x256k1-aes256cbc', nonce: '1dvWO7uOnBnO7iNDJ9kO9pTasLuKNlej', ephemPublicKey: 'FBH1/pAEHOOW14Lu3FWkgV3qOEcuL78Zy+qW1RwzMXQ=', ciphertext: 'f8kBcl/NCyf3sybfbwAKk/np2Bzt9lRVkZejr6uh5FgnNlH/ic62DZzy', }; expect(() => decrypt({ encryptedData: badVersionData, privateKey: bob.ethereumPrivateKey, }), ).toThrow('Encryption type/version not supported.'); }); it('Decryption failed because nonce is wrong or missing', function () { // encrypted data const badNonceData = { version: 'x25519-xsalsa20-poly1305', nonce: '', ephemPublicKey: 'FBH1/pAEHOOW14Lu3FWkgV3qOEcuL78Zy+qW1RwzMXQ=', ciphertext: 'f8kBcl/NCyf3sybfbwAKk/np2Bzt9lRVkZejr6uh5FgnNlH/ic62DZzy', }; expect(() => decrypt({ encryptedData: badNonceData, privateKey: bob.ethereumPrivateKey, }), ).toThrow('bad nonce size'); }); it('Decryption failed because ephemPublicKey is wrong or missing', function () { // encrypted data const badEphemData = { version: 'x25519-xsalsa20-poly1305', nonce: '1dvWO7uOnBnO7iNDJ9kO9pTasLuKNlej', ephemPublicKey: 'FFFF/pAEHOOW14Lu3FWkgV3qOEcuL78Zy+qW1RwzMXQ=', ciphertext: 'f8kBcl/NCyf3sybfbwAKk/np2Bzt9lRVkZejr6uh5FgnNlH/ic62DZzy', }; expect(() => decrypt({ encryptedData: badEphemData, privateKey: bob.ethereumPrivateKey, }), ).toThrow('Decryption failed.'); }); it('Decryption failed because cyphertext is wrong or missing', function () { // encrypted data const badEphemData = { version: 'x25519-xsalsa20-poly1305', nonce: '1dvWO7uOnBnO7iNDJ9kO9pTasLuKNlej', ephemPublicKey: 'FBH1/pAEHOOW14Lu3FWkgV3qOEcuL78Zy+qW1RwzMXQ=', ciphertext: 'ffffff/NCyf3sybfbwAKk/np2Bzt9lRVkZejr6uh5FgnNlH/ic62DZzy', }; expect(() => decrypt({ encryptedData: badEphemData, privateKey: bob.ethereumPrivateKey, }), ).toThrow('Decryption failed.'); }); describe('validation', function () { describe('encrypt', function () { it('should throw if passed null public key', function () { expect(() => encrypt({ publicKey: null, data: secretMessage, version: 'x25519-xsalsa20-poly1305', }), ).toThrow('Missing publicKey parameter'); }); it('should throw if passed undefined public key', function () { expect(() => encrypt({ publicKey: undefined, data: secretMessage, version: 'x25519-xsalsa20-poly1305', }), ).toThrow('Missing publicKey parameter'); }); it('should throw if passed null data', function () { expect(() => encrypt({ publicKey: bob.encryptionPublicKey, data: null, version: 'x25519-xsalsa20-poly1305', }), ).toThrow('Missing data parameter'); }); it('should throw if passed undefined data', function () { expect(() => encrypt({ publicKey: bob.encryptionPublicKey, data: undefined, version: 'x25519-xsalsa20-poly1305', }), ).toThrow('Missing data parameter'); }); it('should throw if passed null version', function () { expect(() => encrypt({ publicKey: bob.encryptionPublicKey, data: secretMessage, version: null, }), ).toThrow('Missing version parameter'); }); it('should throw if passed undefined version', function () { expect(() => encrypt({ publicKey: bob.encryptionPublicKey, data: secretMessage, version: undefined, }), ).toThrow('Missing version parameter'); }); }); describe('encryptSafely', function () { it('should throw if passed null public key', function () { expect(() => encryptSafely({ publicKey: null, data: secretMessage, version: 'x25519-xsalsa20-poly1305', }), ).toThrow('Missing publicKey parameter'); }); it('should throw if passed undefined public key', function () { expect(() => encryptSafely({ publicKey: undefined, data: secretMessage, version: 'x25519-xsalsa20-poly1305', }), ).toThrow('Missing publicKey parameter'); }); it('should throw if passed null data', function () { expect(() => encryptSafely({ publicKey: bob.encryptionPublicKey, data: null, version: 'x25519-xsalsa20-poly1305', }), ).toThrow('Missing data parameter'); }); it('should throw if passed undefined data', function () { expect(() => encryptSafely({ publicKey: bob.encryptionPublicKey, data: undefined, version: 'x25519-xsalsa20-poly1305', }), ).toThrow('Missing data parameter'); }); it('should throw if passed null version', function () { expect(() => encryptSafely({ publicKey: bob.encryptionPublicKey, data: secretMessage, version: null, }), ).toThrow('Missing version parameter'); }); it('should throw if passed undefined version', function () { expect(() => encryptSafely({ publicKey: bob.encryptionPublicKey, data: secretMessage, version: undefined, }), ).toThrow('Missing version parameter'); }); }); describe('decrypt', function () { it('should throw if passed null encrypted data', function () { expect(() => decrypt({ encryptedData: null, privateKey: bob.ethereumPrivateKey, }), ).toThrow('Missing encryptedData parameter'); }); it('should throw if passed undefined encrypted data', function () { expect(() => decrypt({ encryptedData: undefined, privateKey: bob.ethereumPrivateKey, }), ).toThrow('Missing encryptedData parameter'); }); it('should throw if passed null private key', function () { expect(() => decrypt({ encryptedData, privateKey: null, }), ).toThrow('Missing privateKey parameter'); }); it('should throw if passed undefined private key', function () { expect(() => decrypt({ encryptedData, privateKey: undefined, }), ).toThrow('Missing privateKey parameter'); }); }); describe('decryptSafely', function () { it('should throw if passed null encrypted data', function () { expect(() => decryptSafely({ encryptedData: null, privateKey: bob.ethereumPrivateKey, }), ).toThrow('Missing encryptedData parameter'); }); it('should throw if passed undefined encrypted data', function () { expect(() => decryptSafely({ encryptedData: undefined, privateKey: bob.ethereumPrivateKey, }), ).toThrow('Missing encryptedData parameter'); }); it('should throw if passed null private key', function () { expect(() => decryptSafely({ encryptedData, privateKey: null, }), ).toThrow('Missing privateKey parameter'); }); it('should throw if passed undefined private key', function () { expect(() => decryptSafely({ encryptedData, privateKey: undefined, }), ).toThrow('Missing privateKey parameter'); }); }); }); });
the_stack
import fs from 'fs-extra'; import * as path from 'path'; import R from 'ramda'; import semver from 'semver'; import { flatten } from 'lodash'; import { BitIds } from '../../bit-id'; import { COMPILER_ENV_TYPE, COMPONENT_DIST_PATH_TEMPLATE, COMPONENT_ORIGINS, TESTER_ENV_TYPE } from '../../constants'; import ShowDoctorError from '../../error/show-doctor-error'; import EnvExtension from '../../legacy-extensions/env-extension'; import logger from '../../logger/logger'; import { Scope } from '../../scope'; import getNodeModulesPathOfComponent from '../../utils/bit/component-node-modules-path'; import { getPathRelativeRegardlessCWD, PathLinuxRelative, pathNormalizeToLinux } from '../../utils/path'; import BitMap from '../bit-map/bit-map'; import ComponentMap, { ComponentOrigin } from '../bit-map/component-map'; import Component from '../component/consumer-component'; import PackageJsonFile from '../component/package-json-file'; import { PackageJsonTransformer } from '../component/package-json-transformer'; import { preparePackageJsonToWrite } from '../component/package-json-utils'; import DataToPersist from '../component/sources/data-to-persist'; import RemovePath from '../component/sources/remove-path'; import ComponentConfig from '../config/component-config'; import Consumer from '../consumer'; import { ArtifactVinyl } from '../component/sources/artifact'; import { ArtifactFiles, deserializeArtifactFiles, getArtifactFilesByExtension, } from '../component/sources/artifact-files'; export type ComponentWriterProps = { component: Component; writeToPath: PathLinuxRelative; writeConfig?: boolean; writePackageJson?: boolean; override?: boolean; isolated?: boolean; origin: ComponentOrigin; consumer: Consumer | undefined; scope?: Scope | undefined; bitMap: BitMap; ignoreBitDependencies?: boolean | BitIds; deleteBitDirContent?: boolean; existingComponentMap?: ComponentMap; excludeRegistryPrefix?: boolean; saveOnLane?: boolean; applyPackageJsonTransformers?: boolean; }; export default class ComponentWriter { component: Component; writeToPath: PathLinuxRelative; writeConfig: boolean; writePackageJson: boolean; override: boolean; isolated: boolean | undefined; origin: ComponentOrigin; consumer: Consumer | undefined; // when using capsule, the consumer is not defined scope?: Scope | undefined; bitMap: BitMap; ignoreBitDependencies: boolean | BitIds; deleteBitDirContent: boolean | undefined; existingComponentMap: ComponentMap | undefined; excludeRegistryPrefix: boolean; saveOnLane: boolean; applyPackageJsonTransformers: boolean; constructor({ component, writeToPath, writeConfig = false, writePackageJson = true, override = true, isolated = false, origin, consumer, scope = consumer?.scope, bitMap, ignoreBitDependencies = true, deleteBitDirContent, existingComponentMap, excludeRegistryPrefix = false, saveOnLane = false, applyPackageJsonTransformers = true, }: ComponentWriterProps) { this.component = component; this.writeToPath = writeToPath; this.writeConfig = writeConfig; this.writePackageJson = writePackageJson; this.override = override; this.isolated = isolated; this.origin = origin; this.consumer = consumer; this.scope = scope; this.bitMap = bitMap; this.ignoreBitDependencies = ignoreBitDependencies; this.deleteBitDirContent = deleteBitDirContent; this.existingComponentMap = existingComponentMap; this.excludeRegistryPrefix = excludeRegistryPrefix; this.saveOnLane = saveOnLane; this.applyPackageJsonTransformers = applyPackageJsonTransformers; } static getInstance(componentWriterProps: ComponentWriterProps): ComponentWriter { return new ComponentWriter(componentWriterProps); } /** * write the component to the filesystem and update .bitmap with the details. * * bitMap gets updated before writing the files to the filesystem, because as part of writing the * package-json file, the componentMap is needed to be stored with the updated version. * * when a component is not new, write the files according to the paths in .bitmap. */ async write(): Promise<Component> { if (!this.consumer) throw new Error('ComponentWriter.write expect to have a consumer'); await this.populateComponentsFilesToWrite(); this.component.dataToPersist.addBasePath(this.consumer.getPath()); await this.component.dataToPersist.persistAllToFS(); return this.component; } async populateComponentsFilesToWrite(packageManager?: string): Promise<Component> { if (!this.component.files || !this.component.files.length) { throw new ShowDoctorError(`Component ${this.component.id.toString()} is invalid as it has no files`); } this.throwForImportingLegacyIntoHarmony(); this.component.dataToPersist = new DataToPersist(); this._updateFilesBasePaths(); this.component.componentMap = this.existingComponentMap || this.addComponentToBitMap(this.writeToPath); this._copyFilesIntoDistsWhenDistsOutsideComponentDir(); this._determineWhetherToDeleteComponentDirContent(); await this._handlePreviouslyNestedCurrentlyImportedCase(); this._determineWhetherToWriteConfig(); this._updateComponentRootPathAccordingToBitMap(); this._updateBitMapIfNeeded(); await this._updateConsumerConfigIfNeeded(); this._determineWhetherToWritePackageJson(); await this.populateFilesToWriteToComponentDir(packageManager); if (this.isolated) await this.populateArtifacts(); return this.component; } private throwForImportingLegacyIntoHarmony() { if (this.component.isLegacy && this.consumer && !this.consumer.isLegacy) { throw new Error( `unable to write component "${this.component.id.toString()}", it is a legacy component and this workspace is Harmony` ); } } async populateFilesToWriteToComponentDir(packageManager?: string) { if (this.deleteBitDirContent) { this.component.dataToPersist.removePath(new RemovePath(this.writeToPath)); } this.component.files.forEach((file) => (file.override = this.override)); this.component.files.map((file) => this.component.dataToPersist.addFile(file)); const dists = await this.component.dists.getDistsToWrite(this.component, this.bitMap, this.consumer, false); if (dists) this.component.dataToPersist.merge(dists); // TODO: change to new eject config // if (this.writeConfig && this.consumer) { // const configToWrite = await this.component.getConfigToWrite(this.consumer, this.bitMap); // this.component.dataToPersist.merge(configToWrite.dataToPersist); // } // make sure the project's package.json is not overridden by Bit // If a consumer is of isolated env it's ok to override the root package.json (used by the env installation // of compilers / testers / extensions) if ( this.writePackageJson && (this.isolated || (this.consumer && this.consumer.isolated) || this.writeToPath !== '.') ) { const artifactsDir = this.getArtifactsDir(); const { packageJson, distPackageJson } = preparePackageJsonToWrite( this.bitMap, this.component, artifactsDir || this.writeToPath, this.override, this.ignoreBitDependencies, this.excludeRegistryPrefix, packageManager, Boolean(this.isolated) ); const componentConfig = ComponentConfig.fromComponent(this.component); // @todo: temporarily this is running only when there is no version (or version is "latest") // so then package.json always has a valid version. we'll need to figure out when the version // needs to be incremented and when it should not. if ((!this.consumer || this.consumer.isolated) && !this.component.id.hasVersion()) { // this only needs to be done in an isolated // or consumerless (dependency in an isolated) environment packageJson.addOrUpdateProperty('version', this._getNextPatchVersion()); } componentConfig.setCompiler(this.component.compiler ? this.component.compiler.toBitJsonObject() : {}); componentConfig.setTester(this.component.tester ? this.component.tester.toBitJsonObject() : {}); packageJson.addOrUpdateProperty('bit', componentConfig.toPlainObject()); if ((!this.consumer?.isLegacy || !this.scope?.isLegacy) && this.applyPackageJsonTransformers) { await this._applyTransformers(this.component, packageJson); } this._mergeChangedPackageJsonProps(packageJson); this._mergePackageJsonPropsFromOverrides(packageJson); this.component.dataToPersist.addFile(packageJson.toVinylFile()); if (distPackageJson) this.component.dataToPersist.addFile(distPackageJson.toVinylFile()); this.component.packageJsonFile = packageJson; } // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! if (this.component.license && this.component.license.contents) { this.component.license.updatePaths({ newBase: this.writeToPath }); // $FlowFixMe this.component.license is set this.component.license.override = this.override; // $FlowFixMe this.component.license is set // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! this.component.dataToPersist.addFile(this.component.license); } } /** * currently, it writes all artifacts. * later, this responsibility might move to pkg extension, which could write only artifacts * that are set in package.json.files[], to have a similar structure of a package. */ private async populateArtifacts() { if (!this.scope) { // when capsules are written via the workspace, do not write artifacts, they get created by // build-pipeline. when capsules are written via the scope, we do need the dists. return; } const extensionsNamesForArtifacts = ['teambit.compilation/compiler']; const artifactsFiles = flatten( extensionsNamesForArtifacts.map((extName) => getArtifactFilesByExtension(this.component.extensions, extName)) ); const scope = this.scope; const artifactsVinylFlattened: ArtifactVinyl[] = []; await Promise.all( artifactsFiles.map(async (artifactFiles) => { if (!artifactFiles) return; if (!(artifactFiles instanceof ArtifactFiles)) { artifactFiles = deserializeArtifactFiles(artifactFiles); } // fyi, if this is coming from the isolator aspect, it is optimized to import all at once. // see artifact-files.importMultipleDistsArtifacts(). const vinylFiles = await artifactFiles.getVinylsAndImportIfMissing(this.component.scope as string, scope); artifactsVinylFlattened.push(...vinylFiles); }) ); const artifactsDir = this.getArtifactsDir(); if (artifactsDir) { artifactsVinylFlattened.forEach((a) => a.updatePaths({ newBase: artifactsDir })); } this.component.dataToPersist.addManyFiles(artifactsVinylFlattened); } private getArtifactsDir() { // @todo: decide whether new components are allowed to be imported to a legacy workspace // if not, remove the "this.consumer.isLegacy" part in the condition below if (!this.consumer || this.consumer.isLegacy || this.component.isLegacy) return this.component.writtenPath; if (this.origin === COMPONENT_ORIGINS.NESTED) return this.component.writtenPath; return getNodeModulesPathOfComponent({ ...this.component, id: this.component.id, allowNonScope: true }); } addComponentToBitMap(rootDir: string | undefined): ComponentMap { const filesForBitMap = this.component.files.map((file) => { // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! return { name: file.basename, relativePath: pathNormalizeToLinux(file.relative), test: file.test }; }); return this.bitMap.addComponent({ componentId: this.component.id, files: filesForBitMap, mainFile: pathNormalizeToLinux(this.component.mainFile), rootDir, origin: this.origin, trackDir: this.existingComponentMap && this.existingComponentMap.trackDir, originallySharedDir: this.component.originallySharedDir, wrapDir: this.component.wrapDir, onLanesOnly: this.saveOnLane, }); } /** * these changes were entered manually by a user via `overrides` key */ _mergePackageJsonPropsFromOverrides(packageJson: PackageJsonFile) { const valuesToMerge = this.component.overrides.componentOverridesPackageJsonData; packageJson.mergePackageJsonObject(valuesToMerge); } /** * these are changes made by aspects */ async _applyTransformers(component: Component, packageJson: PackageJsonFile) { return PackageJsonTransformer.applyTransformers(component, packageJson); } /** * these are changes done by a compiler */ _mergeChangedPackageJsonProps(packageJson: PackageJsonFile) { if (!this.component.packageJsonChangedProps) return; const valuesToMerge = this._replaceDistPathTemplateWithCalculatedDistPath(packageJson); packageJson.mergePackageJsonObject(valuesToMerge); } /** * see https://github.com/teambit/bit/issues/1808 for more info why it's needed */ _replaceDistPathTemplateWithCalculatedDistPath(packageJson: PackageJsonFile): Record<string, any> { // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! const packageJsonChangedProps: Record<string, any> = this.component.packageJsonChangedProps; const isReplaceNeeded = R.values(packageJsonChangedProps).some((val) => val.includes(COMPONENT_DIST_PATH_TEMPLATE)); if (!isReplaceNeeded) { return packageJsonChangedProps; } const distRootDir = this.component.dists.getDistDir(this.consumer, this.writeToPath || '.'); const distRelativeToPackageJson = getPathRelativeRegardlessCWD( path.dirname(packageJson.filePath), // $FlowFixMe distRootDir ); return Object.keys(packageJsonChangedProps).reduce((acc, key) => { const val = packageJsonChangedProps[key].replace(COMPONENT_DIST_PATH_TEMPLATE, distRelativeToPackageJson); acc[key] = val; return acc; }, {}); } _copyFilesIntoDistsWhenDistsOutsideComponentDir() { if (!this.consumer) return; // not relevant when consumer is not available if (!this.consumer.shouldDistsBeInsideTheComponent() && this.component.dists.isEmpty()) { // since the dists are set to be outside the components dir, the source files must be saved there // otherwise, other components in dists won't be able to link to this component this.component.copyFilesIntoDists(); } } _updateComponentRootPathAccordingToBitMap() { // $FlowFixMe this.component.componentMap is set // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! this.writeToPath = this.component.componentMap.getRootDir(); this.component.writtenPath = this.writeToPath; this._updateFilesBasePaths(); } /** * when there is componentMap, this component (with this version or other version) is already part of the project. * There are several options as to what was the origin before and what is the origin now and according to this, * we update/remove/don't-touch the record in bit.map. * 1) current origin is AUTHORED - If the version is the same as before, don't update bit.map. Otherwise, update. * 2) current origin is IMPORTED - If the version is the same as before, don't update bit.map. Otherwise, update. * 3) current origin is NESTED - If it was not NESTED before, don't update. */ _updateBitMapIfNeeded() { if (this.isolated) return; if (this.consumer?.isLegacy) { // this logic is not needed in Harmony, and we can't just remove the component as it may have // lanes data const componentMapExistWithSameVersion = this.bitMap.isExistWithSameVersion(this.component.id); if (componentMapExistWithSameVersion) { if ( this.existingComponentMap && // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! this.existingComponentMap !== COMPONENT_ORIGINS.NESTED && this.origin === COMPONENT_ORIGINS.NESTED ) { return; } this.bitMap.removeComponent(this.component.id); } } // @ts-ignore this.component.componentMap is set this.component.componentMap = this.addComponentToBitMap(this.component.componentMap.rootDir); } async _updateConsumerConfigIfNeeded() { // for authored components there is no bit.json/package.json component specific // so if the overrides or envs were changed, it should be written to the consumer-config const areEnvsChanged = async (): Promise<boolean> => { // $FlowFixMe this.component.componentMap is set // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! const context = { componentDir: this.component?.componentMap?.getComponentDir() }; const compilerFromConsumer = this.consumer ? await this.consumer.getEnv(COMPILER_ENV_TYPE, context) : undefined; const testerFromConsumer = this.consumer ? await this.consumer.getEnv(TESTER_ENV_TYPE, context) : undefined; const compilerFromComponent = this.component.compiler ? this.component.compiler.toModelObject() : undefined; const testerFromComponent = this.component.tester ? this.component.tester.toModelObject() : undefined; return ( EnvExtension.areEnvsDifferent( compilerFromConsumer ? compilerFromConsumer.toModelObject() : undefined, compilerFromComponent ) || EnvExtension.areEnvsDifferent( testerFromConsumer ? testerFromConsumer.toModelObject() : undefined, testerFromComponent ) ); }; if (this.component.componentMap?.origin === COMPONENT_ORIGINS.AUTHORED && this.consumer) { const envsChanged = await areEnvsChanged(); const componentsConfig = this.consumer?.config?.componentsConfig; componentsConfig?.updateOverridesIfChanged(this.component, envsChanged); } } _determineWhetherToWriteConfig() { // $FlowFixMe this.component.componentMap is set // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! if (this.component.componentMap.origin === COMPONENT_ORIGINS.AUTHORED) { this.writeConfig = false; } } /** * don't write the package.json for an authored component, because its dependencies are managed * by the root package.json */ _determineWhetherToWritePackageJson() { this.writePackageJson = this.writePackageJson && this.origin !== COMPONENT_ORIGINS.AUTHORED; } /** * when a user imports a component that was a dependency before, write the component directly * into the components directory for an easy access/change. Then, remove the current record from * bit.map and add an updated one. */ async _handlePreviouslyNestedCurrentlyImportedCase() { if (!this.consumer) return; // $FlowFixMe this.component.componentMap is set // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! if (this.origin === COMPONENT_ORIGINS.IMPORTED && this.component.componentMap.origin === COMPONENT_ORIGINS.NESTED) { await this._cleanOldNestedComponent(); this.component.componentMap = this.addComponentToBitMap(this.writeToPath); } } /** * For IMPORTED component we have to delete the content of the directory before importing. * Otherwise, when the author adds new files outside of the previous originallySharedDir and this user imports them * the environment will contain both copies, the old one with the old originallySharedDir and the new one. * If a user made changes to the imported component, it will show a warning and stop the process. */ _determineWhetherToDeleteComponentDirContent() { if (typeof this.deleteBitDirContent === 'undefined') { this.deleteBitDirContent = this.origin === COMPONENT_ORIGINS.IMPORTED; } } _updateFilesBasePaths() { const newBase = this.writeToPath || '.'; this.component.files.forEach((file) => file.updatePaths({ newBase })); if (!this.component.dists.isEmpty()) { this.component.dists.get().forEach((dist) => dist.updatePaths({ newBase })); } } async _cleanOldNestedComponent() { if (!this.consumer) throw new Error('ComponentWriter._cleanOldNestedComponent expect to have a consumer'); // $FlowFixMe this function gets called when it was previously NESTED, so the rootDir is set // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! const oldLocation = path.join(this.consumer.getPath(), this.component.componentMap.rootDir); logger.debugAndAddBreadCrumb( 'component-writer._cleanOldNestedComponent', 'deleting the old directory of a component at {oldLocation}', { oldLocation } ); await fs.remove(oldLocation); await this._removeNodeModulesLinksFromDependents(); this.bitMap.removeComponent(this.component.id); } async _removeNodeModulesLinksFromDependents() { if (!this.consumer) { throw new Error('ComponentWriter._removeNodeModulesLinksFromDependents expect to have a consumer'); } const directDependentIds = await this.consumer.getAuthoredAndImportedDependentsIdsOf([this.component]); await Promise.all( directDependentIds.map((dependentId) => { const dependentComponentMap = this.consumer ? this.consumer.bitMap.getComponent(dependentId) : null; const relativeLinkPath = this.consumer ? getNodeModulesPathOfComponent(this.component) : null; const nodeModulesLinkAbs = this.consumer && dependentComponentMap && relativeLinkPath ? this.consumer.toAbsolutePath(path.join(dependentComponentMap.getRootDir(), relativeLinkPath)) : null; if (nodeModulesLinkAbs) { logger.debug(`deleting an obsolete link to node_modules at ${nodeModulesLinkAbs}`); } return nodeModulesLinkAbs ? fs.remove(nodeModulesLinkAbs) : Promise.resolve(); }) ); } _getNextPatchVersion() { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return semver.inc(this.component.version!, 'prerelease') || '0.0.1-0'; } }
the_stack
import { EventEmitter } from '@angular/core'; import { Observable, throwError, forkJoin, NEVER, of } from 'rxjs'; import { map, tap } from 'rxjs/operators'; import { ODataEntityResource, ODataNavigationPropertyResource, ODataPropertyResource, ODataOptions, ODataEntityAnnotations, ODataEntity, Select, Expand, EntityKey, OptionHandler, ODataQueryArguments, ODataQueryArgumentsOptions, } from '../resources/index'; import { ODataCollection } from './collection'; import { Objects, Types, Strings } from '../utils'; import { ODataStructuredType } from '../schema'; import { ModelOptions, ODataModelEvent, ODataModelOptions, ODataModelRelation, ODataModelResource, ODataModelField, INCLUDE_DEEP, INCLUDE_SHALLOW, } from './options'; // @dynamic export class ODataModel<T> { // Properties static options: ModelOptions; static meta: ODataModelOptions<any>; static buildMeta<T>(options: ModelOptions, schema: ODataStructuredType<T>) { this.meta = new ODataModelOptions<T>(options, schema); } // Parent _parent: | [ ODataModel<any> | ODataCollection<any, ODataModel<any>>, ODataModelField<any> | null ] | null = null; _attributes: { [name: string]: any } = {}; _changes: { [name: string]: any } = {}; _relations: { [name: string]: ODataModelRelation<any> } = {}; _resource?: ODataModelResource<T>; _annotations!: ODataEntityAnnotations; _resetting: boolean = false; _silent: boolean = false; _meta: ODataModelOptions<T>; // Events events$ = new EventEmitter<ODataModelEvent<T>>(); constructor( data: Partial<T> | { [name: string]: any } = {}, { parent, resource, annots, reset = false, }: { parent?: [ ODataModel<any> | ODataCollection<any, ODataModel<any>>, ODataModelField<any> | null ]; resource?: ODataModelResource<T>; annots?: ODataEntityAnnotations; reset?: boolean; } = {} ) { const Klass = this.constructor as typeof ODataModel; if (Klass.meta === undefined) throw new Error(`Can't create model without metadata`); this._meta = Klass.meta; this._meta.bind(this, { parent, resource, annots }); // Client Id (<any>this)[this._meta.cid] = (<any>data)[this._meta.cid] || Strings.uniqueId(`${Klass.meta.schema.name.toLowerCase()}-`); let attrs = this.annots().attributes<T>(data, 'full'); let defaults = this.defaults(); this.assign(Objects.merge(defaults, attrs), { reset }); } get [Symbol.toStringTag]() { return 'Model'; } equals(other: ODataModel<T>) { const thisKey = this.key(); const otherKey = other.key(); return ( this === other || (typeof this === typeof other && ((<any>this)[this._meta.cid] === (<any>other)[this._meta.cid] || (thisKey !== undefined && otherKey !== undefined && Types.isEqual(thisKey, otherKey)))) ); } //#region Resources resource(): ODataModelResource<T> { return ODataModelOptions.resource<T>(this) as ODataModelResource<T>; } navigationProperty<N>(name: string): ODataNavigationPropertyResource<N> { const field = this._meta.field(name); if (field === undefined || !field.navigation) throw Error(`Can't find navigation property ${name}`); const resource = this.resource(); if (!(resource instanceof ODataEntityResource) || !resource.hasKey()) throw Error("Can't get navigation without ODataEntityResource with key"); return field.resourceFactory<T, N>( resource ) as ODataNavigationPropertyResource<N>; } property<N>(name: string): ODataPropertyResource<N> { const field = this._meta.field(name); if (field === undefined || field.navigation) throw Error(`Can't find property ${name}`); const resource = this.resource(); if (!(resource instanceof ODataEntityResource) || !resource.hasKey()) throw Error("Can't get property without ODataEntityResource with key"); return field.resourceFactory<T, N>(resource) as ODataPropertyResource<N>; } attach(resource: ODataModelResource<T>) { return this._meta.attach(this, resource); } //#endregion schema() { return this._meta.schema; } annots() { return this._annotations; } key({ field_mapping = false, resolve = true, }: { field_mapping?: boolean; resolve?: boolean } = {}): | EntityKey<T> | { [name: string]: any } | undefined { return this._meta.resolveKey(this, { field_mapping, resolve }); } isNew() { return this.key() === undefined; } isParentOf( child: ODataModel<any> | ODataCollection<any, ODataModel<any>> ): boolean { return ( child !== this && ODataModelOptions.chain(child).some((p) => p[0] === this) ); } referential( field: ODataModelField<any>, { field_mapping = false, resolve = true, }: { field_mapping?: boolean; resolve?: boolean } = {} ): { [name: string]: any } | undefined { return this._meta.resolveReferential(this, field, { field_mapping, resolve, }); } referenced( field: ODataModelField<any>, { field_mapping = false, resolve = true, }: { field_mapping?: boolean; resolve?: boolean } = {} ): { [name: string]: any } | undefined { return this._meta.resolveReferenced(this, field, { field_mapping, resolve, }); } // Validation _errors?: { [key: string]: any }; protected validate({ method, navigation = false, }: { method?: 'create' | 'update' | 'modify'; navigation?: boolean; } = {}) { return this._meta.validate(this, { method, navigation }); } isValid({ method, navigation = false, }: { method?: 'create' | 'update' | 'modify'; navigation?: boolean; } = {}): boolean { this._errors = this.validate({ method, navigation }); if (this._errors !== undefined) this.events$.emit( new ODataModelEvent('invalid', { model: this, value: this._errors, options: { method }, }) ); return this._errors === undefined; } protected defaults() { return this._meta.defaults() || {}; } toEntity({ client_id = false, include_navigation = false, include_concurrency = false, include_computed = false, include_key = true, include_non_field = false, changes_only = false, field_mapping = false, chain = [], }: { client_id?: boolean; include_navigation?: boolean; include_concurrency?: boolean; include_computed?: boolean; include_key?: boolean; include_non_field?: boolean; changes_only?: boolean; field_mapping?: boolean; chain?: (ODataModel<any> | ODataCollection<any, ODataModel<any>>)[]; } = {}): T | { [name: string]: any } { return this._meta.toEntity(this, { client_id, include_navigation, include_concurrency, include_computed, include_key, include_non_field, changes_only, field_mapping, chain, }); } attributes({ changes_only = false, include_concurrency = false, include_computed = false, include_non_field = false, field_mapping = false, }: { changes_only?: boolean; include_concurrency?: boolean; include_computed?: boolean; include_non_field?: boolean; field_mapping?: boolean; } = {}): { [name: string]: any } { return this._meta.attributes(this, { changes_only, include_concurrency, include_computed, include_non_field, field_mapping, }); } set(path: string | string[], value: any) { const pathArray = ( Types.isArray(path) ? path : (path as string).match(/([^[.\]])+/g) ) as any[]; if (pathArray.length === 0) return undefined; if (pathArray.length > 1) { const model = (<any>this)[pathArray[0]]; return model.set(pathArray.slice(1), value); } if (pathArray.length === 1) { return ((<any>this)[pathArray[0]] = value); } } get(path: string | string[]): any { const pathArray = ( Types.isArray(path) ? path : (path as string).match(/([^[.\]])+/g) ) as any[]; if (pathArray.length === 0) return undefined; const value = (<any>this)[pathArray[0]]; if ( pathArray.length > 1 && (value instanceof ODataModel || value instanceof ODataCollection) ) { return value.get(pathArray.slice(1)); } return value; } reset({ path, silent = false, }: { path?: string | string[]; silent?: boolean } = {}) { const pathArray: string[] = ( path === undefined ? [] : Types.isArray(path) ? path : (path as string).match(/([^[.\]])+/g) ) as any[]; const name = pathArray[0]; const value = name !== undefined ? (<any>this)[name] : undefined; if ( ODataModelOptions.isModel(value) || ODataModelOptions.isCollection(value) ) { value.reset({ path: pathArray.slice(1), silent }); } else { this._meta.reset(this, { name: pathArray[0], silent }); } } assign( entity: Partial<T> | { [name: string]: any }, { reset = false, silent = false, }: { reset?: boolean; silent?: boolean } = {} ) { return this._meta.assign(this, entity, { reset, silent }); } clone<M extends ODataModel<T>>() { let Ctor = <typeof ODataModel>this.constructor; return new Ctor(this.toEntity(INCLUDE_SHALLOW), { resource: this.resource() as ODataModelResource<T>, annots: this.annots(), }) as M; } private _request(obs$: Observable<ODataEntity<any>>): Observable<this> { this.events$.emit( new ODataModelEvent('request', { model: this, options: { observable: obs$ }, }) ); return obs$.pipe( map(({ entity, annots }) => { this._annotations = annots; this.assign(annots.attributes<T>(entity || {}, 'full'), { reset: true, }); this.events$.emit( new ODataModelEvent('sync', { model: this, options: { entity, annots }, }) ); return this; }) ); } fetch({ ...options }: ODataOptions & { options?: ODataOptions; } = {}): Observable<this> { let resource = this.resource(); if (resource === undefined) return throwError('fetch: Resource is undefined'); let obs$: Observable<ODataEntity<T>>; if (resource instanceof ODataEntityResource) { if (!resource.hasKey()) return throwError("fetch: Can't fetch model without key"); obs$ = resource.fetch(options); } else if (resource instanceof ODataNavigationPropertyResource) { obs$ = resource.fetch({ responseType: 'entity', ...options }); } else { obs$ = (resource as ODataPropertyResource<T>).fetch({ responseType: 'entity', ...options, }); } return this._request(obs$); } save({ method, navigation = false, validate = true, ...options }: ODataOptions & { method?: 'create' | 'update' | 'modify'; navigation?: boolean; validate?: boolean; options?: ODataOptions; } = {}): Observable<this> { let resource = this.resource(); if (resource === undefined) return throwError('save: Resource is undefined'); if ( !( resource instanceof ODataEntityResource || resource instanceof ODataNavigationPropertyResource ) ) return throwError( 'save: Resource type ODataEntityResource/ODataNavigationPropertyResource needed' ); // Resolve method and resource key if (method === undefined && this.schema().isCompoundKey()) return throwError( 'save: Composite key require a specific method, use create/update/modify' ); method = method || (!resource.hasKey() ? 'create' : 'update'); if ( resource instanceof ODataEntityResource && (method === 'update' || method === 'modify') && !resource.hasKey() ) return throwError('save: Update/Patch require entity key'); if ( resource instanceof ODataNavigationPropertyResource || method === 'create' ) resource.clearKey(); let obs$: Observable<ODataEntity<any>>; if (!validate || this.isValid({ method, navigation })) { const _entity = this.toEntity({ changes_only: method === 'modify', field_mapping: true, include_concurrency: true, include_navigation: navigation, }) as T; obs$ = ( method === 'create' ? resource.create(_entity, options) : method === 'modify' ? resource.modify(_entity, { etag: this.annots().etag, ...options }) : resource.update(_entity, { etag: this.annots().etag, ...options }) ).pipe( map(({ entity, annots }) => ({ entity: entity || _entity, annots })) ); } else { obs$ = throwError(this._errors); } return this._request(obs$); } destroy({ ...options }: ODataOptions & { options?: ODataOptions; } = {}): Observable<this> { let resource = this.resource(); if (resource === undefined) return throwError('destroy: Resource is undefined'); if ( !( resource instanceof ODataEntityResource || resource instanceof ODataNavigationPropertyResource ) ) return throwError( 'destroy: Resource type ODataEntityResource/ODataNavigationPropertyResource needed' ); if (!resource.hasKey()) return throwError("destroy: Can't destroy model without key"); const _entity = this.toEntity({ field_mapping: true }) as T; const obs$ = resource .destroy({ etag: this.annots().etag, ...options }) .pipe( map(({ entity, annots }) => ({ entity: entity || _entity, annots })) ); return this._request(obs$).pipe( tap(() => this.events$.emit(new ODataModelEvent('destroy', { model: this })) ) ); } /** * Create an execution context for change the internal query of a resource * @param func Function to execute */ query( func: (q: { select(opts?: Select<T>): OptionHandler<Select<T>>; expand(opts?: Expand<T>): OptionHandler<Expand<T>>; format(opts?: string): OptionHandler<string>; apply(query: ODataQueryArguments<T>): void; }) => void ) { return this._meta.query(this, this.resource(), func) as this; } /** * Perform a check on the internal state of the model and return true if the model is changed. * @param include_navigation Check in navigation properties * @returns true if the model has changed, false otherwise */ hasChanged({ include_navigation = false, }: { include_navigation?: boolean } = {}) { return this._meta.hasChanged(this, { include_navigation }); } /** * Create an execution context for a given function, where the model is bound to its entity endpoint * @param ctx Context function * @returns The result of the context */ asEntity<R>(ctx: (model: this) => R): R { return this._meta.asEntity(this, ctx); } protected callFunction<P, R>( name: string, params: P | null, responseType: 'property' | 'model' | 'collection' | 'none', { ...options }: {} & ODataQueryArgumentsOptions<R> = {} ): Observable<R | ODataModel<R> | ODataCollection<R, ODataModel<R>> | null> { const resource = this.resource(); if (!(resource instanceof ODataEntityResource) || !resource.hasKey()) return throwError( "Can't call function without ODataEntityResource with key" ); const func = resource.function<P, R>(name); func.query.apply(options); switch (responseType) { case 'property': return func.callProperty(params, options); case 'model': return func.callModel(params, options); case 'collection': return func.callCollection(params, options); default: return func.call(params, { responseType, ...options }); } } protected callAction<P, R>( name: string, params: P | null, responseType: 'property' | 'model' | 'collection' | 'none', { ...options }: {} & ODataQueryArgumentsOptions<R> = {} ): Observable<R | ODataModel<R> | ODataCollection<R, ODataModel<R>> | null> { const resource = this.resource(); if (!(resource instanceof ODataEntityResource) || !resource.hasKey()) return throwError( "Can't call action without ODataEntityResource with key" ); const action = resource.action<P, R>(name); action.query.apply(options); switch (responseType) { case 'property': return action.callProperty(params, options); case 'model': return action.callModel(params, options); case 'collection': return action.callCollection(params, options); default: return action.call(params, { responseType, ...options }); } } // Cast protected cast<S>(type: string): ODataModel<S> { const resource = this.resource(); if (!(resource instanceof ODataEntityResource)) throw new Error( `Can't cast to derived model without ODataEntityResource` ); return resource .cast<S>(type) .asModel(this.toEntity(INCLUDE_DEEP), { annots: this.annots() }); } protected fetchNavigationProperty<S>( name: string, responseType: 'model' | 'collection', { ...options }: {} & ODataQueryArgumentsOptions<S> = {} ): Observable<ODataModel<S> | ODataCollection<S, ODataModel<S>> | null> { const nav = this.navigationProperty<S>( name ) as ODataNavigationPropertyResource<S>; nav.query.apply(options); switch (responseType) { case 'model': return nav.fetchModel(options); case 'collection': return nav.fetchCollection(options); } } // Get Value protected getValue<P>( name: string, options?: ODataOptions ): Observable<P | ODataModel<P> | ODataCollection<P, ODataModel<P>> | null> { const field = this._meta.field(name); if (field === undefined || field.navigation) throw Error(`Can't find property ${name}`); let value = (this as any)[name] as | P | ODataModel<P> | ODataCollection<P, ODataModel<P>>; if (value === undefined) { const prop = field.resourceFactory( this.resource() ) as ODataPropertyResource<P>; return field.collection ? prop .fetchCollection(options) .pipe(tap((c) => this.assign({ [name]: c }, { silent: true }))) : field.isStructuredType() ? prop .fetchModel(options) .pipe(tap((c) => this.assign({ [name]: c }, { silent: true }))) : prop .fetchProperty(options) .pipe(tap((c) => this.assign({ [name]: c }, { silent: true }))); } return of(value as P); } // Set Reference protected setReference<P>( name: string, model: ODataModel<P> | ODataCollection<P, ODataModel<P>> | null, options?: ODataOptions ): Observable<this> { const reference = ( this.navigationProperty<P>(name) as ODataNavigationPropertyResource<P> ).reference(); const etag = this.annots().etag; let obs$ = NEVER as Observable<any>; if (model instanceof ODataModel) { obs$ = reference.set( model._meta.entityResource(model) as ODataEntityResource<P>, { etag, ...options } ); } else if (model instanceof ODataCollection) { obs$ = forkJoin( model .models() .map((m) => reference.add( m._meta.entityResource(m) as ODataEntityResource<P>, options ) ) ); } else if (model === null) { obs$ = reference.unset({ etag, ...options }); } this.events$.emit( new ODataModelEvent('request', { model: this, options: { observable: obs$ }, }) ); return obs$.pipe( map((model) => { this.assign({ [name]: model }); this.events$.emit(new ODataModelEvent('sync', { model: this })); return this; }) ); } protected getReference<P>( name: string ): ODataModel<P> | ODataCollection<P, ODataModel<P>> { const field = this._meta.field(name); if (field === undefined || !field.navigation) throw Error(`Can't find navigation property ${name}`); let model = (this as any)[name] as | ODataModel<P> | ODataCollection<P, ODataModel<P>>; if (model === undefined) { const value = field.collection ? [] : this.referenced(field); model = field.modelCollectionFactory<T, P>({ parent: this, value }); (this as any)[name] = model; } return model; } }
the_stack
import { AcEntity } from '../../angular-cesium/models/ac-entity'; import { EditPoint } from './edit-point'; import { EditPolyline } from './edit-polyline'; import { AcLayerComponent } from '../../angular-cesium/components/ac-layer/ac-layer.component'; import { Cartesian3 } from '../../angular-cesium/models/cartesian3'; import { CoordinateConverter } from '../../angular-cesium/services/coordinate-converter/coordinate-converter.service'; import { PointProps } from './point-edit-options'; import { PolylineEditOptions, PolylineProps } from './polyline-edit-options'; import { GeoUtilsService } from '../../angular-cesium/services/geo-utils/geo-utils.service'; import { defaultLabelProps, LabelProps } from './label-props'; export class EditablePolyline extends AcEntity { private positions: EditPoint[] = []; private polylines: EditPolyline[] = []; private movingPoint: EditPoint; private doneCreation = false; private _enableEdit = true; private _pointProps: PointProps; private polylineProps: PolylineProps; private lastDraggedToPosition: any; private _labels: LabelProps[] = []; constructor(private id: string, private pointsLayer: AcLayerComponent, private polylinesLayer: AcLayerComponent, private coordinateConverter: CoordinateConverter, private editOptions: PolylineEditOptions, positions?: Cartesian3[]) { super(); this._pointProps = {...editOptions.pointProps}; this.props = {...editOptions.polylineProps}; if (positions && positions.length >= 2) { this.createFromExisting(positions); } } get labels(): LabelProps[] { return this._labels; } set labels(labels: LabelProps[]) { if (!labels) { return; } const positions = this.getRealPositions(); this._labels = labels.map((label, index) => { if (!label.position) { label.position = positions[index]; } return Object.assign({}, defaultLabelProps, label); }); } get props(): PolylineProps { return this.polylineProps; } set props(value: PolylineProps) { this.polylineProps = value; } get pointProps(): PointProps { return this._pointProps; } set pointProps(value: PointProps) { this._pointProps = value; } get enableEdit() { return this._enableEdit; } set enableEdit(value: boolean) { this._enableEdit = value; this.positions.forEach(point => { point.show = value; this.updatePointsLayer(false, point); }); } private createFromExisting(positions: Cartesian3[]) { positions.forEach((position) => { this.addPointFromExisting(position); }); this.addAllVirtualEditPoints(); this.doneCreation = true; } setManually(points: { position: Cartesian3, pointProp?: PointProps }[] | Cartesian3[], polylineProps?: PolylineProps) { if (!this.doneCreation) { throw new Error('Update manually only in edit mode, after polyline is created'); } this.positions.forEach(p => this.pointsLayer.remove(p.getId())); const newPoints: EditPoint[] = []; for (let i = 0; i < points.length; i++) { const pointOrCartesian: any = points[i]; let newPoint = null; if (pointOrCartesian.pointProps) { newPoint = new EditPoint(this.id, pointOrCartesian.position, pointOrCartesian.pointProps); } else { newPoint = new EditPoint(this.id, pointOrCartesian, this._pointProps); } newPoints.push(newPoint); } this.positions = newPoints; this.polylineProps = polylineProps ? polylineProps : this.polylineProps; this.updatePointsLayer(true, ...this.positions); this.addAllVirtualEditPoints(); } private addAllVirtualEditPoints() { const currentPoints = [...this.positions]; currentPoints.forEach((pos, index) => { if (index !== currentPoints.length - 1) { const currentPoint = pos; const nextIndex = (index + 1) % (currentPoints.length); const nextPoint = currentPoints[nextIndex]; const midPoint = this.setMiddleVirtualPoint(currentPoint, nextPoint); this.updatePointsLayer(false, midPoint); } }); } private setMiddleVirtualPoint(firstP: EditPoint, secondP: EditPoint): EditPoint { const midPointCartesian3 = Cesium.Cartesian3.lerp(firstP.getPosition(), secondP.getPosition(), 0.5, new Cesium.Cartesian3()); const midPoint = new EditPoint(this.id, midPointCartesian3, this._pointProps); midPoint.setVirtualEditPoint(true); const firstIndex = this.positions.indexOf(firstP); this.positions.splice(firstIndex + 1, 0, midPoint); return midPoint; } private updateMiddleVirtualPoint(virtualEditPoint: EditPoint, prevPoint: EditPoint, nextPoint: EditPoint) { const midPointCartesian3 = Cesium.Cartesian3.lerp(prevPoint.getPosition(), nextPoint.getPosition(), 0.5, new Cesium.Cartesian3()); virtualEditPoint.setPosition(midPointCartesian3); } changeVirtualPointToRealPoint(point: EditPoint) { point.setVirtualEditPoint(false); // actual point becomes a real point const pointsCount = this.positions.length; const pointIndex = this.positions.indexOf(point); const nextIndex = (pointIndex + 1) % (pointsCount); const preIndex = ((pointIndex - 1) + pointsCount) % pointsCount; const nextPoint = this.positions[nextIndex]; const prePoint = this.positions[preIndex]; const firstMidPoint = this.setMiddleVirtualPoint(prePoint, point); const secMidPoint = this.setMiddleVirtualPoint(point, nextPoint); this.updatePointsLayer(false, firstMidPoint, secMidPoint, point); } private renderPolylines() { this.polylines.forEach(polyline => this.polylinesLayer.remove(polyline.getId())); this.polylines = []; const realPoints = this.positions.filter(point => !point.isVirtualEditPoint()); realPoints.forEach((point, index) => { if (index !== realPoints.length - 1) { const nextIndex = (index + 1); const nextPoint = realPoints[nextIndex]; const polyline = new EditPolyline(this.id, point.getPosition(), nextPoint.getPosition(), this.polylineProps); this.polylines.push(polyline); this.polylinesLayer.update(polyline, polyline.getId()); } }); } addPointFromExisting(position: Cartesian3) { const newPoint = new EditPoint(this.id, position, this._pointProps); this.positions.push(newPoint); this.updatePointsLayer(true, newPoint); } addPoint(position: Cartesian3) { if (this.doneCreation) { return; } const isFirstPoint = !this.positions.length; if (isFirstPoint) { const firstPoint = new EditPoint(this.id, position, this._pointProps); this.positions.push(firstPoint); this.updatePointsLayer(true, firstPoint); } this.movingPoint = new EditPoint(this.id, position.clone(), this._pointProps); this.positions.push(this.movingPoint); this.updatePointsLayer(true, this.movingPoint); } movePointFinish(editPoint: EditPoint) { if (this.editOptions.clampHeightTo3D) { editPoint.props.disableDepthTestDistance = Number.POSITIVE_INFINITY; this.updatePointsLayer(false, editPoint); } } movePoint(toPosition: Cartesian3, editPoint: EditPoint) { editPoint.setPosition(toPosition); if (this.doneCreation) { if (editPoint.props.disableDepthTestDistance && this.editOptions.clampHeightTo3D) { // To avoid bug with pickPosition() on point with disableDepthTestDistance editPoint.props.disableDepthTestDistance = undefined; return; // ignore first move because the pickPosition() could be wrong } if (editPoint.isVirtualEditPoint()) { this.changeVirtualPointToRealPoint(editPoint); } const pointsCount = this.positions.length; const pointIndex = this.positions.indexOf(editPoint); if (pointIndex < this.positions.length - 1) { const nextVirtualPoint = this.positions[(pointIndex + 1) % (pointsCount)]; const nextRealPoint = this.positions[(pointIndex + 2) % (pointsCount)]; this.updateMiddleVirtualPoint(nextVirtualPoint, editPoint, nextRealPoint); } if (pointIndex > 0) { const prevVirtualPoint = this.positions[((pointIndex - 1) + pointsCount) % pointsCount]; const prevRealPoint = this.positions[((pointIndex - 2) + pointsCount) % pointsCount]; this.updateMiddleVirtualPoint(prevVirtualPoint, editPoint, prevRealPoint); } } this.updatePointsLayer(true, editPoint); } moveTempMovingPoint(toPosition: Cartesian3) { if (this.movingPoint) { this.movePoint(toPosition, this.movingPoint); } } moveShape(startMovingPosition: Cartesian3, draggedToPosition: Cartesian3) { if (!this.doneCreation) { return; } if (!this.lastDraggedToPosition) { this.lastDraggedToPosition = startMovingPosition; } const delta = GeoUtilsService.getPositionsDelta(this.lastDraggedToPosition, draggedToPosition); this.positions.forEach(point => { const newPos = GeoUtilsService.addDeltaToPosition(point.getPosition(), delta, true); point.setPosition(newPos); }); this.updatePointsLayer(true, ...this.positions); this.lastDraggedToPosition = draggedToPosition; } endMoveShape() { this.lastDraggedToPosition = undefined; this.updatePointsLayer(true, ...this.positions); } removePoint(pointToRemove: EditPoint) { this.removePosition(pointToRemove); this.positions .filter(p => p.isVirtualEditPoint()) .forEach(p => this.removePosition(p)); this.addAllVirtualEditPoints(); this.renderPolylines(); } addLastPoint(position: Cartesian3) { this.doneCreation = true; this.removePosition(this.movingPoint); // remove movingPoint this.movingPoint = null; this.addAllVirtualEditPoints(); } getRealPositions(): Cartesian3[] { return this.getRealPoints() .map(position => position.getPosition()); } getRealPoints(): EditPoint[] { return this.positions .filter(position => !position.isVirtualEditPoint() && position !== this.movingPoint); } getPoints(): EditPoint[] { return this.positions.filter(position => position !== this.movingPoint); } getPositions(): Cartesian3[] { return this.positions.map(position => position.getPosition()); } getPositionsCallbackProperty(): Cartesian3[] { return new Cesium.CallbackProperty(this.getPositions.bind(this), false); } private removePosition(point: EditPoint) { const index = this.positions.findIndex((p) => p === point); if (index < 0) { return; } this.positions.splice(index, 1); this.pointsLayer.remove(point.getId()); } private updatePointsLayer(renderPolylines = true, ...point: EditPoint[]) { if (renderPolylines) { this.renderPolylines(); } point.forEach(p => this.pointsLayer.update(p, p.getId())); } update() { this.updatePointsLayer(); } dispose() { this.positions.forEach(editPoint => { this.pointsLayer.remove(editPoint.getId()); }); this.polylines.forEach(line => this.polylinesLayer.remove(line.getId())); if (this.movingPoint) { this.pointsLayer.remove(this.movingPoint.getId()); this.movingPoint = undefined; } this.positions.length = 0; } getPointsCount(): number { return this.positions.length; } getId() { return this.id; } }
the_stack
import objectPath from 'object-path'; import { createRxDocumentConstructor, basePrototype } from '../rx-document'; import { createDocCache } from '../doc-cache'; import { newRxError, newRxTypeError } from '../rx-error'; import { flatClone, getFromMapOrThrow } from '../util'; import type { RxChangeEvent, RxCollection, RxDatabase, RxDocument, RxDocumentWriteData, RxLocalDocumentData, RxPlugin, RxStorageKeyObjectInstance } from '../types'; import { isRxDatabase } from '../rx-database'; import { isRxCollection } from '../rx-collection'; import { filter, map, distinctUntilChanged, startWith, mergeMap } from 'rxjs/operators'; import { Observable } from 'rxjs'; import { findLocalDocument, writeSingleLocal } from '../rx-storage-helper'; import { overwritable } from '../overwritable'; const DOC_CACHE_BY_PARENT = new WeakMap(); const _getDocCache = (parent: any) => { if (!DOC_CACHE_BY_PARENT.has(parent)) { DOC_CACHE_BY_PARENT.set( parent, createDocCache() ); } return DOC_CACHE_BY_PARENT.get(parent); }; const CHANGE_SUB_BY_PARENT = new WeakMap(); const _getChangeSub = (parent: any) => { if (!CHANGE_SUB_BY_PARENT.has(parent)) { const sub = parent.$ .pipe( filter(cE => (cE as RxChangeEvent<any>).isLocal) ) .subscribe((cE: RxChangeEvent<any>) => { const docCache = _getDocCache(parent); const doc = docCache.get(cE.documentId); if (doc) { doc._handleChangeEvent(cE); } }); parent._subs.push(sub); CHANGE_SUB_BY_PARENT.set( parent, sub ); } return CHANGE_SUB_BY_PARENT.get(parent); }; const RxDocumentParent = createRxDocumentConstructor() as any; export class RxLocalDocument extends RxDocumentParent { constructor( public readonly id: string, jsonData: any, public readonly parent: RxCollection | RxDatabase ) { super(null, jsonData); } } function _getKeyObjectStorageInstanceByParent(parent: any): RxStorageKeyObjectInstance<any, any> { if (isRxDatabase(parent)) { return (parent as RxDatabase<{}>).localDocumentsStore; // database } else { return (parent as RxCollection).localDocumentsStore; // collection } } const RxLocalDocumentPrototype: any = { get isLocal() { return true; }, // // overwrites // _handleChangeEvent( this: any, changeEvent: RxChangeEvent ) { if (changeEvent.documentId !== this.primary) { return; } switch (changeEvent.operation) { case 'UPDATE': const newData = changeEvent.documentData; this._dataSync$.next(newData); break; case 'DELETE': // remove from docCache to assure new upserted RxDocuments will be a new instance const docCache = _getDocCache(this.parent); docCache.delete(this.primary); this._isDeleted$.next(true); break; } }, get allAttachments$() { // this is overwritten here because we cannot re-set getters on the prototype throw newRxError('LD1', { document: this }); }, get primaryPath() { return 'id'; }, get primary() { return this.id; }, get $() { return (this as RxDocument)._dataSync$.asObservable(); }, $emit(this: any, changeEvent: RxChangeEvent) { return this.parent.$emit(changeEvent); }, get(this: RxDocument, objPath: string) { if (!this._data) { return undefined; } if (typeof objPath !== 'string') { throw newRxTypeError('LD2', { objPath }); } let valueObj = objectPath.get(this._data, objPath); valueObj = overwritable.deepFreezeWhenDevMode(valueObj); return valueObj; }, get$(this: RxDocument, path: string) { if (path.includes('.item.')) { throw newRxError('LD3', { path }); } if (path === this.primaryPath) throw newRxError('LD4'); return this._dataSync$ .pipe( map(data => objectPath.get(data, path)), distinctUntilChanged() ); }, set(this: RxDocument, objPath: string, value: any) { if (!value) { // object path not set, overwrite whole data const data: any = flatClone(objPath); data._rev = this._data._rev; this._data = data; return this; } if (objPath === '_id') { throw newRxError('LD5', { objPath, value }); } if (Object.is(this.get(objPath), value)) { return; } objectPath.set(this._data, objPath, value); return this; }, _saveData(this: RxLocalDocument, newData: RxLocalDocumentData) { const oldData = this._dataSync$.getValue(); const storageInstance = _getKeyObjectStorageInstanceByParent(this.parent); newData._id = this.id; return storageInstance.bulkWrite([{ previous: oldData, document: newData }]) .then((res) => { const docResult = res.success.get(newData._id); if (!docResult) { throw getFromMapOrThrow(res.error, newData._id); } newData._rev = docResult._rev; }); }, remove(this: any): Promise<void> { const storageInstance = _getKeyObjectStorageInstanceByParent(this.parent); const writeData: RxDocumentWriteData<{ _id: string }> = { _id: this.id, _deleted: true, _attachments: {} }; return writeSingleLocal(storageInstance, { previous: this._data, document: writeData }) .then(() => { _getDocCache(this.parent).delete(this.id); }); } }; let INIT_DONE = false; const _init = () => { if (INIT_DONE) return; else INIT_DONE = true; // add functions of RxDocument const docBaseProto = basePrototype; const props = Object.getOwnPropertyNames(docBaseProto); props.forEach(key => { const exists = Object.getOwnPropertyDescriptor(RxLocalDocumentPrototype, key); if (exists) return; const desc: any = Object.getOwnPropertyDescriptor(docBaseProto, key); Object.defineProperty(RxLocalDocumentPrototype, key, desc); }); /** * overwrite things that not work on local documents * with throwing function */ const getThrowingFun = (k: string) => () => { throw newRxError('LD6', { functionName: k }); }; [ 'populate', 'update', 'putAttachment', 'getAttachment', 'allAttachments' ].forEach((k: string) => RxLocalDocumentPrototype[k] = getThrowingFun(k)); }; RxLocalDocument.create = (id: string, data: any, parent: any) => { _init(); _getChangeSub(parent); const newDoc = new RxLocalDocument(id, data, parent); newDoc.__proto__ = RxLocalDocumentPrototype; _getDocCache(parent).set(id, newDoc); return newDoc; }; /** * save the local-document-data * throws if already exists */ function insertLocal( this: RxDatabase | RxCollection, id: string, docData: any ): Promise<RxLocalDocument> { if (isRxCollection(this) && this._isInMemory) { return (this as any).parentCollection.insertLocal(id, docData); } return (this as any).getLocal(id) .then((existing: any) => { if (existing) { throw newRxError('LD7', { id, data: docData }); } // create new one docData = flatClone(docData); docData._id = id; return writeSingleLocal( _getKeyObjectStorageInstanceByParent(this), { document: docData } ).then(res => { docData._rev = res._rev; const newDoc = RxLocalDocument.create(id, docData, this); return newDoc; }); }); } /** * save the local-document-data * overwrites existing if exists */ function upsertLocal(this: any, id: string, data: any): Promise<RxLocalDocument> { if (isRxCollection(this) && this._isInMemory) { return this._parentCollection.upsertLocal(id, data); } return this.getLocal(id) .then((existing: RxDocument) => { if (!existing) { // create new one const docPromise = this.insertLocal(id, data); return docPromise; } else { // update existing data._rev = existing._data._rev; return existing.atomicUpdate(() => data).then(() => existing); } }); } function getLocal(this: any, id: string): Promise<RxLocalDocument | null> { if (isRxCollection(this) && this._isInMemory) { return this.parentCollection.getLocal(id); } const storageInstance = _getKeyObjectStorageInstanceByParent(this); const docCache = _getDocCache(this); // check in doc-cache const found = docCache.get(id); if (found) { return Promise.resolve(found); } // if not found, check in storage instance return findLocalDocument(storageInstance, id) .then((docData) => { if (!docData) { return null; } const doc = RxLocalDocument.create(id, docData, this); return doc; }) .catch(() => null); } function getLocal$(this: RxCollection, id: string): Observable<RxLocalDocument | null> { return this.$.pipe( startWith(null), mergeMap(async (cE: RxChangeEvent | null) => { if (cE) { return { changeEvent: cE }; } else { const doc = await this.getLocal(id); return { doc: doc }; } }), mergeMap(async (changeEventOrDoc) => { if (changeEventOrDoc.changeEvent) { const cE = changeEventOrDoc.changeEvent; if (!cE.isLocal || cE.documentId !== id) { return { use: false }; } else { const doc = await this.getLocal(id); return { use: true, doc: doc }; } } else { return { use: true, doc: changeEventOrDoc.doc }; } }), filter(filterFlagged => filterFlagged.use), map(filterFlagged => { return filterFlagged.doc; }) ); } export const RxDBLocalDocumentsPlugin: RxPlugin = { name: 'local-documents', rxdb: true, prototypes: { RxCollection: (proto: any) => { proto.insertLocal = insertLocal; proto.upsertLocal = upsertLocal; proto.getLocal = getLocal; proto.getLocal$ = getLocal$; }, RxDatabase: (proto: any) => { proto.insertLocal = insertLocal; proto.upsertLocal = upsertLocal; proto.getLocal = getLocal; proto.getLocal$ = getLocal$; } }, overwritable: {} };
the_stack
import React, { useEffect, useState } from 'react'; import { I18nManager, LayoutChangeEvent, StatusBarAnimation, StyleProp, StyleSheet, ViewStyle, Keyboard, StatusBar, } from 'react-native'; import { DrawerKeyboardDismissMode, DrawerLockMode, DrawerPosition, DrawerType, GestureDetector, Gesture, } from 'react-native-gesture-handler'; import Animated, { runOnJS, useAnimatedStyle, useDerivedValue, useSharedValue, withSpring, } from 'react-native-reanimated'; export enum BetterDrawerState { IDLE = 'Idle', DRAGGING = 'Dragging', SETTLING = 'Settling', } export interface BetterDrawerLayoutProps { /** * This attribute is present in the standard implementation already and is one * of the required params. Gesture handler version of DrawerLayout make it * possible for the function passed as `renderNavigationView` to take an * Animated value as a parameter that indicates the progress of drawer * opening/closing animation (progress value is 0 when closed and 1 when * opened). This can be used by the drawer component to animated its children * while the drawer is opening or closing. */ renderNavigationView: ( progressAnimatedValue: Animated.SharedValue<number> ) => React.ReactNode; drawerPosition?: DrawerPosition; drawerWidth?: number; drawerBackgroundColor?: string; drawerLockMode?: DrawerLockMode; keyboardDismissMode?: DrawerKeyboardDismissMode; /** * Called when the drawer is closed. */ onDrawerClose?: () => void; /** * Called when the drawer is opened. */ onDrawerOpen?: () => void; /** * Called when the status of the drawer changes. */ onDrawerStateChanged?: ( newState: BetterDrawerState, drawerWillShow: boolean ) => void; drawerType?: DrawerType; /** * Defines how far from the edge of the content view the gesture should * activate. */ edgeWidth?: number; minSwipeDistance?: number; /** * When set to true Drawer component will use * {@link https://reactnative.dev/docs/statusbar StatusBar} API to hide the OS * status bar whenever the drawer is pulled or when its in an "open" state. */ hideStatusBar?: boolean; /** * @default 'slide' * * Can be used when hideStatusBar is set to true and will select the animation * used for hiding/showing the status bar. See * {@link https://reactnative.dev/docs/statusbar StatusBar} documentation for * more details */ statusBarAnimation?: StatusBarAnimation; /** * @default black * * Color of a semi-transparent overlay to be displayed on top of the content * view when drawer gets open. A solid color should be used as the opacity is * added by the Drawer itself and the opacity of the overlay is animated (from * 0% to 70%). */ overlayColor?: string; contentContainerStyle?: StyleProp<ViewStyle>; drawerContainerStyle?: StyleProp<ViewStyle>; /** * Enables two-finger gestures on supported devices, for example iPads with * trackpads. If not enabled the gesture will require click + drag, with * `enableTrackpadTwoFingerGesture` swiping with two fingers will also trigger * the gesture. */ enableTrackpadTwoFingerGesture?: boolean; /** * Called when the pan gesture gets updated, position represents a fraction of * the drawer that is visible */ onDrawerSlide?: (position: number) => void; children?: React.ReactNode; } interface OverlayProps { drawerType: DrawerType; color: string; progress: Animated.SharedValue<number>; lockMode: DrawerLockMode; close: () => void; } function Overlay(props: OverlayProps) { const overlayStyle = useAnimatedStyle(() => ({ backgroundColor: props.color, opacity: props.progress.value, transform: [ { translateX: // when the overlay should not be visible move it off the screen // to prevent it from intercepting touch events on Android props.drawerType !== 'front' || props.progress.value === 0 ? 10000 : 0, }, ], })); const tap = Gesture.Tap(); tap.onEnd((_event, success) => { 'worklet'; if (success && props.lockMode !== 'locked-open') { // close the drawer when tapped on the overlay only if the gesture // was not cancelled and it's not locked in opened state props.close(); } }); return ( <GestureDetector gesture={tap}> <Animated.View style={[styles.overlay, overlayStyle]} /> </GestureDetector> ); } export interface DrawerLayoutController { open: () => void; close: () => void; } export const DrawerLayout = React.forwardRef< DrawerLayoutController, BetterDrawerLayoutProps >( ( { drawerWidth = 200, drawerPosition = 'left', drawerType = 'front', edgeWidth = 20, minSwipeDistance = 3, overlayColor = 'rgba(0, 0, 0, 0.7)', drawerLockMode = 'unlocked', enableTrackpadTwoFingerGesture = false, keyboardDismissMode, statusBarAnimation, hideStatusBar, drawerBackgroundColor, drawerContainerStyle, contentContainerStyle, children, renderNavigationView, onDrawerClose, onDrawerOpen, onDrawerSlide, onDrawerStateChanged, }: BetterDrawerLayoutProps, ref ) => { const animationConfig = { damping: 30, stiffness: 250 }; const fromLeft = drawerPosition === 'left'; const drawerSlide = drawerType !== 'back'; const containerSlide = drawerType !== 'front'; // setting NaN as a starting value allows to tell when the value gets changes // for the first time const [containerWidth, setContainerWidth] = useState(Number.NaN); const [drawerVisible, setDrawerVisible] = useState(false); const drawerState = useSharedValue(BetterDrawerState.IDLE); // between 0 and drawerWidth (drawer on the left) or -drawerWidth and 0 (drawer on the right) const drawerOffset = useSharedValue(0); // stores value of the offset at the start of the gesture const drawerSavedOffset = useSharedValue(0); // stores the translation that is supposed to be ignored (user tried to // drag while animation was running) const ignoredOffset = useSharedValue(0); // stores the x coordinate of the drag starting point (to ignore dragging on the overlay) const dragStartPosition = useSharedValue(0); // between 0 and 1, 0 - closed, 1 - opened const openingProgress = useDerivedValue(() => { if (fromLeft) { return drawerOffset.value / drawerWidth; } else { return -drawerOffset.value / drawerWidth; } }, [drawerOffset, containerWidth, drawerWidth, fromLeft]); // we rely on row and row-reverse flex directions to position the drawer // properly. Apparently for RTL these are flipped which requires us to use // the opposite setting for the drawer to appear from left or right // according to the drawerPosition prop const reverseContentDirection = I18nManager.isRTL ? fromLeft : !fromLeft; // set the drawer to closed position when the props change to prevent it from // opening or moving on the screen useEffect(() => { drawerOffset.value = 0; drawerSavedOffset.value = 0; setDrawerVisible(false); // eslint-disable-next-line react-hooks/exhaustive-deps }, [drawerWidth, drawerPosition, drawerType]); // measure the container function handleContainerLayout({ nativeEvent }: LayoutChangeEvent) { setContainerWidth(nativeEvent.layout.width); } function onDragStart() { if (keyboardDismissMode === 'on-drag') { Keyboard.dismiss(); } // this is required in addition to the similar call below, because the gesture // doesn't change `drawerVisible` state to prevent re-render during gesture // so when dragging from closed it wouldn't hide the status bar if (hideStatusBar) { StatusBar.setHidden(true, statusBarAnimation ?? 'slide'); } } function setState(newState: BetterDrawerState, willShow: boolean) { if (hideStatusBar) { StatusBar.setHidden(willShow, statusBarAnimation ?? 'slide'); } // dispach events if (drawerState.value !== newState || drawerVisible !== willShow) { // send state change event only when the state changed or the visibility of the // drawer (for example when drawer is in SETTLING state after opening and the user // taps on the overlay the state is still settling, but willShow is now false) onDrawerStateChanged?.(newState, willShow); } if (drawerVisible !== willShow) { setDrawerVisible(willShow); } if (newState === BetterDrawerState.IDLE) { if (willShow) { onDrawerOpen?.(); } else { onDrawerClose?.(); } } drawerState.value = newState; } function open() { 'worklet'; if (fromLeft && drawerOffset.value < drawerWidth) { // drawer is on the left and is not fully opened runOnJS(setState)(BetterDrawerState.SETTLING, true); drawerOffset.value = withSpring( drawerWidth, animationConfig, (finished) => { drawerSavedOffset.value = drawerOffset.value; if (finished) { // animation cannot be interrupted by a drag, but can be by // calling close or open (through tap or a controller) runOnJS(setState)(BetterDrawerState.IDLE, true); } } ); } else if (!fromLeft && drawerOffset.value > -drawerWidth) { // drawer is on the right and is not fully opened runOnJS(setState)(BetterDrawerState.SETTLING, true); drawerOffset.value = withSpring( -drawerWidth, animationConfig, (finished) => { drawerSavedOffset.value = drawerOffset.value; if (finished) { // animation cannot be interrupted by a drag, but can be by // calling close or open (through tap or a controller) runOnJS(setState)(BetterDrawerState.IDLE, true); } } ); } else { // drawer is fully opened runOnJS(setState)(BetterDrawerState.IDLE, true); } } function close() { 'worklet'; if (fromLeft && drawerOffset.value > 0) { // drawer is on the left and is not fully closed runOnJS(setState)(BetterDrawerState.SETTLING, false); drawerOffset.value = withSpring(0, animationConfig, (finished) => { drawerSavedOffset.value = drawerOffset.value; if (finished) { // animation cannot be interrupted by a drag, but can be by // calling close or open (through tap or a controller) runOnJS(setState)(BetterDrawerState.IDLE, false); } }); } else if (!fromLeft && drawerOffset.value < 0) { // drawer is on the right and is not fully closed runOnJS(setState)(BetterDrawerState.SETTLING, false); drawerOffset.value = withSpring(0, animationConfig, (finished) => { drawerSavedOffset.value = drawerOffset.value; if (finished) { // animation cannot be interrupted by a drag, but can be by // calling close or open (through tap or a controller) runOnJS(setState)(BetterDrawerState.IDLE, false); } }); } else { // drawer is fully closed runOnJS(setState)(BetterDrawerState.IDLE, false); } } // gestureOrientation is 1 if the expected gesture is from left to right and // -1 otherwise e.g. when drawer is on the left and is closed we expect left // to right gesture, thus orientation will be 1. const gestureOrientation = (fromLeft ? 1 : -1) * (drawerVisible ? -1 : 1); // When drawer is closed we want the hitSlop to be horizontally shorter than // the container size by the value of SLOP. This will make it only activate // when gesture happens not further than SLOP away from the edge const hitSlop = fromLeft ? { left: 0, width: drawerVisible ? undefined : edgeWidth } : { right: 0, width: drawerVisible ? undefined : edgeWidth }; // *** THIS IS THE LARGE COMMENT ABOVE *** // // While closing the drawer when user starts gesture outside of its area (in greyed // out part of the window), we want the drawer to follow only once finger reaches the // edge of the drawer. // E.g. on the diagram below drawer is illustrate by X signs and the greyed out area by // dots. The touch gesture starts at '*' and moves left, touch path is indicated by // an arrow pointing left // 1) +---------------+ 2) +---------------+ 3) +---------------+ 4) +---------------+ // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........| // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........| // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........| // |XXXXXXXX|......| |XXXXXXXX|.<-*..| |XXXXXXXX|<--*..| |XXXXX|<-----*..| // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........| // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........| // |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........| // +---------------+ +---------------+ +---------------+ +---------------+ // // For the above to work properly we define animated value that will keep // start position of the gesture. Then we use that value to calculate how // much we need to subtract from the dragX. If the gesture started on the // greyed out area we take the distance from the edge of the drawer to the // start position. Otherwise we don't subtract at all and the drawer be // pulled back as soon as you start the pan. // // This is used only when drawerType is "front" // const pan = Gesture.Pan(); pan.failOffsetY([-15, 15]); pan.hitSlop(hitSlop); pan.activeOffsetX(gestureOrientation * minSwipeDistance); pan.enableTrackpadTwoFingerGesture(enableTrackpadTwoFingerGesture); pan.enabled( drawerLockMode !== 'locked-closed' && drawerLockMode !== 'locked-open' ); pan.onStart((event) => { 'worklet'; ignoredOffset.value = 0; dragStartPosition.value = event.x; }); pan.onUpdate((event) => { 'worklet'; if (drawerState.value === BetterDrawerState.IDLE) { runOnJS(setState)(BetterDrawerState.DRAGGING, drawerVisible); runOnJS(onDragStart)(); } if (drawerState.value === BetterDrawerState.DRAGGING) { let newOffset = drawerSavedOffset.value + event.translationX - ignoredOffset.value; if (fromLeft) { // refer to the large comment above if ( drawerType === 'front' && event.translationX < 0 && drawerOffset.value > 0 ) { newOffset += dragStartPosition.value - drawerWidth; } // clamp the offset so the drawer does not move away from the edge newOffset = Math.max(0, Math.min(drawerWidth, newOffset)); } else { // refer to the large comment above if ( drawerType === 'front' && event.translationX > 0 && drawerOffset.value < 0 ) { newOffset += dragStartPosition.value - (containerWidth - drawerWidth); } // clamp the offset so the drawer does not move away from the edge newOffset = Math.max(-drawerWidth, Math.min(0, newOffset)); } drawerOffset.value = newOffset; // send event if there is a listener if (onDrawerSlide !== undefined) { runOnJS(onDrawerSlide)(openingProgress.value); } } else { // drawerState is SETTLING, save the translation to ignore it later ignoredOffset.value = event.translationX; } }); pan.onEnd((_event) => { 'worklet'; if (drawerState.value === BetterDrawerState.DRAGGING) { // update offsets and animations only when the drag was not ignored drawerSavedOffset.value = drawerOffset.value; // if the drawer was dragged more than half of its width open it, // otherwise close it if (fromLeft) { if (drawerOffset.value > drawerWidth / 2) { open(); } else { close(); } } else { if (drawerOffset.value < -drawerWidth / 2) { open(); } else { close(); } } } }); const dynamicDrawerStyles = { backgroundColor: drawerBackgroundColor, width: drawerWidth, }; const drawerStyle = useAnimatedStyle(() => { let translateX = 0; if (drawerSlide) { // drawer is supposed to be moved with the gesture (in this case // drawer is anchored to be off the screen when not opened) if (fromLeft) { translateX = -drawerWidth; } else { translateX = containerWidth; } translateX += drawerOffset.value; } else { // drawer is stationary (in this case drawer is below the content // so it's anchored left edge to left edge or right to right) if (fromLeft) { translateX = 0; } else { translateX = containerWidth - drawerWidth; } } // if the drawer is not visible move it off the screen to prevent it // from intercepting touch events on Android if (drawerOffset.value === 0) { translateX = 10000; } return { flexDirection: reverseContentDirection ? 'row-reverse' : 'row', transform: [{ translateX }], }; }); const containerStyle = useAnimatedStyle(() => { let translateX = 0; if (containerSlide) { // the container should be moved with the gesture translateX = drawerOffset.value; } return { transform: [{ translateX }], }; }); if (ref !== null) { // ref is set, create a controller and pass it const controller: DrawerLayoutController = { open: () => { open(); }, close: () => { close(); }, }; if (typeof ref === 'function') { ref(controller); } else { ref.current = controller; } } return ( <GestureDetector gesture={pan}> <Animated.View style={styles.main} onLayout={handleContainerLayout}> <Animated.View style={[ drawerType === 'front' ? styles.containerOnBack : styles.containerInFront, contentContainerStyle, containerStyle, ]}> {children} <Overlay drawerType={drawerType} color={overlayColor} progress={openingProgress} lockMode={drawerLockMode} close={close} /> </Animated.View> <Animated.View style={[ styles.drawerContainer, drawerContainerStyle, dynamicDrawerStyles, drawerStyle, ]}> {renderNavigationView(openingProgress)} </Animated.View> </Animated.View> </GestureDetector> ); } ); const styles = StyleSheet.create({ drawerContainer: { ...StyleSheet.absoluteFillObject, zIndex: 1001, flexDirection: 'row', }, containerInFront: { ...StyleSheet.absoluteFillObject, zIndex: 1002, }, containerOnBack: { ...StyleSheet.absoluteFillObject, }, main: { flex: 1, zIndex: 0, overflow: 'hidden', }, overlay: { ...StyleSheet.absoluteFillObject, zIndex: 1000, }, });
the_stack
import { EventEmitter } from 'events'; import * as BluebirdPromise from 'bluebird'; export interface ISoapMethod { (args: any, callback: (err: any, result: any, raw: any, soapHeader: any) => void, options?: any, extraHeaders?: any): void; } export interface ISoapServiceMethod { (args:any, callback?: (data: any) => void, headers?: any, req?: any): any; } // SOAP Fault 1.1 & 1.2 export type ISoapFault = ISoapFault12 | ISoapFault11; // SOAP Fault 1.1 export interface ISoapFault11 { Fault: { faultcode: number | string; faultstring: string; detail?: string; statusCode?: number; }; } // SOAP Fault 1.2 // 1.2 also supports additional, optional elements: // Role, Node, Detail. Should be added when soap module implements them // https://www.w3.org/TR/soap12/#soapfault export interface ISoapFault12 { Fault: { Code: { Value: string; Subcode?: { Value: string; }; }; Reason: { Text: string; }; statusCode?: number; }; } export interface ISecurity { addOptions(options: any): void; toXML(): string; } export interface IServicePort { [methodName: string]: ISoapServiceMethod; } export interface IService { [portName: string]: IServicePort; } export interface IServices { [serviceName: string]: IService; } export interface IXmlAttribute { name: string; value: string; } export interface IWsdlBaseOptions { attributesKey?: string; valueKey?: string; xmlKey?: string; overrideRootElement?: { namespace: string; xmlnsAttributes?: IXmlAttribute[]; }; ignoredNamespaces?: boolean | string[] | { namespaces?: string[]; override?: boolean; }; ignoreBaseNameSpaces?: boolean; escapeXML?: boolean; returnFault?: boolean; handleNilAsNull?: boolean; wsdl_headers?: { [key: string]: any }; wsdl_options?: { [key: string]: any }; } export interface IOptions extends IWsdlBaseOptions { disableCache?: boolean; endpoint?: string; envelopeKey?: string; httpClient?: HttpClient; request?: (options: any, callback?: (error: any, res: any, body: any) => void) => void; stream?: boolean; // wsdl options that only work for client forceSoap12Headers?: boolean; customDeserializer?: any; [key: string]: any; } export interface IOneWayOptions { responseCode?: number; emptyBody?: boolean; } export interface IServerOptions extends IWsdlBaseOptions { path: string; services: IServices; xml?: string; uri?: string; suppressStack?: boolean; oneWay?: IOneWayOptions; [key: string]: any; } export interface Definitions { descriptions: object; ignoredNamespaces: string[]; messages: WsdlMessages; portTypes: WsdlPortTypes; bindings: WsdlBindings; services: WsdlServices; schemas: WsdlSchemas; valueKey: string; xmlKey: string; xmlns: WsdlXmlns; '$targetNamespace': string; '$name': string; } export interface XsdTypeBase { ignoredNamespaces: string[]; valueKey: string; xmlKey: string; xmlns?: WsdlXmlns, } export interface WsdlSchemas { [prop: string]: WsdlSchema; } export interface WsdlSchema extends XsdTypeBase { children: any[]; complexTypes?: WsdlElements; elements?: WsdlElements; includes: any[]; name: string; nsName: string; prefix: string; types?: WsdlElements; xmlns: WsdlXmlns; } export interface WsdlElements { [prop: string]: XsdElement; } export type XsdElement = XsdElementType | XsdComplexType; export interface WsdlXmlns { wsu?: string; wsp?: string; wsam?: string; soap?: string; tns?: string; xsd?: string; __tns__?: string; [prop: string]: string | void; } export interface XsdComplexType extends XsdTypeBase { children: XsdElement[] | void; name: string; nsName: string; prefix: string; '$name': string; [prop: string]: any; } export interface XsdElementType extends XsdTypeBase { children: XsdElement[] | void; name: string; nsName: string; prefix: string; targetNSAlias: string; targetNamespace: string; '$lookupType': string; '$lookupTypes': any[]; '$name': string; '$type': string; [prop: string]: any; } export interface WsdlMessages { [prop: string]: WsdlMessage; } export interface WsdlMessage extends XsdTypeBase { element: XsdElement; parts: { [prop: string]: any }; '$name': string; } export interface WsdlPortTypes { [prop: string]: WsdlPortType; } export interface WsdlPortType extends XsdTypeBase { methods: { [prop: string]: XsdElement } } export interface WsdlBindings { [prop: string]: WsdlBinding; } export interface WsdlBinding extends XsdTypeBase { methods: WsdlElements; style: string; transport: string; topElements: {[prop: string]: any}; } export interface WsdlServices { [prop: string]: WsdlService; } export interface WsdlService extends XsdTypeBase { ports: {[prop: string]: any}; } export class WSDL { constructor(definition: any, uri: string, options?: IOptions); ignoredNamespaces: string[]; ignoreBaseNameSpaces: boolean; valueKey: string; xmlKey: string; xmlnsInEnvelope: string; onReady(callback: (err:Error) => void): void; processIncludes(callback: (err:Error) => void): void; describeServices(): { [k: string]: any }; toXML(): string; xmlToObject(xml: any, callback?: (err:Error, result:any) => void): any; findSchemaObject(nsURI: string, qname: string): XsdElement | null | undefined; objectToDocumentXML(name: string, params: any, nsPrefix?: string, nsURI?: string, type?: string): any; objectToRpcXML(name: string, params: any, nsPrefix?: string, nsURI?: string, isParts?: any): string; isIgnoredNameSpace(ns: string): boolean; filterOutIgnoredNameSpace(ns: string): string; objectToXML(obj: any, name: string, nsPrefix?: any, nsURI?: string, isFirst?: boolean, xmlnsAttr?: any, schemaObject?: any, nsContext?: any): string; processAttributes(child: any, nsContext: any): string; findSchemaType(name: any, nsURI: any): any; findChildSchemaObject(parameterTypeObj: any, childName: any, backtrace?: any): any; uri: string; definitions: Definitions; } export class Client extends EventEmitter { constructor(wsdl: WSDL, endpoint?: string, options?: IOptions); addBodyAttribute(bodyAttribute: any, name?: string, namespace?: string, xmlns?: string): void; addHttpHeader(name: string, value: any): void; addSoapHeader(soapHeader: any, name?: string, namespace?: any, xmlns?: string): number; changeSoapHeader(index: number, soapHeader: any, name?: string, namespace?: string, xmlns?: string): void; clearBodyAttributes(): void; clearHttpHeaders(): void; clearSoapHeaders(): void; describe(): any; getBodyAttributes(): any[]; getHttpHeaders(): { [k:string]: string }; getSoapHeaders(): string[]; setEndpoint(endpoint: string): void; setSOAPAction(action: string): void; setSecurity(security: ISecurity): void; wsdl: WSDL; [method: string]: ISoapMethod | WSDL | Function; } export function createClient(url: string, callback: (err: any, client: Client) => void): void; export function createClient(url: string, options: IOptions, callback: (err: any, client: Client) => void): void; export function createClientAsync(url: string, options?: IOptions, endpoint?: string): BluebirdPromise<Client>; export class Server extends EventEmitter { constructor(server: any, path: string, services: IServices, wsdl: WSDL, options: IServerOptions); path: string; services: IServices; wsdl: WSDL; addSoapHeader(soapHeader: any, name?: string, namespace?: any, xmlns?: string): number; changeSoapHeader(index: any, soapHeader: any, name?: any, namespace?: any, xmlns?: any): void; getSoapHeaders(): string[]; clearSoapHeaders(): void; log(type: string, data: any): any; authorizeConnection(req: any): boolean; authenticate(security: ISecurity): boolean; } export function listen(server: any, path: string, service: any, wsdl: string): Server; export function listen(server: any, options: IServerOptions): Server; export class HttpClient { constructor(options?: IOptions); buildRequest(rurl: string, data: any | string, exheaders?: { [key: string]: any }, exoptions?: { [key: string]: any }): any; handleResponse(req: any, res: any, body: any | string): any | string; request(rurl: string, data: any | string, callback: (err: any, res: any, body: any | string) => void, exheaders?: { [key: string]: any }, exoptions?: { [key: string]: any }): any; requestStream(rurl: string, data: any | string, exheaders?: { [key: string]: any }, exoptions?: { [key: string]: any }): any; } export class BasicAuthSecurity implements ISecurity { constructor(username: string, password: string, defaults?: any); addHeaders(headers: any): void; addOptions(options: any): void; toXML(): string; } export class BearerSecurity implements ISecurity { constructor(token: string, defaults?: any); addHeaders(headers: any): void; addOptions(options: any): void; toXML(): string; } export class WSSecurity implements ISecurity { constructor(username: string, password: string, options?: any); addOptions(options: any): void; toXML(): string; } export class WSSecurityCert implements ISecurity { constructor(privatePEM: any, publicP12PEM: any, password: any); addOptions(options: any): void; toXML(): string; } export class ClientSSLSecurity implements ISecurity { constructor(key: string | Buffer, cert: string | Buffer, ca?: string | any[] | Buffer, defaults?: any); constructor(key: string | Buffer, cert: string | Buffer, defaults?: any); addOptions(options: any): void; toXML(): string; } export class ClientSSLSecurityPFX implements ISecurity { constructor(pfx: string | Buffer, passphrase: string, defaults?: any); constructor(pfx: string | Buffer, defaults?: any); addOptions(options: any): void; toXML(): string; } export function passwordDigest(nonce: string, created: string, password: string): string; // Below are added for backwards compatibility for previous @types/soap users. export interface Security extends ISecurity {} export interface SoapMethod extends ISoapMethod {} export interface Option extends IOptions {}
the_stack
import { Ranking, isNumberColumn, Column, IColumnDesc, isSupportType, isMapAbleColumn, DEFAULT_COLOR, IDataRow, } from '../model'; import { colorPool, MAX_COLORS } from '../model/internal'; import { concat, equal, extent, range, resolveValue, ISequence } from '../internal'; import { timeParse } from 'd3-time-format'; import type { IDataProvider, IDeriveOptions, IExportOptions } from './interfaces'; /** * @internal */ export function cleanCategories(categories: Set<string>) { // remove missing values categories.delete(null); categories.delete(undefined); categories.delete(''); categories.delete('NA'); categories.delete('NaN'); categories.delete('na'); return Array.from(categories).map(String).sort(); } function hasDifferentSizes(data: any[][]) { if (data.length === 0) { return false; } const base = data[0].length; return data.some((d) => d != null && base !== (Array.isArray(d) ? d.length : -1)); } function isEmpty(v: any) { return ( v == null || (Array.isArray(v) && v.length === 0) || (v instanceof Set && v.size === 0) || (v instanceof Map && v.size === 0) || equal({}, v) ); } function deriveBaseType(value: any, all: () => any[], column: number | string, options: IDeriveOptions) { if (value == null) { console.warn('cannot derive from null value for column: ', column); return null; } // primitive if (typeof value === 'number') { return { type: 'number', domain: extent(all()), }; } if (typeof value === 'boolean') { return { type: 'boolean', }; } if (value instanceof Date) { return { type: 'date', }; } const formats = Array.isArray(options.datePattern) ? options.datePattern : [options.datePattern]; for (const format of formats) { const dateParse = timeParse(format); if (dateParse(value) == null) { continue; } return { type: 'date', dateParse: format, }; } const treatAsCategorical = typeof options.categoricalThreshold === 'function' ? options.categoricalThreshold : (u: number, t: number) => u < t * (options.categoricalThreshold as number); if (typeof value === 'string') { //maybe a categorical const values = all(); const categories = new Set(values); if (treatAsCategorical(categories.size, values.length)) { return { type: 'categorical', categories: cleanCategories(categories), }; } return { type: 'string', }; } if (typeof value === 'object' && value.alt != null && value.href != null) { return { type: 'link', }; } return null; } function deriveType( label: string, value: any, column: number | string, all: () => any[], options: IDeriveOptions ): IColumnDesc { const base: any = { type: 'string', label, column, }; const primitive = deriveBaseType(value, all, column, options); if (primitive != null) { return Object.assign(base, primitive); } // set if (value instanceof Set) { const cats = new Set<string>(); for (const value of all()) { if (!(value instanceof Set)) { continue; } value.forEach((vi) => { cats.add(String(vi)); }); } return Object.assign(base, { type: 'set', categories: cleanCategories(cats), }); } // map if (value instanceof Map) { const first = Array.from(value.values()).find((d) => !isEmpty(d)); const mapAll = () => { const r: any[] = []; for (const vi of all()) { if (!(vi instanceof Map)) { continue; } vi.forEach((vii) => { if (!isEmpty(vii)) { r.push(vii); } }); } return r; }; const p = deriveBaseType(first, mapAll, column, options); return Object.assign(base, p || {}, { type: p ? `${p.type}Map` : 'stringMap', }); } // array if (Array.isArray(value)) { const values = all(); const sameLength = !hasDifferentSizes(values); if (sameLength) { base.dataLength = value.length; } const first = value.find((v) => !isEmpty(v)); const p = deriveBaseType(first, () => concat(values).filter((d) => !isEmpty(d)), column, options); if (p && p.type === 'categorical' && !sameLength) { return Object.assign(base, p, { type: 'set', }); } if (p || isEmpty(first)) { return Object.assign(base, p || {}, { type: p ? `${p.type}s` : 'strings', }); } if (typeof first === 'object' && first.key != null && first.value != null) { // key,value pair map const mapAll = () => { const r: any[] = []; for (const vi of values) { if (!Array.isArray(vi)) { continue; } for (const vii of vi) { if (!isEmpty(vii)) { r.push(vii); } } } return r; }; const p = deriveBaseType(first.value, mapAll, column, options); return Object.assign(base, p || {}, { type: p ? `${p.type}Map` : 'stringMap', }); } } // check boxplot const bs = ['min', 'max', 'median', 'q1', 'q3']; if (value !== null && typeof value === 'object' && bs.every((b) => typeof value[b] === 'number')) { // boxplot const vs = all(); return Object.assign(base, { type: 'boxplot', domain: [ vs.reduce((a, b) => Math.min(a, b.min), Number.POSITIVE_INFINITY), vs.reduce((a, b) => Math.max(a, b.max), Number.NEGATIVE_INFINITY), ], }); } if (value !== null && typeof value === 'object') { // object map const first = Object.keys(value) .map((k) => value[k]) .filter((d) => !isEmpty(d)); const mapAll = () => { const r: any[] = []; for (const vi of all()) { if (vi == null) { continue; } Object.keys(vi).forEach((k) => { const vii = vi[k]; if (!isEmpty(vii)) { r.push(vii); } }); } return r; }; const p = deriveBaseType(first, mapAll, column, options); return Object.assign(base, p || {}, { type: p ? `${p.type}Map` : 'stringMap', }); } console.log('cannot infer type of column:', column); //unknown type return base; } function selectColumns(existing: string[], columns: string[]) { const allNots = columns.every((d) => d.startsWith('-')); if (!allNots) { return columns; } // negate case, exclude columns that are given using -notation const exclude = new Set(columns); return existing.filter((d) => !exclude.has(`-${d}`)); } function toLabel(key: string | number) { if (typeof key === 'number') { return `Col ${key + 1}`; } key = key.trim(); if (key.length === 0) { return 'Unknown'; } return key .split(/[\s]+/gm) .map((k) => (k.length === 0 ? k : `${k[0]!.toUpperCase()}${k.slice(1)}`)) .join(' '); } export function deriveColumnDescriptions(data: any[], options: Partial<IDeriveOptions> = {}) { const config = Object.assign( { categoricalThreshold: (u: number, n: number) => u <= MAX_COLORS && u < n * 0.7, //70% unique and less equal to 22 categories columns: [], datePattern: ['%x', '%Y-%m-%d', '%Y-%m-%dT%H:%M:%S.%LZ'], }, options ); const r: IColumnDesc[] = []; if (data.length === 0) { // no data to derive something from return r; } const first = data[0]; const columns: (number | string)[] = Array.isArray(first) ? range(first.length) : config.columns.length > 0 ? selectColumns(Object.keys(first), config.columns) : Object.keys(first); return columns.map((key) => { let v = resolveValue(first, key); if (isEmpty(v)) { // cannot derive something from null try other rows const foundRow = data.find((row) => !isEmpty(resolveValue(row, key))); v = foundRow ? foundRow[key] : null; } return deriveType( toLabel(key), v, key, () => data.map((d) => resolveValue(d, key)).filter((d) => !isEmpty(d)), config ); }); } /** * assigns colors to columns if they are numbers and not yet defined * @param columns * @returns {IColumnDesc[]} */ export function deriveColors(columns: IColumnDesc[]) { const colors = colorPool(); columns.forEach((col: IColumnDesc) => { if (isMapAbleColumn(col)) { col.colorMapping = col.colorMapping || col.color || colors() || DEFAULT_COLOR; } }); return columns; } const DEFAULT_EXPORT_OPTIONS: IExportOptions = { separator: '\t', newline: '\n', header: true, quote: false, quoteChar: '"', filter: (c: Column) => !isSupportType(c), verboseColumnHeaders: false, }; function createCSVExporter(columns: readonly Column[], options: IExportOptions) { //optionally quote not numbers const escape = new RegExp(`[${options.quoteChar}]`, 'g'); function quote(v: any, c?: Column) { const l = String(v); if ((options.quote || l.indexOf('\n') >= 0) && (!c || !isNumberColumn(c))) { return `${options.quoteChar}${l.replace(escape, options.quoteChar + options.quoteChar)}${options.quoteChar}`; } return l; } function addHeader() { return columns .map((d) => quote(`${d.label}${options.verboseColumnHeaders && d.description ? `\n${d.description}` : ''}`)) .join(options.separator); } function addRow(row: IDataRow) { return columns.map((c) => quote(c.getExportValue(row, 'text'), c)).join(options.separator); } return { addHeader, addRow, }; } /** * utility to export a ranking to a table with the given separator * @param ranking * @param data * @param options * @returns {Promise<string>} */ export function exportRanking(ranking: Ranking, data: any[], options: Partial<IExportOptions> = {}): string { const opts: IExportOptions = Object.assign({}, DEFAULT_EXPORT_OPTIONS, options); const columns = ranking.flatColumns.filter((c) => opts.filter(c)); const order = ranking.getOrder(); const exporter = createCSVExporter(columns, opts); const r: string[] = []; if (opts.header) { r.push(exporter.addHeader()); } data.forEach((row, i) => { r.push(exporter.addRow({ v: row, i: order[i] })); }); return r.join(opts.newline); } /** * export table helper * @param columnsOrRanking * @param data * @param options * @returns {string} */ export function exportTable( columnsOrRanking: readonly Column[] | Ranking, data: ISequence<IDataRow>, options: Partial<IExportOptions> = {} ): string { const opts: IExportOptions = Object.assign({}, DEFAULT_EXPORT_OPTIONS, options); const columns = columnsOrRanking instanceof Ranking ? columnsOrRanking.flatColumns.filter((c) => opts.filter(c)) : columnsOrRanking; const exporter = createCSVExporter(columns, opts); const r: string[] = []; if (opts.header) { r.push(exporter.addHeader()); } data.forEach((row) => { r.push(exporter.addRow(row)); }); return r.join(opts.newline); } /** @internal */ export function map2Object<T>(map: Map<string, T>) { const r: { [key: string]: T } = {}; map.forEach((v, k) => (r[k] = v)); return r; } /** @internal */ export function object2Map<T>(obj: { [key: string]: T }) { const r = new Map<string, T>(); for (const k of Object.keys(obj)) { r.set(k, obj[k]); } return r; } /** @internal */ export function rangeSelection( provider: IDataProvider, rankingId: string, dataIndex: number, relIndex: number, ctrlKey: boolean ) { const ranking = provider.getRankings().find((d) => d.id === rankingId); if (!ranking) { // no known reference return false; } const selection = provider.getSelection(); if (selection.length === 0 || selection.includes(dataIndex)) { return false; // no other or deselect } const order = ranking.getOrder(); const lookup = new Map(Array.from(order).map((d, i) => [d, i])); const distances = selection.map((d) => { const index = lookup.has(d) ? lookup.get(d)! : Number.POSITIVE_INFINITY; return { s: d, index, distance: Math.abs(relIndex - index) }; }); const nearest = distances.sort((a, b) => a.distance - b.distance)[0]!; if (!isFinite(nearest.distance)) { return false; // all outside } if (!ctrlKey) { selection.splice(0, selection.length); selection.push(nearest.s); } if (nearest.index < relIndex) { for (let i = nearest.index + 1; i <= relIndex; ++i) { selection.push(order[i]); } } else { for (let i = relIndex; i <= nearest.index; ++i) { selection.push(order[i]); } } provider.setSelection(selection); return true; } export function isPromiseLike<T>(promiseLike: Promise<T> | T): promiseLike is Promise<T> { return promiseLike != null && typeof (promiseLike as Promise<T>).then === 'function'; }
the_stack
import { get_exchange_rates } from './exchangeRate' const mathjs = require('mathjs'); interface PluginState { scope: object; globalConfig: object; lineData: object; }; type BlockType = '+' | '-'; const inline_math_regex = /^(\+|\-)?=(?= *[0-9a-zA-Z\[\(\-\+])/; const equation_result_separator = " => "; const equation_result_collapsed = " |> "; // Font Awesome clipboard regular const clipboard = `<svg aria-hidden="true" focusable="false" data-prefix="far" data-icon="clipboard" class="svg-inline--fa fa-clipboard fa-w-12" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><path fill="currentColor" d="M336 64h-80c0-35.3-28.7-64-64-64s-64 28.7-64 64H48C21.5 64 0 85.5 0 112v352c0 26.5 21.5 48 48 48h288c26.5 0 48-21.5 48-48V112c0-26.5-21.5-48-48-48zM192 40c13.3 0 24 10.7 24 24s-10.7 24-24 24-24-10.7-24-24 10.7-24 24-24zm144 418c0 3.3-2.7 6-6 6H54c-3.3 0-6-2.7-6-6V118c0-3.3 2.7-6 6-6h42v36c0 6.6 5.4 12 12 12h168c6.6 0 12-5.4 12-12v-36h42c3.3 0 6 2.7 6 6z"></path></svg>`; // Font Awesome check const check = `<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="check" class="svg-inline--fa fa-check fa-w-16" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor" d="M173.898 439.404l-166.4-166.4c-9.997-9.997-9.997-26.206 0-36.204l36.203-36.204c9.997-9.998 26.207-9.998 36.204 0L192 312.69 432.095 72.596c9.997-9.997 26.207-9.997 36.204 0l36.203 36.204c9.997 9.997 9.997 26.206 0 36.204l-294.4 294.401c-9.998 9.997-26.207 9.997-36.204-.001z"></path></svg>`; function plugin(CodeMirror, context) { const math = mathjs.create(mathjs.all, {}); function truthy(s: string) { s = s.toLowerCase(); return s.startsWith('t') || s.startsWith('y') || s === '1'; } function falsey(s: string) { s = s.toLowerCase(); return s.startsWith('f') || s.startsWith('n') || s === '0'; } // Helper for the math lines function, // removes all lines until the ```math symbol function erase_to_start(lines: string[], lineno: number, allow_inline: boolean) { for (let i = lineno; i >= 0; i--) { const line = lines[i]; if (!line) continue; if (line.trim() === '```math') { break; } else if (!(allow_inline && line.match(inline_math_regex))) { lines[i] = ''; } } } // Takes in an array of all lines, and strips out any non-math lines function trim_lines(lines: string[], allow_inline: boolean) { let might_be_in_block = false; for (let i = 0; i < lines.length; i++) { const line = lines[i]; if (!line) continue; if (allow_inline && line.match(inline_math_regex)) { continue; } else if (might_be_in_block && line.trim() === '```') { might_be_in_block = false; lines[i] = '```'; continue; } else if (line.trim() === '```math') { might_be_in_block = true; lines[i] = '```math'; } if (!might_be_in_block) lines[i] = ''; } if (might_be_in_block) { erase_to_start(lines, lines.length, allow_inline); } return lines; } function reprocess(cm: any) { const allow_inline = cm.state.mathMode.globalConfig.inlinesyntax; const lines = trim_lines(cm.getValue('\n').split('\n'), allow_inline); // scope is global to the note let scope = Object.assign({}, cm.state.mathMode.scope); let lineData = {}; let globalConfig = Object.assign({}, cm.state.mathMode.globalConfig); let config = Object.assign({}, globalConfig); let block_total = ''; for (let i = 0; i < lines.length; i++) { const line = lines[i]; if (!line || line === '```math') { block_total = ''; } else if (line === '```') { config = Object.assign({}, globalConfig); block_total = ''; } else if (line.includes(':')) { lineData[i] = process_config(line, config); } else { // Allow the user to redefine the total variable if they want const localScope = Object.assign({total: block_total}, scope); lineData[i] = process_line(line, localScope, config, block_total); // Update the scope scope = Object.assign(scope, localScope); block_total = lineData[i].total; } if (truthy(config.global)) { globalConfig = Object.assign(globalConfig, config, {global: 'false'}); } } cm.state.mathMode.lineData = lineData; refresh_widgets(cm); } function get_line_equation(line: string): string { return line.replace(inline_math_regex, ''); } function get_sum_type(line: string): BlockType { const match = inline_math_regex.exec(line) if (match && match.length > 1 && match[1] === '-') return '-'; return '+'; } function math_contains_assignment(parsed: any, name: string) { if (!parsed) return false; const filtered = parsed.filter(function (n) { return n.isAssignmentNode && n.name === name }); return filtered.length > 0; } function math_contains_symbol(parsed: any, name: string) { if (!parsed) return false; const filtered = parsed.filter(function (n) { return n.isSymbolNode && n.name === name }); return filtered.length > 0; } function process_line(line: string, scope: any, config: any, block_total: string): any { let p = null; let result = ''; let contains_total = false; try { p = math.parse(get_line_equation(line)); // Evaluate the Expression if (falsey(config.simplify)) result = p.evaluate(scope); else result = math.simplify(p) contains_total = math_contains_symbol(p, 'total'); if (result && !contains_total) { const sum_char = get_sum_type(line); // An error can occur when the types don't match up // To recover, restart the sum counter try { block_total = math.parse(`${block_total} ${sum_char} ${result}`).evaluate(scope); } catch(err) { // If the error parsing still fails, we will just return the result (no sign) // This will fail in cases were the result type is a symbolic type // There is probably a better method to handle this case try { block_total = math.parse(`${sum_char} ${result}`).evaluate(scope); } catch(errr) { block_total = result; } } } // Format the output result = math.format(result, { precision: Number(config.precision), lowerExp: Number(config.lowerExp), upperExp: Number(config.upperExp), notation: config.notation, }); // Attach a name if necessary if (p.name && truthy(config.verbose)) result = p.name + ': ' + result; } catch(e) { result = e.message; if (e.message.indexOf('Cannot create unit') === 0) { result = ''; } } // If the total variable wasn't modified, clear it // This needs to be outside the "try" statement to guarantee that it runs if (!math_contains_assignment(p, 'total')) delete scope['total']; return { result: result, total: block_total, displaytotal: truthy(config.displaytotal) && !contains_total, inputHidden: config.hide === 'expression', resultHidden: config.hide === 'result' || result === '', inline: truthy(config.inline), alignRight: config.align === 'right', copyButton: config.copyButton, }; } function process_config(line: string, config: any) { const [ key, value ] = line.split(':', 2); config[key.trim()] = value.trim(); if (truthy(config.bignumber)) { math.config({ number: 'BigNumber', precision: 128 }); } else { math.config({ number: 'number' }); } return { isConfig: true }; } function clear_math_widgets(cm: any, lineInfo: any) { // This could potentially cause a conflict with another plugin cm.removeLineClass(lineInfo.handle, 'wrap', 'cm-comment'); if (lineInfo.widgets) { cm.removeLineClass(lineInfo.handle, 'text', 'math-hidden'); cm.removeLineClass(lineInfo.handle, 'text', 'math-input-inline'); cm.removeLineClass(lineInfo.handle, 'text', 'math-input-line'); for (const wid of lineInfo.widgets) { if (wid.className === 'math-result-line') wid.clear(); } } } function refresh_widgets(cm: any) { for (let i = cm.firstLine(); i <= cm.lastLine(); i++) { const line = cm.lineInfo(i); clear_math_widgets(cm, line); const lineData = cm.state.mathMode.lineData[i]; if (!lineData) continue; if (lineData.isConfig) { cm.addLineClass(i, 'wrap', 'cm-comment'); continue; } cm.addLineClass(i, 'wrap', 'cm-mm-math-block'); if (lineData.resultHidden) continue; if (lineData.inputHidden) cm.addLineClass(i, 'text', 'math-hidden'); else if (lineData.inline) cm.addLineClass(i, 'text', 'math-input-inline'); const marker = lineData.inputHidden ? equation_result_collapsed : equation_result_separator; let result = lineData.result; if (lineData.displaytotal && !result.includes('total')) { result = lineData.total; } const res = document.createElement('div'); res.setAttribute('class', 'math-result'); const txt = document.createElement('span'); txt.setAttribute('class', 'math-copy-tooltip'); txt.innerHTML = clipboard; const btn = document.createElement('span'); btn.setAttribute('class', 'math-copy-button'); btn.innerHTML = marker + result; btn.onclick = () => { navigator.clipboard.writeText(result) .then(() => txt.innerHTML = check) .catch(err => console.error("Could not copy text")); }; btn.onmouseleave = () => {txt.innerHTML = clipboard;}; // The order of children is important res.appendChild(btn); if (lineData.copyButton) res.appendChild(txt); if (lineData.alignRight) res.setAttribute('class', 'math-result-right'); // handleMouseEvents gives control of mouse handling for the widget to codemirror // This is necessary to get the cursor to be placed in the right location ofter // clicking on a widget // The downside is that it breaks copying of widget text (for textareas, it never // works on contenteditable) // I'm okay with this because I want the user to be able to select a block // without accidently grabbing the result cm.addLineWidget(i, res, { className: 'math-result-line', handleMouseEvents: true }); // This will be used to clear the colouring from cm-comment cm.addLineClass(i, 'text', 'math-input-line'); } } function clean_up(cm: any, lines: string[]) { for (let i = 0; i < lines.length; i++) { if (!lines[i]) { const line = cm.lineInfo(i); clear_math_widgets(cm, line); } } } // On each change we're going to scan for function on_change(cm: any, change: any) { let lines = trim_lines(cm.getValue('\n').split('\n'), true); clean_up(cm, lines); // Most changes are the user typing a single character // If this doesn't happen inside a math block, we shouldn't re-process // +input means the user input the text (as opposed to joplin/plugin) // +delete means the user deleted some text // setValue means something programically altered the text if (change.from.line === change.to.line && change.origin !== "setValue") { const from = change.from.line; if (!lines[from] && (from === cm.firstLine() || !lines[from - 1]) && (from === cm.lastLine() || !lines[from + 1])) return; } if (cm.state.mathMode.timer) clearTimeout(cm.state.mathMode.timer); cm.state.mathMode.timer = setTimeout(() => { // Because the entire document shares one scope, // we will re-process the entire document for each change reprocess(cm); cm.state.mathMode.timer = null; }, 300); } function update_rates(cm: any) { get_exchange_rates().then(rates => {; math.createUnit(rates.base); math.createUnit(rates.base.toLowerCase(), math.unit(1, rates.base)); Object.keys(rates.rates) .forEach((currency) => { math.createUnit(currency, math.unit(1/rates.rates[currency], rates.base)); math.createUnit(currency.toLowerCase(), math.unit(1/rates.rates[currency], rates.base)); }); reprocess(cm); }); } // I ran into an odd bug during development where the function wouldn't be called // when the default value of the option was true (only happened on some notes) // The fix for me was to set the option to true in codeMirrorOptions instead CodeMirror.defineOption('enable-math-mode', false, async function(cm, val, old) { // Cleanup if (old && old != CodeMirror.Init) { clearInterval(cm.state.mathMode.rateInterval); cm.state.mathMode = null; cm.off("change", on_change); } // setup if (val) { const globalConfig = await context.postMessage({name: 'getConfig'}); let interval = null; if (globalConfig.currency) { interval = setInterval(() => { update_rates(cm); }, 1000*60*60*24); } cm.state.mathMode = { scope: {}, rateInterval: interval, globalConfig: globalConfig, lineData: {}, }; if (globalConfig.currency) { update_rates(cm); } reprocess(cm); // We need to process all blocks on the next update cm.on('change', on_change); } }); } module.exports = { default: function(context) { return { plugin: function(CodeMirror) { return plugin(CodeMirror, context); }, codeMirrorResources: ['addon/mode/multiplex'], codeMirrorOptions: { 'enable-math-mode': true }, assets: function() { return [ { mime: 'text/css', inline: true, text: `.math-result-line { opacity: 0.75; display: block; } .math-result-right { padding-right: 5px; text-align: right; } .math-input-inline { float: left; } .CodeMirror pre.CodeMirror-line.math-input-inline { padding-right: 10px; } .math-hidden { display: none; } .math-copy-button:hover { cursor: pointer; } .math-copy-tooltip { opacity: 0; } .math-copy-tooltip > svg{ height: 1em; margin-left: 6px; } .math-copy-button:hover + .math-copy-tooltip { opacity: 1; } /* This will style math text to be the same as the notes text colour */ .CodeMirror-line.math-input-line span.cm-comment { color: inherit; } .cm-mm-math-block { /* On macOS systems the line following a float: left will be aligned to the right. We don't want it to happen, so this is placed in which prevents top level lines from becoming wrapped up in the float */ overflow: auto; } ` } ]; }, } }, }
the_stack
import { Resolver, schemaComposer, ObjectTypeComposer } from 'graphql-compose'; import { Query } from 'mongoose'; import { UserModel, IUser } from '../../__mocks__/userModel'; import { connection, prepareCursorQuery } from '../connection'; import { findMany } from '../findMany'; import { count } from '../count'; import { convertModelToGraphQL } from '../../fieldsConverter'; import { ExtendedResolveParams } from '..'; jest.mock('../findMany', () => ({ findMany: jest.fn((...args) => jest.requireActual('../findMany').findMany(...args)), })); jest.mock('../count', () => ({ count: jest.fn((...args) => jest.requireActual('../count').count(...args)), })); beforeAll(() => UserModel.base.createConnection()); afterAll(() => UserModel.base.disconnect()); describe('connection() resolver', () => { describe('prepareCursorQuery()', () => { let rawQuery; describe('single index', () => { const cursorData = { a: 10 }; const indexKeys = Object.keys(cursorData); it('asc order', () => { const indexData = { a: 1 }; // for beforeCursorQuery rawQuery = {}; prepareCursorQuery(rawQuery, cursorData, indexKeys, indexData, '$lt', '$gt'); expect(rawQuery).toEqual({ a: { $lt: 10 } }); // for afterCursorQuery rawQuery = {}; prepareCursorQuery(rawQuery, cursorData, indexKeys, indexData, '$gt', '$lt'); expect(rawQuery).toEqual({ a: { $gt: 10 } }); }); it('desc order', () => { const indexData = { a: -1 }; // for beforeCursorQuery rawQuery = {}; prepareCursorQuery(rawQuery, cursorData, indexKeys, indexData, '$lt', '$gt'); expect(rawQuery).toEqual({ a: { $gt: 10 } }); // for afterCursorQuery rawQuery = {}; prepareCursorQuery(rawQuery, cursorData, indexKeys, indexData, '$gt', '$lt'); expect(rawQuery).toEqual({ a: { $lt: 10 } }); }); }); describe('compound index', () => { const cursorData = { a: 10, b: 100, c: 1000 }; const indexKeys = Object.keys(cursorData); it('asc order', () => { const indexData = { a: 1, b: -1, c: 1 }; // for beforeCursorQuery rawQuery = {}; prepareCursorQuery(rawQuery, cursorData, indexKeys, indexData, '$lt', '$gt'); expect(rawQuery).toEqual({ $or: [ { a: 10, b: 100, c: { $lt: 1000 } }, { a: 10, b: { $gt: 100 } }, { a: { $lt: 10 } }, ], }); // for afterCursorQuery rawQuery = {}; prepareCursorQuery(rawQuery, cursorData, indexKeys, indexData, '$gt', '$lt'); expect(rawQuery).toEqual({ $or: [ { a: 10, b: 100, c: { $gt: 1000 } }, { a: 10, b: { $lt: 100 } }, { a: { $gt: 10 } }, ], }); }); it('desc order', () => { const indexData = { a: -1, b: 1, c: -1 }; // for beforeCursorQuery rawQuery = {}; prepareCursorQuery(rawQuery, cursorData, indexKeys, indexData, '$lt', '$gt'); expect(rawQuery).toEqual({ $or: [ { a: 10, b: 100, c: { $gt: 1000 } }, { a: 10, b: { $lt: 100 } }, { a: { $gt: 10 } }, ], }); // for afterCursorQuery rawQuery = {}; prepareCursorQuery(rawQuery, cursorData, indexKeys, indexData, '$gt', '$lt'); expect(rawQuery).toEqual({ $or: [ { a: 10, b: 100, c: { $lt: 1000 } }, { a: 10, b: { $gt: 100 } }, { a: { $lt: 10 } }, ], }); }); }); }); describe('connection() -> ', () => { let UserTC: ObjectTypeComposer; beforeEach(() => { schemaComposer.clear(); UserTC = convertModelToGraphQL(UserModel, 'User', schemaComposer); }); let user1: IUser; let user2: IUser; beforeEach(async () => { await UserModel.deleteMany({}); user1 = new UserModel({ name: 'userName1', skills: ['js', 'ruby', 'php', 'python'], gender: 'male', relocation: true, contacts: { email: 'mail' }, }); user2 = new UserModel({ name: 'userName2', skills: ['go', 'erlang'], gender: 'female', relocation: false, contacts: { email: 'mail' }, }); await user1.save(); await user2.save(); }); it('should return Resolver object with default name', () => { const resolver = connection(UserModel, UserTC); if (!resolver) throw new Error('Connection resolver is undefined'); expect(resolver).toBeInstanceOf(Resolver); expect(resolver.getNestedName()).toEqual('connection'); }); it('Resolver object should have `filter` arg', () => { const resolver = connection(UserModel, UserTC); if (!resolver) throw new Error('Connection resolver is undefined'); expect(resolver.hasArg('filter')).toBe(true); }); it('Resolver object should have `sort` arg', () => { const resolver = connection(UserModel, UserTC); if (!resolver) throw new Error('Connection resolver is undefined'); expect(resolver.hasArg('sort')).toBe(true); }); it('Resolver object should have `connection args', () => { const resolver = connection(UserModel, UserTC); if (!resolver) throw new Error('Connection resolver is undefined'); expect(resolver.hasArg('first')).toBe(true); expect(resolver.hasArg('last')).toBe(true); expect(resolver.hasArg('before')).toBe(true); expect(resolver.hasArg('after')).toBe(true); }); it('should create custom edge type', () => { const resolver = connection(UserModel, UserTC, { edgeTypeName: 'CustomEdge', } as any); if (!resolver) throw new Error('Connection resolver is undefined'); expect(schemaComposer.has('CustomEdge')).toBe(true); }); describe('Resolver.resolve():Promise', () => { it('should be fulfilled Promise', async () => { const resolver = connection(UserModel, UserTC); if (!resolver) throw new Error('Connection resolver is undefined'); const result = resolver.resolve({ args: { first: 20 } }); await expect(result).resolves.toBeDefined(); }); it('should return array of documents in `edges`', async () => { const resolver = connection(UserModel, UserTC); if (!resolver) throw new Error('Connection resolver is undefined'); const result = await resolver.resolve({ args: { first: 20 } }); expect(result.edges).toBeInstanceOf(Array); expect(result.edges).toHaveLength(2); expect(result.edges.map((d: any) => d.node.name)).toEqual( expect.arrayContaining([user1.name, user2.name]) ); }); it('should limit records', async () => { const resolver = connection(UserModel, UserTC); if (!resolver) throw new Error('Connection resolver is undefined'); const result = await resolver.resolve({ args: { first: 1 } }); expect(result.edges).toBeInstanceOf(Array); expect(result.edges).toHaveLength(1); }); it('should sort records', async () => { const resolver = connection(UserModel, UserTC); if (!resolver) throw new Error('Connection resolver is undefined'); const result1 = await resolver.resolve({ args: { sort: { _id: 1 }, first: 1 }, }); const result2 = await resolver.resolve({ args: { sort: { _id: -1 }, first: 1 }, }); expect(`${result1.edges[0].node._id}`).not.toBe(`${result2.edges[0].node._id}`); }); it('should return mongoose documents', async () => { const resolver = connection(UserModel, UserTC); if (!resolver) throw new Error('Connection resolver is undefined'); const result = await resolver.resolve({ args: { first: 20 } }); expect(result.edges[0].node).toBeInstanceOf(UserModel); expect(result.edges[1].node).toBeInstanceOf(UserModel); }); it('should call `beforeQuery` method with non-executed `query` as arg', async () => { expect.assertions(4); let extendedQuery: Query<any, any>; const resolver = connection(UserModel, UserTC); const result = await resolver.resolve({ args: {}, beforeQuery: (query: any, rp: ExtendedResolveParams) => { expect(query).toBeInstanceOf(Query); expect(rp.model).toBe(UserModel); // modify query before execution extendedQuery = query.where({ _id: user1.id }).limit(1989); return extendedQuery; }, }); expect(result.edges).toHaveLength(1); expect(result.edges[0].node._id.toString()).toEqual(user1.id.toString()); }); it('should override result with `beforeQuery`', async () => { const resolver = connection(UserModel, UserTC); if (!resolver) { throw new Error('resolver is undefined'); } const result = await resolver.resolve({ args: {}, beforeQuery: (query: any, rp: ExtendedResolveParams) => { expect(query).toBeInstanceOf(Query); expect(rp.model).toBe(UserModel); return [{ overrides: true }]; }, }); expect(result).toHaveProperty('edges.0.node', { overrides: true }); }); it('should use internal resolver custom opts', async () => { schemaComposer.clear(); UserTC = convertModelToGraphQL(UserModel, 'User', schemaComposer); const mockCountOpts = { suffix: 'ABC' }; const mockFindManyOpts = { suffix: 'DEF' }; const resolver = connection(UserModel, UserTC, { countOpts: mockCountOpts, findManyOpts: mockFindManyOpts, } as any); if (!resolver) throw new Error('Connection resolver is undefined'); expect(count).toHaveBeenCalledWith(expect.anything(), expect.anything(), mockCountOpts); expect(findMany).toHaveBeenCalledWith( expect.anything(), expect.anything(), mockFindManyOpts ); }); }); }); });
the_stack
import { IonBackButton, IonButton, IonButtons, IonCard, IonCardContent, IonCol, IonContent, IonGrid, IonHeader, IonInfiniteScroll, IonInfiniteScrollContent, IonInput, IonItem, IonLabel, IonList, IonListHeader, IonMenuButton, IonPage, IonProgressBar, IonRow, IonSegment, IonSegmentButton, IonTitle, IonToolbar, isPlatform, } from '@ionic/react'; import { V1PodList } from '@kubernetes/client-node'; import React, { memo, useContext, useState } from 'react'; import { RouteComponentProps } from 'react-router'; import { IContext } from '../../../declarations'; import { kubernetesRequest, pluginRequest } from '../../../utils/api'; import { IS_INCLUSTER } from '../../../utils/constants'; import { AppContext } from '../../../utils/context'; import useWindowWidth from '../../../utils/useWindowWidth'; import Chart, { IAggregations } from './Chart'; import Document, { IElasticsearchDocument, IElasticsearchDocumentSource } from './Document'; import Details from './Details'; const getFieldsRecursively = (prefix: string, document: IElasticsearchDocumentSource): string[] => { const fields: string[] = []; for (const field in document) { if (typeof document[field] === 'object') { fields.push(...getFieldsRecursively(prefix ? `${prefix}.${field}` : field, document[field])); } else { fields.push(prefix ? `${prefix}.${field}` : field); } } return fields; }; const getFields = (documents: IElasticsearchDocument[]): string[] => { const fields: string[] = []; for (const document of documents) { fields.push(...getFieldsRecursively('', document['_source'])); } const uniqueFields: string[] = []; for (const field of fields) { if (uniqueFields.indexOf(field) === -1) { uniqueFields.push(field); } } return uniqueFields; }; interface IElasticsearchHitsTotal { value: number; } interface IElasticsearchHits { hits: IElasticsearchDocument[]; total: IElasticsearchHitsTotal; } interface IElasticsearchResult { // eslint-disable-next-line @typescript-eslint/naming-convention _scroll_id: string; hits: IElasticsearchHits; aggregations?: IAggregations; } type IQueryPageProps = RouteComponentProps; const QueryPage: React.FunctionComponent<IQueryPageProps> = ({ location }: IQueryPageProps) => { const context = useContext<IContext>(AppContext); const width = useWindowWidth(); const url = new URLSearchParams(location.search); const [activeSegment, setActiveSegment] = useState<string>('query'); const [query, setQuery] = useState<string>(url.get('query') ? (url.get('query') as string) : ''); const [from, setFrom] = useState<string>(url.get('from') ? (url.get('from') as string) : 'now-15m'); const [to, setTo] = useState<string>(url.get('to') ? (url.get('to') as string) : 'now'); const [scrollID, setScrollID] = useState<string>(''); const [documents, setDocuments] = useState<IElasticsearchDocument[]>([]); const [hits, setHits] = useState<number>(0); const [aggregations, setAggregations] = useState<IAggregations | undefined>(undefined); const [fields, setFields] = useState<string[]>([]); const [selectedFields, setSelectedFields] = useState<string[]>( url.get('selectedFields') ? (url.get('selectedFields') as string).split(',') : [], ); const [error, setError] = useState<string>(''); const [isFetching, setIsFetching] = useState<boolean>(false); const handleQuery = (event) => { setQuery(event.target.value); }; const handleFrom = (event) => { setFrom(event.target.value); }; const handleTo = (event) => { setTo(event.target.value); }; const addField = (field: string) => { setSelectedFields((fields) => [...fields, field]); }; const removeField = (field: string) => { setSelectedFields(selectedFields.filter((item) => item !== field)); }; let result: IElasticsearchResult = { // eslint-disable-next-line @typescript-eslint/naming-convention _scroll_id: '', hits: { hits: [], total: { value: 0 } }, aggregations: { logcount: { buckets: [], interval: '' } }, }; const runQuery = async (useScrollID: boolean) => { try { setError(''); setIsFetching(true); let portforwardingPath = ''; if (!IS_INCLUSTER) { const podList: V1PodList = await kubernetesRequest( 'GET', `/api/v1/namespaces/${context.settings.elasticsearchNamespace}/pods?labelSelector=${context.settings.elasticsearchSelector}`, '', context.settings, await context.kubernetesAuthWrapper(''), ); if (podList.items.length > 0 && podList.items[0].metadata) { portforwardingPath = `/api/v1/namespaces/${podList.items[0].metadata.namespace}/pods/${podList.items[0].metadata.name}/portforward`; } else { throw new Error( `Could not find Pod in Namespace "${context.settings.elasticsearchNamespace}" with selector "${context.settings.elasticsearchSelector}".`, ); } } result = await pluginRequest( 'elasticsearch', context.settings.elasticsearchPort, context.settings.elasticsearchAddress, { query: { size: 100, // eslint-disable-next-line @typescript-eslint/naming-convention sort: [{ '@timestamp': { order: 'desc' } }], query: { bool: { must: [ { range: { '@timestamp': { gte: from, lte: to, }, }, }, { // eslint-disable-next-line @typescript-eslint/naming-convention query_string: { query: query, }, }, ], }, }, aggs: { logcount: { // eslint-disable-next-line @typescript-eslint/naming-convention auto_date_histogram: { field: '@timestamp', buckets: 30, }, }, }, }, scrollID: useScrollID ? scrollID : '', username: context.settings.elasticsearchUsername, password: context.settings.elasticsearchPassword, }, portforwardingPath, context.settings, await context.kubernetesAuthWrapper(''), ); if (!useScrollID) { setScrollID(result._scroll_id); setFields(getFields(result.hits.hits.slice(result.hits.hits.length > 10 ? 10 : result.hits.hits.length))); setAggregations(result.aggregations); setDocuments(result.hits.hits); setHits(result.hits.total.value); } else { setDocuments((docs) => [...docs, ...result.hits.hits]); } setIsFetching(false); } catch (err) { setIsFetching(false); setDocuments([]); setError(err.message); } }; return ( <IonPage> <IonHeader> <IonToolbar> <IonButtons slot="start"> <IonMenuButton /> <IonBackButton /> </IonButtons> <IonTitle>Elasticsearch</IonTitle> <IonButtons slot="primary"> <Details /> </IonButtons> </IonToolbar> </IonHeader> <IonContent> {isFetching ? <IonProgressBar slot="fixed" type="indeterminate" color="primary" /> : null} <IonGrid> <IonRow> <IonCol> <IonCard> <IonCardContent> <IonSegment value={activeSegment} onIonChange={(e) => setActiveSegment(e.detail.value as string)}> <IonSegmentButton value="query"> <IonLabel>Query</IonLabel> </IonSegmentButton> <IonSegmentButton value="options"> <IonLabel>Options</IonLabel> </IonSegmentButton> </IonSegment> {activeSegment === 'query' ? ( <IonGrid> <IonRow> <IonCol sizeXs="12" sizeSm="12" sizeMd="12" sizeLg="10" sizeXl="10"> <IonItem> <IonInput type="text" required={true} placeholder="Query" value={query} onInput={handleQuery} /> </IonItem> </IonCol> <IonCol sizeXs="12" sizeSm="12" sizeMd="12" sizeLg="2" sizeXl="2"> <IonButton expand="block" onClick={() => runQuery(false)}> Search </IonButton> </IonCol> </IonRow> </IonGrid> ) : null} {activeSegment === 'options' ? ( <IonGrid> <IonRow> <IonCol sizeXs="12" sizeSm="12" sizeMd="12" sizeLg="6" sizeXl="6"> <IonItem> <IonLabel position="stacked">From</IonLabel> <IonInput type="text" required={true} placeholder="From" value={from} onInput={handleFrom} /> </IonItem> </IonCol> <IonCol sizeXs="12" sizeSm="12" sizeMd="12" sizeLg="6" sizeXl="6"> <IonItem> <IonLabel position="stacked">To</IonLabel> <IonInput type="text" required={true} placeholder="To" value={to} onInput={handleTo} /> </IonItem> </IonCol> </IonRow> <IonRow> <IonCol sizeXs="12" sizeSm="12" sizeMd="12" sizeLg="12" sizeXl="12"> <IonList> <IonListHeader mode="md"> <IonLabel>Selected Fields</IonLabel> </IonListHeader> {selectedFields.map((field, index) => ( <IonItem key={index} button={true} onClick={() => removeField(field)}> {field} </IonItem> ))} <IonListHeader mode="md"> <IonLabel>Fields</IonLabel> </IonListHeader> {fields.map((field, index) => ( <IonItem key={index} button={true} onClick={() => addField(field)}> {field} </IonItem> ))} </IonList> </IonCol> </IonRow> </IonGrid> ) : null} </IonCardContent> </IonCard> </IonCol> </IonRow> {aggregations && aggregations.logcount && aggregations.logcount.buckets && aggregations.logcount.buckets.length > 0 ? ( <IonRow> <IonCol> <IonCard> <IonCardContent> {hits ? ( <div style={{ textAlign: 'center' }}> <b>{hits}</b> hits </div> ) : null} <Chart aggregations={aggregations} /> </IonCardContent> </IonCard> </IonCol> </IonRow> ) : null} {error || documents.length > 0 ? ( <IonRow> <IonCol> <IonCard> <IonCardContent> {error ? ( error ) : ( <React.Fragment> {isPlatform('hybrid') || isPlatform('mobile') || width < 992 ? ( <IonList> {documents.map((document, index) => ( <Document key={index} layout="item" document={document} fields={selectedFields} /> ))} </IonList> ) : ( <div className="table-multi-line"> <table> <thead> <tr> <th>@timestamp</th> {selectedFields.length === 0 ? ( <th>message</th> ) : ( selectedFields.map((field) => <th key={field}>{field}</th>) )} </tr> </thead> <tbody> {documents.map((document, index) => ( <Document key={index} layout="table" document={document} fields={selectedFields} /> ))} </tbody> </table> </div> )} <IonInfiniteScroll threshold="25%" disabled={isFetching || documents.length > 5000} onIonInfinite={() => runQuery(true)} > <IonInfiniteScrollContent loadingText="Loading more Documents..."></IonInfiniteScrollContent> </IonInfiniteScroll> </React.Fragment> )} </IonCardContent> </IonCard> </IonCol> </IonRow> ) : null} </IonGrid> </IonContent> </IonPage> ); }; export default memo(QueryPage, (): boolean => { return true; });
the_stack
import path from 'path'; import { DynamicPool, isTimeoutError, StaticPool } from '../src'; import { Pool } from '../src/pool'; const TASK_NUM = 4; function wait(t: number) { return new Promise((resolve) => { setTimeout(resolve, t); }); } describe('pool tests', () => { it('should throw error if size is not number', () => { expect(() => { new Pool('a' as unknown as number); }).toThrowError(TypeError); }); it('should throw error if size is NaN', () => { expect(() => { new Pool(NaN); }).toThrowError('"size" must not be NaN!'); }); it('should throw error if size < 1', () => { expect(() => { new Pool(0); }).toThrowError(RangeError); }); it('should throw error if pool is deprecated', async () => { const pool = new Pool(5); pool.destroy(); try { await pool.runTask(null, {}); } catch (err) { expect(err.message).toBe('This pool is deprecated! Please use a new one.'); } }); }); describe('static pool tests', () => { it('should throw error if task is not string or function', () => { expect(() => { new StaticPool({ size: TASK_NUM, task: 1 as unknown as string }); }).toThrowError(TypeError); }); it('should throw error if param is function', async () => { const pool = new StaticPool({ size: TASK_NUM, task(n) { return n; } }); expect.assertions(1); try { await pool.exec(() => {}); } catch (error) { expect(error).toBeInstanceOf(TypeError); } pool.destroy(); }); it('test task function with workerData', async () => { const pool = new StaticPool({ size: TASK_NUM, workerData: 10, task: function (n: number) { return this.workerData * n; } }); const execArr = []; for (let i = 0; i < 10; i++) { execArr.push(pool.exec(i)); } const resArr = await Promise.all(execArr); expect(resArr).toEqual([0, 10, 20, 30, 40, 50, 60, 70, 80, 90]); pool.destroy(); }); it('test worker file', async () => { const workerData = 100; const pool = new StaticPool({ task: path.resolve(__dirname, 'add.js'), size: TASK_NUM, workerData }); const paramArr = [0, 11, 12, 13, 14]; const expectResArr = paramArr.map((n) => n + workerData); const execArr = paramArr.map((n) => pool.exec(n)); const resArr = await Promise.all(execArr); expect(resArr).toEqual(expectResArr); pool.destroy(); }); it('test no param', async () => { const pool = new StaticPool({ task: () => undefined, size: TASK_NUM }); expect(await pool.exec()).toBe(undefined); pool.destroy(); }); it("test 'this' reference", async () => { const data = 10; let pool, res; pool = new StaticPool({ size: TASK_NUM, workerData: data, task() { //@ts-ignore return this.workerData; } }); res = await pool.exec(); expect(res).toBe(data); pool.destroy(); pool = new StaticPool({ size: TASK_NUM, workerData: data, task: () => { // @ts-ignore return this.workerData; } }); res = await pool.exec(); expect(res).toBe(data); pool.destroy(); }); it("test 'this' reference under strict mode", async () => { function task() { 'use strict'; //@ts-ignore return this.workerData; } const pool = new StaticPool({ size: TASK_NUM, task, workerData: 10 }); expect(await pool.exec()).toBe(10); pool.destroy(); }); }); function add20() { //@ts-ignore return this.workerData + 20; } function sub10() { //@ts-ignore return this.workerData - 10; } function mult10() { //@ts-ignore return this.workerData * 10; } function div10() { //@ts-ignore return this.workerData / 10; } describe('dynamic pool tests', () => { it('test basic function', async () => { const pool = new DynamicPool(TASK_NUM); const execArr = []; execArr.push( pool.exec({ task: add20, workerData: 20 }) ); execArr.push( pool.exec({ task: sub10, workerData: 20 }) ); execArr.push( pool.exec({ task: mult10, workerData: 20 }) ); execArr.push( pool.exec({ task: div10, workerData: 20 }) ); const resArr = await Promise.all(execArr); expect(resArr).toEqual([40, 10, 200, 2]); pool.destroy(); }); it("test 'this' reference", async () => { const pool = new DynamicPool(TASK_NUM); const data = 10; let res = await pool.exec({ workerData: data, task() { //@ts-ignore return this.workerData; } }); expect(res).toBe(data); res = await pool.exec({ workerData: data, task: () => { // @ts-ignore return this.workerData; } }); expect(res).toBe(data); pool.destroy(); }); it("test 'this' reference under strict mode", async () => { function task() { 'use strict'; //@ts-ignore return this.workerData; } const pool = new DynamicPool(TASK_NUM); const res = await pool.exec({ task, workerData: 10 }); expect(res).toBe(10); pool.destroy(); }); it('should throw error if task is not function', async () => { const pool = new DynamicPool(TASK_NUM); expect.assertions(1); try { pool.exec({ // @ts-ignore task: 1 }); } catch (error) { expect(error).toBeInstanceOf(TypeError); } pool.destroy(); }); it('should param field work', async () => { const pool = new DynamicPool(1); const res = await pool.exec({ task: (n) => n + 1, param: 10 }); expect(res).toBe(11); pool.destroy(); }); }); describe('error tests', () => { it('error static pool test', async () => { const pool = new StaticPool({ task: (n) => { if (n < 0) { throw new Error('err'); } return n + 1; }, size: TASK_NUM }); for (let i = 0; i < TASK_NUM; i++) { try { await pool.exec(-1); } catch (err) { expect(err.message).toBe('err'); } } for (let i = 0; i < TASK_NUM; i++) { const res = await pool.exec(i); expect(res).toBe(i + 1); } pool.destroy(); }); it('test dynamic pool error', async () => { const pool = new DynamicPool(TASK_NUM); for (let i = 0; i < TASK_NUM; i++) { try { await pool.exec({ task() { const workerData = this.workerData; if (workerData < 0) { throw new Error('err'); } return workerData + 1; }, workerData: -1 }); } catch (err) { expect(err.message).toBe('err'); } } for (let i = 0; i < TASK_NUM; i++) { try { const res = await pool.exec({ task() { if (this.workerData! < 0) { throw new Error('err'); } return this.workerData + 1; }, workerData: i }); expect(res).toBe(i + 1); } catch (err) { expect(err).toBe(null); } } pool.destroy(); }); }); describe('timeout tests', () => { it('test static pool with timeout', async () => { const pool = new StaticPool({ size: TASK_NUM, task() { while (true); } }); await wait(500); expect.assertions(1); try { await pool.createExecutor().setTimeout(1000).exec(); } catch (err) { expect(isTimeoutError(err)).toBe(true); } pool.destroy(); }); it('should static pool pass within timeout', async () => { const pool = new StaticPool({ size: TASK_NUM, task() { return 1; } }); const res = await pool.createExecutor().setTimeout(1000).exec(); expect(res).toBe(1); pool.destroy(); }); it('should static pool recover after timeout', async () => { const pool = new StaticPool({ size: 1, task() { let i = 1 << 30; while (i--); return 0; } }); let timeoutError: Error | undefined; expect.assertions(2); try { await pool.createExecutor().setTimeout(1).exec(); } catch (error) { if (isTimeoutError(error)) { timeoutError = error; const result = await pool.exec(); expect(result).toBe(0); } } expect(timeoutError).not.toBeUndefined(); pool.destroy(); }); it('test dynamic pool with timeout', async () => { const pool = new DynamicPool(TASK_NUM); expect.assertions(1); try { await pool.exec({ task() { while (true); }, timeout: 1000 }); } catch (err) { expect(isTimeoutError(err)).toBe(true); } pool.destroy(); }); it('should dynamic pool pass within timeout', async () => { const pool = new DynamicPool(TASK_NUM); const res = await pool.exec({ task() { return 1; }, timeout: 1000 }); expect(res).toBe(1); pool.destroy(); }); }); describe('async task function tests', () => { it('should static pool work with async task', async () => { const pool = new StaticPool({ size: 1, task: async function (n) { return n; } }); const res = await pool.exec(1); expect(res).toBe(1); pool.destroy(); }); it('should dynamic pool work with async task', async () => { const pool = new DynamicPool(1); const res = await pool.exec({ task: async function () { return this.workerData; }, workerData: 1 }); expect(res).toBe(1); pool.destroy(); }); }); describe('SHARE_ENV tests', () => { const { promisify } = require('util'); const exec = promisify(require('child_process').exec); it('should pass', async () => { await exec('node ./__test__/shareEnv.js'); }); }); describe('resourceLimits tests', () => { const STACK_SIZE_MB = 16; function shouldSetResourceLimits(pool: Pool) { return new Promise((resolve, reject) => { pool.once('worker-ready', (worker) => { const stackSizeMb = worker.resourceLimits.stackSizeMb; if (stackSizeMb === STACK_SIZE_MB) { resolve(undefined); } else { reject(`stackSizeMb is ${stackSizeMb}`); } }); }); } it('should static pool created with resourceLimits', async () => { const pool = new StaticPool({ size: 1, task() {}, resourceLimits: { stackSizeMb: STACK_SIZE_MB } }); try { await shouldSetResourceLimits(pool); } catch (error) { throw error; } finally { pool.destroy(); } }); it('should dynamic pool created with resourceLimits', async () => { const pool = new DynamicPool(1, { resourceLimits: { stackSizeMb: STACK_SIZE_MB } }); try { await shouldSetResourceLimits(pool); } catch (error) { throw error; } finally { pool.destroy(); } }); }); describe('task executor tests', () => { it('should static pool set timeout', async () => { const pool = new StaticPool({ size: 1, task() { while (true); } }); try { await pool.createExecutor().setTimeout(500).exec(); } catch (error) { expect(isTimeoutError(error)).toBe(true); } finally { pool.destroy(); } }); it('should static pool set transferList', async () => { const pool = new StaticPool({ size: 1, task() {} }); const buf = new ArrayBuffer(16); expect(buf.byteLength).toBe(16); await pool.createExecutor().setTransferList([buf]).exec(); expect(buf.byteLength).toBe(0); pool.destroy(); }); it('should throw when static pool executor run multiple time', async () => { const pool = new StaticPool({ size: 2, task: () => {} }); const executor = pool.createExecutor(); await executor.exec(); try { await executor.exec(); } catch (error) { expect(error).toEqual(new Error('task executor is already called!')); } pool.destroy(); }); it('should dynamic pool set timeout', async () => { const pool = new DynamicPool(1); try { await pool .createExecutor(() => { while (true); }) .setTimeout(500) .exec(); } catch (error) { expect(isTimeoutError(error)).toBe(true); } finally { pool.destroy(); } }); it('should dynamic pool set transferList', async () => { const pool = new DynamicPool(1); const buf = new ArrayBuffer(16); expect(buf.byteLength).toBe(16); await pool .createExecutor(() => {}) .setTransferList([buf]) .exec(); expect(buf.byteLength).toBe(0); pool.destroy(); }); it('should throw when dynamic pool executor run multiple time', async () => { const pool = new DynamicPool(2); const executor = pool.createExecutor(() => {}); await executor.exec(); try { await executor.exec(); } catch (error) { expect(error).toEqual(new Error('task executor is already called!')); } pool.destroy(); }); }); describe('require function tests', () => { it('should static pool require module using this.require', async () => { const pool = new StaticPool({ size: 1, task() { const os = this.require('os'); return os.cpus().length; } }); const cpus = await pool.exec(); expect(cpus).toBeGreaterThan(0); pool.destroy(); }); it('should static pool require module using this.require when using arrow function task', async () => { const pool = new StaticPool({ size: 1, task: () => { // @ts-ignore const os = this.require('os'); return os.cpus().length; } }); const cpus = await pool.exec(); expect(cpus).toBeGreaterThan(0); pool.destroy(); }); it('should dynamic pool require module using this.require', async () => { const pool = new DynamicPool(2); const cpus = await pool .createExecutor(function () { const os = this.require('os'); return os.cpus().length; }) .exec(); expect(cpus).toBeGreaterThan(0); pool.destroy(); }); it('should dynamic pool require module using this.require when using arrow function task', async () => { const pool = new DynamicPool(2); const cpus = await pool .createExecutor(() => { // @ts-ignore const os = this.require('os'); return os.cpus().length; }) .exec(); expect(cpus).toBeGreaterThan(0); pool.destroy(); }); });
the_stack
import type { Uri } from '@velcro/common'; import type { BinaryOperator, Function, Identifier, MemberExpression, Node, Pattern } from 'estree'; import MagicString from 'magic-string'; import type { ParserFunction } from '../parsing'; import type { DEFAULT_SHIM_GLOBALS } from '../shims'; import { SourceModuleDependency } from '../sourceModuleDependency'; import { isArrayPattern, isArrowFunctionExpression, isAssignmentPattern, isBinaryExpression, isBlockStatement, isCallExpression, isClassDeclaration, isFunction, isFunctionDeclaration, isFunctionExpression, isIdentifier, isIfStatement, isMemberExpression, isMethodDefinition, isObjectPattern, isProgram, isProperty, isRestElement, isStringLiteral, isTemplateLiteral, isThisExpression, isTryStatement, isUnaryExpression, isVariableDeclaration, NodeWithParent, parse as parseAst, } from './ast'; import { traverse } from './traverse'; import type { Visitor } from './traverse'; declare module 'estree' { export interface BaseNodeWithoutComments { start: number; end: number; } } export const parse = function parseJavaScript( uri: Uri, code: string, options: { globalModules: typeof DEFAULT_SHIM_GLOBALS; nodeEnv: string; } ): ReturnType<ParserFunction> { const visitorCtx: DependencyVisitorContext = { unboundSymbols: new Map(), locals: new Map(), magicString: new MagicString(code, { filename: uri.toString(), indentExclusionRanges: [] }), nodeEnv: options.nodeEnv, replacedSymbols: new Set<Identifier>(), requires: [], requireResolves: [], skip: new Set(), skipTransform: new Set(), }; const dependencies = [] as SourceModuleDependency[]; try { // let lastToken: Token | undefined; const ast = parseAst(code, { // onComment: (_isBlock, _test, start, end) => { // result.changes.push({ type: 'remove', start, end }); // }, // onInsertedSemicolon(lastTokEnd) { // result.changes.push({ type: 'appendRight', position: lastTokEnd, value: ';' }); // }, // onToken: (token) => { // const start = lastToken ? lastToken.end + 1 : 0; // const end = token.start; // if (end > start) { // result.changes.push({ type: 'remove', start, end }); // } // lastToken = token; // }, }); traverse(ast, visitorCtx, scopingAndRequiresVisitor); traverse(ast, visitorCtx, collectGlobalsVisitor); } catch (err) { // console.debug(code); // console.trace(err); throw new Error(`Error parsing ${uri}: ${err.message}`); } // Handle explicit requires const requiresBySpec = new Map<string, Array<{ start: number; end: number }>>(); for (const requireDependency of visitorCtx.requires) { let locations = requiresBySpec.get(requireDependency.spec.value); if (!locations) { locations = []; requiresBySpec.set(requireDependency.spec.value, locations); } locations.push({ start: requireDependency.spec.start, end: requireDependency.spec.end }); } for (const [spec, locations] of requiresBySpec) { dependencies.push(SourceModuleDependency.fromRequire(spec, locations)); } // Handle require.resolve const requireResolvesBySpec = new Map<string, Array<{ start: number; end: number }>>(); for (const requireDependency of visitorCtx.requireResolves) { let locations = requiresBySpec.get(requireDependency.spec.value); if (!locations) { locations = []; requiresBySpec.set(requireDependency.spec.value, locations); } locations.push({ start: requireDependency.spec.start, end: requireDependency.spec.end }); } for (const [spec, locations] of requireResolvesBySpec) { dependencies.push(SourceModuleDependency.fromRequireResolve(spec, locations)); } for (const [symbolName, locations] of visitorCtx.unboundSymbols) { const shim = options.globalModules[symbolName]; if (shim) { dependencies.push(SourceModuleDependency.fromGlobalObject(shim.spec, locations, shim.export)); for (const location of locations) { visitorCtx.magicString.overwrite( location.start, location.end, `require(${JSON.stringify(`${shim.spec}`)})${shim.export ? `.${shim.export}` : ''}` ); } } } return { code: visitorCtx.magicString, dependencies, }; }; export type CommonJsRequire = { callee: { start: number; end: number }; spec: { start: number; end: number; value: string }; }; export type CommonJsRequireResolve = { callee: { start: number; end: number }; spec: { start: number; end: number; value: string }; }; export type DependencyVisitorContext = { readonly unboundSymbols: Map<string, Node[]>; readonly locals: Map<Node, { [identifier: string]: boolean }>; readonly magicString: MagicString; readonly nodeEnv: string; readonly requires: CommonJsRequire[]; readonly replacedSymbols: Set<Identifier>; readonly requireResolves: CommonJsRequireResolve[]; readonly skip: Set<Node>; readonly skipTransform: Set<Node>; }; export const scopingAndRequiresVisitor: Visitor<DependencyVisitorContext> = { enter(node, parent, ctx) { // Get AST-node level locations in the source map ctx.magicString.addSourcemapLocation(node.start); ctx.magicString.addSourcemapLocation(node.end); if (ctx.skip.has(node)) { return this.skip(); } visitAndCaptureScoping(node, parent, ctx); visitAndSkipBranches(node, parent, ctx); visitRequires(node, parent, ctx); }, leave(node, _parent, ctx) { let skipped = false; let nextCheck: NodeWithParent<Node> | undefined = node; while (nextCheck) { if (ctx.skipTransform.has(nextCheck)) { skipped = true; break; } nextCheck = nextCheck.parent as NodeWithParent<Node> | undefined; } if ( !skipped && isMemberExpression(node) && memberExpressionMatches(node, 'process.env.NODE_ENV') ) { ctx.magicString.overwrite(node.start, node.end, JSON.stringify(ctx.nodeEnv), { contentOnly: true, storeName: true, }); ctx.skip.add(node); ctx.skipTransform.add(node); } }, }; export const collectGlobalsVisitor: Visitor<DependencyVisitorContext> = { enter(node, _parent, ctx) { if (ctx.skip.has(node)) { return this.skip(); } if (isBindingIdentifier(node) && isIdentifier(node) && !isArgumentOfTypeOf(node)) { var name = node.name; if (name === 'undefined') return; if (ctx.replacedSymbols.has(node)) { return; } let foundBinding = false; let nextParent = node.parent; while (nextParent) { if (name === 'arguments' && declaresArguments(nextParent)) { foundBinding = true; break; } const locals = ctx.locals.get(nextParent); if (locals && locals[name]) { foundBinding = true; break; } nextParent = nextParent.parent; } if (!foundBinding) { let unboundSymbols = ctx.unboundSymbols.get(name); if (!unboundSymbols) { unboundSymbols = []; ctx.unboundSymbols.set(name, unboundSymbols); } unboundSymbols.push(node); } } else if (isThisExpression(node)) { let foundBinding = false; let nextParent = node.parent; while (nextParent) { if (declaresThis(nextParent)) { foundBinding = true; break; } nextParent = nextParent.parent; } if (!foundBinding) { let unboundSymbols = ctx.unboundSymbols.get('this'); if (!unboundSymbols) { unboundSymbols = []; ctx.unboundSymbols.set('this', unboundSymbols); } unboundSymbols.push(node); } } }, }; function visitAndCaptureScoping( node: NodeWithParent, _parent: NodeWithParent | null, ctx: DependencyVisitorContext ) { if (isVariableDeclaration(node)) { let parent: NodeWithParent | undefined; let nextParent = node.parent; while (nextParent) { if (node.kind === 'var' ? isScope(nextParent) : isBlockScope(nextParent)) { parent = nextParent; break; } nextParent = nextParent.parent; } if (!parent) { throw new Error(`Invariant violation: Failed to find a parent`); } let locals = ctx.locals.get(parent); if (!locals) { locals = {}; ctx.locals.set(parent, locals); } for (const declaration of node.declarations) { declarePattern(declaration.id, locals); } } else if (isFunctionDeclaration(node)) { let parent: NodeWithParent | undefined; let nextParent = node.parent; if (nextParent && nextParent.parent) { nextParent = nextParent.parent; } while (nextParent) { if (isScope(nextParent)) { parent = nextParent; break; } nextParent = nextParent.parent; } if (!parent) { throw new Error(`Invariant violation: Failed to find a parent`); } let locals = ctx.locals.get(parent); if (!locals) { locals = {}; ctx.locals.set(parent, locals); } declareFunction(node, locals); } else if (isFunction(node)) { let locals = ctx.locals.get(node); if (!locals) { locals = {}; ctx.locals.set(node, locals); } declareFunction(node, locals); } else if (isClassDeclaration(node) && node.id) { let parent: NodeWithParent | undefined; let nextParent = node.parent; if (nextParent && nextParent.parent) { nextParent = nextParent.parent; } while (nextParent) { if (isScope(nextParent)) { parent = nextParent; break; } nextParent = nextParent.parent; } if (!parent) { throw new Error(`Invariant violation: Failed to find a parent`); } let locals = ctx.locals.get(parent); if (!locals) { locals = {}; ctx.locals.set(parent, locals); } locals[node.id.name] = true; } else if (isTryStatement(node)) { if (node.handler) { let locals = ctx.locals.get(node.handler); if (!locals) { locals = {}; ctx.locals.set(node.handler, locals); } if (node.handler.param) { declarePattern(node.handler.param, locals); } } } } function visitAndSkipBranches( node: NodeWithParent, _parent: NodeWithParent | null, ctx: DependencyVisitorContext ) { if (isIfStatement(node) && isBinaryExpression(node.test)) { const tests = { '!=': (l: string, r: string) => l != r, '!==': (l: string, r: string) => l !== r, '==': (l: string, r: string) => l == r, '===': (l: string, r: string) => l === r, } as { [key in BinaryOperator]: (l: string, r: string) => boolean }; const test = tests[node.test.operator]; if (test) { if ( isStringLiteral(node.test.left) && isMemberExpression(node.test.right) && memberExpressionMatches(node.test.right, 'process.env.NODE_ENV') ) { let rootObject = node.test.right; while (isMemberExpression(rootObject.object)) { rootObject = rootObject.object; } if (isIdentifier(rootObject.object)) { ctx.replacedSymbols.add(rootObject.object); } ctx.skipTransform.add(node.test.right); // if ('development' === process.env.NODE_ENV) {} if (!test(node.test.left.value, ctx.nodeEnv)) { ctx.skip.add(node.consequent); // We can blow away the consequent ctx.magicString.remove( node.start, node.alternate ? node.alternate.start : node.consequent.end ); } else { // We can blow away the test ctx.magicString.remove(node.start, node.consequent.start - 1); if (node.alternate) { ctx.skip.add(node.alternate); // We can blow away the alternate but we need to start and the end of the consequent + 1 char ctx.magicString.remove(node.consequent.end + 1, node.alternate.end); } } } else if ( isStringLiteral(node.test.right) && isMemberExpression(node.test.left) && memberExpressionMatches(node.test.left, 'process.env.NODE_ENV') ) { let rootObject = node.test.left; while (isMemberExpression(rootObject.object)) { rootObject = rootObject.object; } if (isIdentifier(rootObject.object)) { ctx.replacedSymbols.add(rootObject.object); } ctx.skipTransform.add(node.test.left); // if (process.env.NODE_ENV === 'development') {} if (!test(node.test.right.value, ctx.nodeEnv)) { ctx.skip.add(node.consequent); // We can blow away the consequent ctx.magicString.remove( node.start, node.alternate ? node.alternate.start : node.consequent.end ); } else { // We can blow away the test and the alternate ctx.magicString.remove(node.start, node.consequent.start - 1); if (node.alternate) { ctx.skip.add(node.alternate); // We can blow away the alternate but we need to start and the end of the consequent + 1 char ctx.magicString.remove(node.consequent.end + 1, node.alternate.end); } } } } } } function visitRequires( node: NodeWithParent, _parent: NodeWithParent | null, ctx: DependencyVisitorContext ) { if (isCallExpression(node)) { const callee = node.callee; if (isIdentifier(callee) && callee.name === 'require') { const firstArg = node.arguments[0]; if (isStringLiteral(firstArg)) { ctx.requires.push({ spec: { start: firstArg.start, end: firstArg.end, value: firstArg.value }, callee: { start: callee.start, end: callee.end }, }); } else if ( isTemplateLiteral(firstArg) && firstArg.expressions.length === 0 && firstArg.quasis.length === 1 ) { ctx.requires.push({ spec: { start: firstArg.quasis[0].start, end: firstArg.quasis[0].end, value: firstArg.quasis[0].value.raw, }, callee: { start: callee.start, end: callee.end }, }); } else { console.warn('Non string-literal first arg to require', firstArg); } } else if ( isMemberExpression(callee) && isIdentifier(callee.object) && callee.object.name === 'require' && isIdentifier(callee.property) && callee.property.name === 'resolve' ) { const firstArg = node.arguments[0]; if (isStringLiteral(firstArg)) { ctx.requireResolves.push({ spec: { start: firstArg.start, end: firstArg.end, value: firstArg.value }, callee: { start: callee.start, end: callee.end }, }); } else { console.warn('Non string-literal first arg to require.resolve', firstArg); } } } } function declareFunction(node: Function, locals: { [name: string]: boolean }) { node.params.forEach(function (node) { declarePattern(node, locals); }); if ((node as any).id) { locals[(node as any).id.name] = true; } } function declarePattern(node: Pattern, locals: { [name: string]: boolean }) { if (isIdentifier(node)) { locals[node.name] = true; } else if (isObjectPattern(node)) { node.properties.forEach((node) => isRestElement(node) ? declarePattern(node.argument, locals) : declarePattern(node.value, locals) ); } else if (isArrayPattern(node)) { node.elements.forEach((node) => node && declarePattern(node, locals)); } else if (isRestElement(node)) { declarePattern(node.argument, locals); } else if (isAssignmentPattern(node)) { declarePattern(node.left, locals); } else { throw new Error(`Invariant violation: Unexpected pattern type: ${node.type}`); } } function isArgumentOfTypeOf(node: NodeWithParent) { const parent = node.parent as Node; return isUnaryExpression(parent) && parent.operator === 'typeof'; } function isBindingIdentifier(node: NodeWithParent) { return ( isIdentifier(node) && !isPropertyOfMemberExpression(node) && !isKeyOfProperty(node) && !isKeyOfMethodDefinition(node) ); } function isKeyOfProperty(node: NodeWithParent) { return node.parent && isProperty(node.parent) && node.parent.key === node; } function isPropertyOfMemberExpression(node: NodeWithParent) { return node.parent && isMemberExpression(node.parent) && node.parent.object !== node; } function isKeyOfMethodDefinition(node: NodeWithParent) { return node.parent && isMethodDefinition(node.parent); } function isScope(node: NodeWithParent) { return ( isFunctionDeclaration(node) || isFunctionExpression(node) || isArrowFunctionExpression(node) || isProgram(node) ); } function isBlockScope(node: NodeWithParent) { return isBlockStatement(node) || isScope(node); } function declaresArguments(node: NodeWithParent) { return isFunctionDeclaration(node) || isFunctionExpression(node); } function declaresThis(node: NodeWithParent) { return isFunctionDeclaration(node) || isFunctionExpression(node); } function memberExpressionMatches(node: MemberExpression, pattern: string) { const memberParts = pattern.split('.'); if (memberParts.length < 2) { return false; } const object = memberParts.shift(); const property = memberParts.shift(); for (let i = memberParts.length - 1; i >= 0; i--) { if (!isIdentifier(node.property) || node.property.name !== memberParts[i]) { return false; } if (!isMemberExpression(node.object)) { return false; } node = node.object; } if (!isIdentifier(node.object) || !isIdentifier(node.property)) { return false; } return node.object.name === object && node.property.name === property; }
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class CustomerProfiles extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: CustomerProfiles.Types.ClientConfiguration) config: Config & CustomerProfiles.Types.ClientConfiguration; /** * Associates a new key value with a specific profile, such as a Contact Trace Record (CTR) ContactId. A profile object can have a single unique key and any number of additional keys that can be used to identify the profile that it belongs to. */ addProfileKey(params: CustomerProfiles.Types.AddProfileKeyRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.AddProfileKeyResponse) => void): Request<CustomerProfiles.Types.AddProfileKeyResponse, AWSError>; /** * Associates a new key value with a specific profile, such as a Contact Trace Record (CTR) ContactId. A profile object can have a single unique key and any number of additional keys that can be used to identify the profile that it belongs to. */ addProfileKey(callback?: (err: AWSError, data: CustomerProfiles.Types.AddProfileKeyResponse) => void): Request<CustomerProfiles.Types.AddProfileKeyResponse, AWSError>; /** * Creates a domain, which is a container for all customer data, such as customer profile attributes, object types, profile keys, and encryption keys. You can create multiple domains, and each domain can have multiple third-party integrations. Each Amazon Connect instance can be associated with only one domain. Multiple Amazon Connect instances can be associated with one domain. */ createDomain(params: CustomerProfiles.Types.CreateDomainRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.CreateDomainResponse) => void): Request<CustomerProfiles.Types.CreateDomainResponse, AWSError>; /** * Creates a domain, which is a container for all customer data, such as customer profile attributes, object types, profile keys, and encryption keys. You can create multiple domains, and each domain can have multiple third-party integrations. Each Amazon Connect instance can be associated with only one domain. Multiple Amazon Connect instances can be associated with one domain. */ createDomain(callback?: (err: AWSError, data: CustomerProfiles.Types.CreateDomainResponse) => void): Request<CustomerProfiles.Types.CreateDomainResponse, AWSError>; /** * Creates a standard profile. A standard profile represents the following attributes for a customer profile in a domain. */ createProfile(params: CustomerProfiles.Types.CreateProfileRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.CreateProfileResponse) => void): Request<CustomerProfiles.Types.CreateProfileResponse, AWSError>; /** * Creates a standard profile. A standard profile represents the following attributes for a customer profile in a domain. */ createProfile(callback?: (err: AWSError, data: CustomerProfiles.Types.CreateProfileResponse) => void): Request<CustomerProfiles.Types.CreateProfileResponse, AWSError>; /** * Deletes a specific domain and all of its customer data, such as customer profile attributes and their related objects. */ deleteDomain(params: CustomerProfiles.Types.DeleteDomainRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.DeleteDomainResponse) => void): Request<CustomerProfiles.Types.DeleteDomainResponse, AWSError>; /** * Deletes a specific domain and all of its customer data, such as customer profile attributes and their related objects. */ deleteDomain(callback?: (err: AWSError, data: CustomerProfiles.Types.DeleteDomainResponse) => void): Request<CustomerProfiles.Types.DeleteDomainResponse, AWSError>; /** * Removes an integration from a specific domain. */ deleteIntegration(params: CustomerProfiles.Types.DeleteIntegrationRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.DeleteIntegrationResponse) => void): Request<CustomerProfiles.Types.DeleteIntegrationResponse, AWSError>; /** * Removes an integration from a specific domain. */ deleteIntegration(callback?: (err: AWSError, data: CustomerProfiles.Types.DeleteIntegrationResponse) => void): Request<CustomerProfiles.Types.DeleteIntegrationResponse, AWSError>; /** * Deletes the standard customer profile and all data pertaining to the profile. */ deleteProfile(params: CustomerProfiles.Types.DeleteProfileRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.DeleteProfileResponse) => void): Request<CustomerProfiles.Types.DeleteProfileResponse, AWSError>; /** * Deletes the standard customer profile and all data pertaining to the profile. */ deleteProfile(callback?: (err: AWSError, data: CustomerProfiles.Types.DeleteProfileResponse) => void): Request<CustomerProfiles.Types.DeleteProfileResponse, AWSError>; /** * Removes a searchable key from a customer profile. */ deleteProfileKey(params: CustomerProfiles.Types.DeleteProfileKeyRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.DeleteProfileKeyResponse) => void): Request<CustomerProfiles.Types.DeleteProfileKeyResponse, AWSError>; /** * Removes a searchable key from a customer profile. */ deleteProfileKey(callback?: (err: AWSError, data: CustomerProfiles.Types.DeleteProfileKeyResponse) => void): Request<CustomerProfiles.Types.DeleteProfileKeyResponse, AWSError>; /** * Removes an object associated with a profile of a given ProfileObjectType. */ deleteProfileObject(params: CustomerProfiles.Types.DeleteProfileObjectRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.DeleteProfileObjectResponse) => void): Request<CustomerProfiles.Types.DeleteProfileObjectResponse, AWSError>; /** * Removes an object associated with a profile of a given ProfileObjectType. */ deleteProfileObject(callback?: (err: AWSError, data: CustomerProfiles.Types.DeleteProfileObjectResponse) => void): Request<CustomerProfiles.Types.DeleteProfileObjectResponse, AWSError>; /** * Removes a ProfileObjectType from a specific domain as well as removes all the ProfileObjects of that type. It also disables integrations from this specific ProfileObjectType. In addition, it scrubs all of the fields of the standard profile that were populated from this ProfileObjectType. */ deleteProfileObjectType(params: CustomerProfiles.Types.DeleteProfileObjectTypeRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.DeleteProfileObjectTypeResponse) => void): Request<CustomerProfiles.Types.DeleteProfileObjectTypeResponse, AWSError>; /** * Removes a ProfileObjectType from a specific domain as well as removes all the ProfileObjects of that type. It also disables integrations from this specific ProfileObjectType. In addition, it scrubs all of the fields of the standard profile that were populated from this ProfileObjectType. */ deleteProfileObjectType(callback?: (err: AWSError, data: CustomerProfiles.Types.DeleteProfileObjectTypeResponse) => void): Request<CustomerProfiles.Types.DeleteProfileObjectTypeResponse, AWSError>; /** * Returns information about a specific domain. */ getDomain(params: CustomerProfiles.Types.GetDomainRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.GetDomainResponse) => void): Request<CustomerProfiles.Types.GetDomainResponse, AWSError>; /** * Returns information about a specific domain. */ getDomain(callback?: (err: AWSError, data: CustomerProfiles.Types.GetDomainResponse) => void): Request<CustomerProfiles.Types.GetDomainResponse, AWSError>; /** * Returns an integration for a domain. */ getIntegration(params: CustomerProfiles.Types.GetIntegrationRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.GetIntegrationResponse) => void): Request<CustomerProfiles.Types.GetIntegrationResponse, AWSError>; /** * Returns an integration for a domain. */ getIntegration(callback?: (err: AWSError, data: CustomerProfiles.Types.GetIntegrationResponse) => void): Request<CustomerProfiles.Types.GetIntegrationResponse, AWSError>; /** * Returns the object types for a specific domain. */ getProfileObjectType(params: CustomerProfiles.Types.GetProfileObjectTypeRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.GetProfileObjectTypeResponse) => void): Request<CustomerProfiles.Types.GetProfileObjectTypeResponse, AWSError>; /** * Returns the object types for a specific domain. */ getProfileObjectType(callback?: (err: AWSError, data: CustomerProfiles.Types.GetProfileObjectTypeResponse) => void): Request<CustomerProfiles.Types.GetProfileObjectTypeResponse, AWSError>; /** * Returns the template information for a specific object type. A template is a predefined ProfileObjectType, such as “Salesforce-Account” or “Salesforce-Contact.” When a user sends a ProfileObject, using the PutProfileObject API, with an ObjectTypeName that matches one of the TemplateIds, it uses the mappings from the template. */ getProfileObjectTypeTemplate(params: CustomerProfiles.Types.GetProfileObjectTypeTemplateRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.GetProfileObjectTypeTemplateResponse) => void): Request<CustomerProfiles.Types.GetProfileObjectTypeTemplateResponse, AWSError>; /** * Returns the template information for a specific object type. A template is a predefined ProfileObjectType, such as “Salesforce-Account” or “Salesforce-Contact.” When a user sends a ProfileObject, using the PutProfileObject API, with an ObjectTypeName that matches one of the TemplateIds, it uses the mappings from the template. */ getProfileObjectTypeTemplate(callback?: (err: AWSError, data: CustomerProfiles.Types.GetProfileObjectTypeTemplateResponse) => void): Request<CustomerProfiles.Types.GetProfileObjectTypeTemplateResponse, AWSError>; /** * Lists all of the integrations associated to a specific URI in the AWS account. */ listAccountIntegrations(params: CustomerProfiles.Types.ListAccountIntegrationsRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.ListAccountIntegrationsResponse) => void): Request<CustomerProfiles.Types.ListAccountIntegrationsResponse, AWSError>; /** * Lists all of the integrations associated to a specific URI in the AWS account. */ listAccountIntegrations(callback?: (err: AWSError, data: CustomerProfiles.Types.ListAccountIntegrationsResponse) => void): Request<CustomerProfiles.Types.ListAccountIntegrationsResponse, AWSError>; /** * Returns a list of all the domains for an AWS account that have been created. */ listDomains(params: CustomerProfiles.Types.ListDomainsRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.ListDomainsResponse) => void): Request<CustomerProfiles.Types.ListDomainsResponse, AWSError>; /** * Returns a list of all the domains for an AWS account that have been created. */ listDomains(callback?: (err: AWSError, data: CustomerProfiles.Types.ListDomainsResponse) => void): Request<CustomerProfiles.Types.ListDomainsResponse, AWSError>; /** * Lists all of the integrations in your domain. */ listIntegrations(params: CustomerProfiles.Types.ListIntegrationsRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.ListIntegrationsResponse) => void): Request<CustomerProfiles.Types.ListIntegrationsResponse, AWSError>; /** * Lists all of the integrations in your domain. */ listIntegrations(callback?: (err: AWSError, data: CustomerProfiles.Types.ListIntegrationsResponse) => void): Request<CustomerProfiles.Types.ListIntegrationsResponse, AWSError>; /** * Lists all of the template information for object types. */ listProfileObjectTypeTemplates(params: CustomerProfiles.Types.ListProfileObjectTypeTemplatesRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.ListProfileObjectTypeTemplatesResponse) => void): Request<CustomerProfiles.Types.ListProfileObjectTypeTemplatesResponse, AWSError>; /** * Lists all of the template information for object types. */ listProfileObjectTypeTemplates(callback?: (err: AWSError, data: CustomerProfiles.Types.ListProfileObjectTypeTemplatesResponse) => void): Request<CustomerProfiles.Types.ListProfileObjectTypeTemplatesResponse, AWSError>; /** * Lists all of the templates available within the service. */ listProfileObjectTypes(params: CustomerProfiles.Types.ListProfileObjectTypesRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.ListProfileObjectTypesResponse) => void): Request<CustomerProfiles.Types.ListProfileObjectTypesResponse, AWSError>; /** * Lists all of the templates available within the service. */ listProfileObjectTypes(callback?: (err: AWSError, data: CustomerProfiles.Types.ListProfileObjectTypesResponse) => void): Request<CustomerProfiles.Types.ListProfileObjectTypesResponse, AWSError>; /** * Returns a list of objects associated with a profile of a given ProfileObjectType. */ listProfileObjects(params: CustomerProfiles.Types.ListProfileObjectsRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.ListProfileObjectsResponse) => void): Request<CustomerProfiles.Types.ListProfileObjectsResponse, AWSError>; /** * Returns a list of objects associated with a profile of a given ProfileObjectType. */ listProfileObjects(callback?: (err: AWSError, data: CustomerProfiles.Types.ListProfileObjectsResponse) => void): Request<CustomerProfiles.Types.ListProfileObjectsResponse, AWSError>; /** * Displays the tags associated with an Amazon Connect Customer Profiles resource. In Connect Customer Profiles, domains, profile object types, and integrations can be tagged. */ listTagsForResource(params: CustomerProfiles.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.ListTagsForResourceResponse) => void): Request<CustomerProfiles.Types.ListTagsForResourceResponse, AWSError>; /** * Displays the tags associated with an Amazon Connect Customer Profiles resource. In Connect Customer Profiles, domains, profile object types, and integrations can be tagged. */ listTagsForResource(callback?: (err: AWSError, data: CustomerProfiles.Types.ListTagsForResourceResponse) => void): Request<CustomerProfiles.Types.ListTagsForResourceResponse, AWSError>; /** * Adds an integration between the service and a third-party service, which includes Amazon AppFlow and Amazon Connect. An integration can belong to only one domain. */ putIntegration(params: CustomerProfiles.Types.PutIntegrationRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.PutIntegrationResponse) => void): Request<CustomerProfiles.Types.PutIntegrationResponse, AWSError>; /** * Adds an integration between the service and a third-party service, which includes Amazon AppFlow and Amazon Connect. An integration can belong to only one domain. */ putIntegration(callback?: (err: AWSError, data: CustomerProfiles.Types.PutIntegrationResponse) => void): Request<CustomerProfiles.Types.PutIntegrationResponse, AWSError>; /** * Adds additional objects to customer profiles of a given ObjectType. When adding a specific profile object, like a Contact Trace Record (CTR), an inferred profile can get created if it is not mapped to an existing profile. The resulting profile will only have a phone number populated in the standard ProfileObject. Any additional CTRs with the same phone number will be mapped to the same inferred profile. When a ProfileObject is created and if a ProfileObjectType already exists for the ProfileObject, it will provide data to a standard profile depending on the ProfileObjectType definition. PutProfileObject needs an ObjectType, which can be created using PutProfileObjectType. */ putProfileObject(params: CustomerProfiles.Types.PutProfileObjectRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.PutProfileObjectResponse) => void): Request<CustomerProfiles.Types.PutProfileObjectResponse, AWSError>; /** * Adds additional objects to customer profiles of a given ObjectType. When adding a specific profile object, like a Contact Trace Record (CTR), an inferred profile can get created if it is not mapped to an existing profile. The resulting profile will only have a phone number populated in the standard ProfileObject. Any additional CTRs with the same phone number will be mapped to the same inferred profile. When a ProfileObject is created and if a ProfileObjectType already exists for the ProfileObject, it will provide data to a standard profile depending on the ProfileObjectType definition. PutProfileObject needs an ObjectType, which can be created using PutProfileObjectType. */ putProfileObject(callback?: (err: AWSError, data: CustomerProfiles.Types.PutProfileObjectResponse) => void): Request<CustomerProfiles.Types.PutProfileObjectResponse, AWSError>; /** * Defines a ProfileObjectType. */ putProfileObjectType(params: CustomerProfiles.Types.PutProfileObjectTypeRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.PutProfileObjectTypeResponse) => void): Request<CustomerProfiles.Types.PutProfileObjectTypeResponse, AWSError>; /** * Defines a ProfileObjectType. */ putProfileObjectType(callback?: (err: AWSError, data: CustomerProfiles.Types.PutProfileObjectTypeResponse) => void): Request<CustomerProfiles.Types.PutProfileObjectTypeResponse, AWSError>; /** * Searches for profiles within a specific domain name using name, phone number, email address, account number, or a custom defined index. */ searchProfiles(params: CustomerProfiles.Types.SearchProfilesRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.SearchProfilesResponse) => void): Request<CustomerProfiles.Types.SearchProfilesResponse, AWSError>; /** * Searches for profiles within a specific domain name using name, phone number, email address, account number, or a custom defined index. */ searchProfiles(callback?: (err: AWSError, data: CustomerProfiles.Types.SearchProfilesResponse) => void): Request<CustomerProfiles.Types.SearchProfilesResponse, AWSError>; /** * Assigns one or more tags (key-value pairs) to the specified Amazon Connect Customer Profiles resource. Tags can help you organize and categorize your resources. You can also use them to scope user permissions by granting a user permission to access or change only resources with certain tag values. In Connect Customer Profiles, domains, profile object types, and integrations can be tagged. Tags don't have any semantic meaning to AWS and are interpreted strictly as strings of characters. You can use the TagResource action with a resource that already has tags. If you specify a new tag key, this tag is appended to the list of tags associated with the resource. If you specify a tag key that is already associated with the resource, the new tag value that you specify replaces the previous value for that tag. You can associate as many as 50 tags with a resource. */ tagResource(params: CustomerProfiles.Types.TagResourceRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.TagResourceResponse) => void): Request<CustomerProfiles.Types.TagResourceResponse, AWSError>; /** * Assigns one or more tags (key-value pairs) to the specified Amazon Connect Customer Profiles resource. Tags can help you organize and categorize your resources. You can also use them to scope user permissions by granting a user permission to access or change only resources with certain tag values. In Connect Customer Profiles, domains, profile object types, and integrations can be tagged. Tags don't have any semantic meaning to AWS and are interpreted strictly as strings of characters. You can use the TagResource action with a resource that already has tags. If you specify a new tag key, this tag is appended to the list of tags associated with the resource. If you specify a tag key that is already associated with the resource, the new tag value that you specify replaces the previous value for that tag. You can associate as many as 50 tags with a resource. */ tagResource(callback?: (err: AWSError, data: CustomerProfiles.Types.TagResourceResponse) => void): Request<CustomerProfiles.Types.TagResourceResponse, AWSError>; /** * Removes one or more tags from the specified Amazon Connect Customer Profiles resource. In Connect Customer Profiles, domains, profile object types, and integrations can be tagged. */ untagResource(params: CustomerProfiles.Types.UntagResourceRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.UntagResourceResponse) => void): Request<CustomerProfiles.Types.UntagResourceResponse, AWSError>; /** * Removes one or more tags from the specified Amazon Connect Customer Profiles resource. In Connect Customer Profiles, domains, profile object types, and integrations can be tagged. */ untagResource(callback?: (err: AWSError, data: CustomerProfiles.Types.UntagResourceResponse) => void): Request<CustomerProfiles.Types.UntagResourceResponse, AWSError>; /** * Updates the properties of a domain, including creating or selecting a dead letter queue or an encryption key. Once a domain is created, the name can’t be changed. */ updateDomain(params: CustomerProfiles.Types.UpdateDomainRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.UpdateDomainResponse) => void): Request<CustomerProfiles.Types.UpdateDomainResponse, AWSError>; /** * Updates the properties of a domain, including creating or selecting a dead letter queue or an encryption key. Once a domain is created, the name can’t be changed. */ updateDomain(callback?: (err: AWSError, data: CustomerProfiles.Types.UpdateDomainResponse) => void): Request<CustomerProfiles.Types.UpdateDomainResponse, AWSError>; /** * Updates the properties of a profile. The ProfileId is required for updating a customer profile. When calling the UpdateProfile API, specifying an empty string value means that any existing value will be removed. Not specifying a string value means that any value already there will be kept. */ updateProfile(params: CustomerProfiles.Types.UpdateProfileRequest, callback?: (err: AWSError, data: CustomerProfiles.Types.UpdateProfileResponse) => void): Request<CustomerProfiles.Types.UpdateProfileResponse, AWSError>; /** * Updates the properties of a profile. The ProfileId is required for updating a customer profile. When calling the UpdateProfile API, specifying an empty string value means that any existing value will be removed. Not specifying a string value means that any value already there will be kept. */ updateProfile(callback?: (err: AWSError, data: CustomerProfiles.Types.UpdateProfileResponse) => void): Request<CustomerProfiles.Types.UpdateProfileResponse, AWSError>; } declare namespace CustomerProfiles { export type name = string; export interface AddProfileKeyRequest { /** * The unique identifier of a customer profile. */ ProfileId: uuid; /** * A searchable identifier of a customer profile. */ KeyName: name; /** * A list of key values. */ Values: requestValueList; /** * The unique name of the domain. */ DomainName: name; } export interface AddProfileKeyResponse { /** * A searchable identifier of a customer profile. */ KeyName?: name; /** * A list of key values. */ Values?: requestValueList; } export interface Address { /** * The first line of a customer address. */ Address1?: string1To255; /** * The second line of a customer address. */ Address2?: string1To255; /** * The third line of a customer address. */ Address3?: string1To255; /** * The fourth line of a customer address. */ Address4?: string1To255; /** * The city in which a customer lives. */ City?: string1To255; /** * The county in which a customer lives. */ County?: string1To255; /** * The state in which a customer lives. */ State?: string1To255; /** * The province in which a customer lives. */ Province?: string1To255; /** * The country in which a customer lives. */ Country?: string1To255; /** * The postal code of a customer address. */ PostalCode?: string1To255; } export type Attributes = {[key: string]: string1To255}; export interface CreateDomainRequest { /** * The unique name of the domain. */ DomainName: name; /** * The default number of days until the data within the domain expires. */ DefaultExpirationDays: expirationDaysInteger; /** * The default encryption key, which is an AWS managed key, is used when no specific type of encryption key is specified. It is used to encrypt all data before it is placed in permanent or semi-permanent storage. */ DefaultEncryptionKey?: encryptionKey; /** * The URL of the SQS dead letter queue, which is used for reporting errors associated with ingesting data from third party applications. You must set up a policy on the DeadLetterQueue for the SendMessage operation to enable Amazon Connect Customer Profiles to send messages to the DeadLetterQueue. */ DeadLetterQueueUrl?: sqsQueueUrl; /** * The tags used to organize, track, or control access for this resource. */ Tags?: TagMap; } export interface CreateDomainResponse { /** * The unique name of the domain. */ DomainName: name; /** * The default number of days until the data within the domain expires. */ DefaultExpirationDays: expirationDaysInteger; /** * The default encryption key, which is an AWS managed key, is used when no specific type of encryption key is specified. It is used to encrypt all data before it is placed in permanent or semi-permanent storage. */ DefaultEncryptionKey?: encryptionKey; /** * The URL of the SQS dead letter queue, which is used for reporting errors associated with ingesting data from third party applications. */ DeadLetterQueueUrl?: sqsQueueUrl; /** * The timestamp of when the domain was created. */ CreatedAt: timestamp; /** * The timestamp of when the domain was most recently edited. */ LastUpdatedAt: timestamp; /** * The tags used to organize, track, or control access for this resource. */ Tags?: TagMap; } export interface CreateProfileRequest { /** * The unique name of the domain. */ DomainName: name; /** * A unique account number that you have given to the customer. */ AccountNumber?: string1To255; /** * Any additional information relevant to the customer's profile. */ AdditionalInformation?: string1To1000; /** * The type of profile used to describe the customer. */ PartyType?: PartyType; /** * The name of the customer’s business. */ BusinessName?: string1To255; /** * The customer’s first name. */ FirstName?: string1To255; /** * The customer’s middle name. */ MiddleName?: string1To255; /** * The customer’s last name. */ LastName?: string1To255; /** * The customer’s birth date. */ BirthDate?: string1To255; /** * The gender with which the customer identifies. */ Gender?: Gender; /** * The customer's phone number, which has not been specified as a mobile, home, or business number. */ PhoneNumber?: string1To255; /** * The customer’s mobile phone number. */ MobilePhoneNumber?: string1To255; /** * The customer’s home phone number. */ HomePhoneNumber?: string1To255; /** * The customer’s business phone number. */ BusinessPhoneNumber?: string1To255; /** * The customer's email address, which has not been specified as a personal or business address. */ EmailAddress?: string1To255; /** * The customer’s personal email address. */ PersonalEmailAddress?: string1To255; /** * The customer’s business email address. */ BusinessEmailAddress?: string1To255; /** * A generic address associated with the customer that is not mailing, shipping, or billing. */ Address?: Address; /** * The customer’s shipping address. */ ShippingAddress?: Address; /** * The customer’s mailing address. */ MailingAddress?: Address; /** * The customer’s billing address. */ BillingAddress?: Address; /** * A key value pair of attributes of a customer profile. */ Attributes?: Attributes; } export interface CreateProfileResponse { /** * The unique identifier of a customer profile. */ ProfileId: uuid; } export interface DeleteDomainRequest { /** * The unique name of the domain. */ DomainName: name; } export interface DeleteDomainResponse { /** * A message that indicates the delete request is done. */ Message: message; } export interface DeleteIntegrationRequest { /** * The unique name of the domain. */ DomainName: name; /** * The URI of the S3 bucket or any other type of data source. */ Uri: string1To255; } export interface DeleteIntegrationResponse { /** * A message that indicates the delete request is done. */ Message: message; } export interface DeleteProfileKeyRequest { /** * The unique identifier of a customer profile. */ ProfileId: uuid; /** * A searchable identifier of a customer profile. */ KeyName: name; /** * A list of key values. */ Values: requestValueList; /** * The unique name of the domain. */ DomainName: name; } export interface DeleteProfileKeyResponse { /** * A message that indicates the delete request is done. */ Message?: message; } export interface DeleteProfileObjectRequest { /** * The unique identifier of a customer profile. */ ProfileId: uuid; /** * The unique identifier of the profile object generated by the service. */ ProfileObjectUniqueKey: string1To255; /** * The name of the profile object type. */ ObjectTypeName: typeName; /** * The unique name of the domain. */ DomainName: name; } export interface DeleteProfileObjectResponse { /** * A message that indicates the delete request is done. */ Message?: message; } export interface DeleteProfileObjectTypeRequest { /** * The unique name of the domain. */ DomainName: name; /** * The name of the profile object type. */ ObjectTypeName: typeName; } export interface DeleteProfileObjectTypeResponse { /** * A message that indicates the delete request is done. */ Message: message; } export interface DeleteProfileRequest { /** * The unique identifier of a customer profile. */ ProfileId: uuid; /** * The unique name of the domain. */ DomainName: name; } export interface DeleteProfileResponse { /** * A message that indicates the delete request is done. */ Message?: message; } export type DomainList = ListDomainItem[]; export interface DomainStats { /** * The total number of profiles currently in the domain. */ ProfileCount?: long; /** * The number of profiles that you are currently paying for in the domain. If you have more than 100 objects associated with a single profile, that profile counts as two profiles. If you have more than 200 objects, that profile counts as three, and so on. */ MeteringProfileCount?: long; /** * The total number of objects in domain. */ ObjectCount?: long; /** * The total size, in bytes, of all objects in the domain. */ TotalSize?: long; } export type FieldContentType = "STRING"|"NUMBER"|"PHONE_NUMBER"|"EMAIL_ADDRESS"|"NAME"|string; export type FieldMap = {[key: string]: ObjectTypeField}; export type FieldNameList = name[]; export type Gender = "MALE"|"FEMALE"|"UNSPECIFIED"|string; export interface GetDomainRequest { /** * A unique name for the domain. */ DomainName: name; } export interface GetDomainResponse { /** * The unique name of the domain. */ DomainName: name; /** * The default number of days until the data within the domain expires. */ DefaultExpirationDays?: expirationDaysInteger; /** * The default encryption key, which is an AWS managed key, is used when no specific type of encryption key is specified. It is used to encrypt all data before it is placed in permanent or semi-permanent storage. */ DefaultEncryptionKey?: encryptionKey; /** * The URL of the SQS dead letter queue, which is used for reporting errors associated with ingesting data from third party applications. */ DeadLetterQueueUrl?: sqsQueueUrl; /** * Usage-specific statistics about the domain. */ Stats?: DomainStats; /** * The timestamp of when the domain was created. */ CreatedAt: timestamp; /** * The timestamp of when the domain was most recently edited. */ LastUpdatedAt: timestamp; /** * The tags used to organize, track, or control access for this resource. */ Tags?: TagMap; } export interface GetIntegrationRequest { /** * The unique name of the domain. */ DomainName: name; /** * The URI of the S3 bucket or any other type of data source. */ Uri: string1To255; } export interface GetIntegrationResponse { /** * The unique name of the domain. */ DomainName: name; /** * The URI of the S3 bucket or any other type of data source. */ Uri: string1To255; /** * The name of the profile object type. */ ObjectTypeName: typeName; /** * The timestamp of when the domain was created. */ CreatedAt: timestamp; /** * The timestamp of when the domain was most recently edited. */ LastUpdatedAt: timestamp; /** * The tags used to organize, track, or control access for this resource. */ Tags?: TagMap; } export interface GetProfileObjectTypeRequest { /** * The unique name of the domain. */ DomainName: name; /** * The name of the profile object type. */ ObjectTypeName: typeName; } export interface GetProfileObjectTypeResponse { /** * The name of the profile object type. */ ObjectTypeName: typeName; /** * The description of the profile object type. */ Description: text; /** * A unique identifier for the object template. */ TemplateId?: name; /** * The number of days until the data in the object expires. */ ExpirationDays?: expirationDaysInteger; /** * The customer-provided key to encrypt the profile object that will be created in this profile object type. */ EncryptionKey?: encryptionKey; /** * Indicates whether a profile should be created when data is received if one doesn’t exist for an object of this type. The default is FALSE. If the AllowProfileCreation flag is set to FALSE, then the service tries to fetch a standard profile and associate this object with the profile. If it is set to TRUE, and if no match is found, then the service creates a new standard profile. */ AllowProfileCreation?: boolean; /** * A map of the name and ObjectType field. */ Fields?: FieldMap; /** * A list of unique keys that can be used to map data to the profile. */ Keys?: KeyMap; /** * The timestamp of when the domain was created. */ CreatedAt?: timestamp; /** * The timestamp of when the domain was most recently edited. */ LastUpdatedAt?: timestamp; /** * The tags used to organize, track, or control access for this resource. */ Tags?: TagMap; } export interface GetProfileObjectTypeTemplateRequest { /** * A unique identifier for the object template. */ TemplateId: name; } export interface GetProfileObjectTypeTemplateResponse { /** * A unique identifier for the object template. */ TemplateId?: name; /** * The name of the source of the object template. */ SourceName?: name; /** * The source of the object template. */ SourceObject?: name; /** * Indicates whether a profile should be created when data is received if one doesn’t exist for an object of this type. The default is FALSE. If the AllowProfileCreation flag is set to FALSE, then the service tries to fetch a standard profile and associate this object with the profile. If it is set to TRUE, and if no match is found, then the service creates a new standard profile. */ AllowProfileCreation?: boolean; /** * A map of the name and ObjectType field. */ Fields?: FieldMap; /** * A list of unique keys that can be used to map data to the profile. */ Keys?: KeyMap; } export type IntegrationList = ListIntegrationItem[]; export type KeyMap = {[key: string]: ObjectTypeKeyList}; export interface ListAccountIntegrationsRequest { /** * The URI of the S3 bucket or any other type of data source. */ Uri: string1To255; /** * The pagination token from the previous ListAccountIntegrations API call. */ NextToken?: token; /** * The maximum number of objects returned per page. */ MaxResults?: maxSize100; } export interface ListAccountIntegrationsResponse { /** * The list of ListAccountIntegration instances. */ Items?: IntegrationList; /** * The pagination token from the previous ListAccountIntegrations API call. */ NextToken?: token; } export interface ListDomainItem { /** * The unique name of the domain. */ DomainName: name; /** * The timestamp of when the domain was created. */ CreatedAt: timestamp; /** * The timestamp of when the domain was most recently edited. */ LastUpdatedAt: timestamp; /** * The tags used to organize, track, or control access for this resource. */ Tags?: TagMap; } export interface ListDomainsRequest { /** * The pagination token from the previous ListDomain API call. */ NextToken?: token; /** * The maximum number of objects returned per page. */ MaxResults?: maxSize100; } export interface ListDomainsResponse { /** * The list of ListDomains instances. */ Items?: DomainList; /** * The pagination token from the previous ListDomains API call. */ NextToken?: token; } export interface ListIntegrationItem { /** * The unique name of the domain. */ DomainName: name; /** * The URI of the S3 bucket or any other type of data source. */ Uri: string1To255; /** * The name of the profile object type. */ ObjectTypeName: typeName; /** * The timestamp of when the domain was created. */ CreatedAt: timestamp; /** * The timestamp of when the domain was most recently edited. */ LastUpdatedAt: timestamp; /** * The tags used to organize, track, or control access for this resource. */ Tags?: TagMap; } export interface ListIntegrationsRequest { /** * The unique name of the domain. */ DomainName: name; /** * The pagination token from the previous ListIntegrations API call. */ NextToken?: token; /** * The maximum number of objects returned per page. */ MaxResults?: maxSize100; } export interface ListIntegrationsResponse { /** * The list of ListIntegrations instances. */ Items?: IntegrationList; /** * The pagination token from the previous ListIntegrations API call. */ NextToken?: token; } export interface ListProfileObjectTypeItem { /** * The name of the profile object type. */ ObjectTypeName: typeName; /** * Description of the profile object type. */ Description: text; /** * The timestamp of when the domain was created. */ CreatedAt?: timestamp; /** * The timestamp of when the domain was most recently edited. */ LastUpdatedAt?: timestamp; /** * The tags used to organize, track, or control access for this resource. */ Tags?: TagMap; } export interface ListProfileObjectTypeTemplateItem { /** * A unique identifier for the object template. */ TemplateId?: name; /** * The name of the source of the object template. */ SourceName?: name; /** * The source of the object template. */ SourceObject?: name; } export interface ListProfileObjectTypeTemplatesRequest { /** * The pagination token from the previous ListObjectTypeTemplates API call. */ NextToken?: token; /** * The maximum number of objects returned per page. */ MaxResults?: maxSize100; } export interface ListProfileObjectTypeTemplatesResponse { /** * The list of ListProfileObjectType template instances. */ Items?: ProfileObjectTypeTemplateList; /** * The pagination token from the previous ListObjectTypeTemplates API call. */ NextToken?: token; } export interface ListProfileObjectTypesRequest { /** * The unique name of the domain. */ DomainName: name; /** * Identifies the next page of results to return. */ NextToken?: token; /** * The maximum number of objects returned per page. */ MaxResults?: maxSize100; } export interface ListProfileObjectTypesResponse { /** * The list of ListProfileObjectTypes instances. */ Items?: ProfileObjectTypeList; /** * Identifies the next page of results to return. */ NextToken?: token; } export interface ListProfileObjectsItem { /** * Specifies the kind of object being added to a profile, such as "Salesforce-Account." */ ObjectTypeName?: typeName; /** * The unique identifier of the ProfileObject generated by the service. */ ProfileObjectUniqueKey?: string1To255; /** * A JSON representation of a ProfileObject that belongs to a profile. */ Object?: stringifiedJson; } export interface ListProfileObjectsRequest { /** * The pagination token from the previous call to ListProfileObjects. */ NextToken?: token; /** * The maximum number of objects returned per page. */ MaxResults?: maxSize100; /** * The unique name of the domain. */ DomainName: name; /** * The name of the profile object type. */ ObjectTypeName: typeName; /** * The unique identifier of a customer profile. */ ProfileId: uuid; } export interface ListProfileObjectsResponse { /** * The list of ListProfileObject instances. */ Items?: ProfileObjectList; /** * The pagination token from the previous call to ListProfileObjects. */ NextToken?: token; } export interface ListTagsForResourceRequest { /** * The ARN of the resource for which you want to view tags. */ resourceArn: TagArn; } export interface ListTagsForResourceResponse { /** * The tags used to organize, track, or control access for this resource. */ tags?: TagMap; } export interface ObjectTypeField { /** * A field of a ProfileObject. For example: _source.FirstName, where “_source” is a ProfileObjectType of a Zendesk user and “FirstName” is a field in that ObjectType. */ Source?: text; /** * The location of the data in the standard ProfileObject model. For example: _profile.Address.PostalCode. */ Target?: text; /** * The content type of the field. Used for determining equality when searching. */ ContentType?: FieldContentType; } export interface ObjectTypeKey { /** * The types of keys that a ProfileObject can have. Each ProfileObject can have only 1 UNIQUE key but multiple PROFILE keys. PROFILE means that this key can be used to tie an object to a PROFILE. UNIQUE means that it can be used to uniquely identify an object. If a key a is marked as SECONDARY, it will be used to search for profiles after all other PROFILE keys have been searched. A LOOKUP_ONLY key is only used to match a profile but is not persisted to be used for searching of the profile. A NEW_ONLY key is only used if the profile does not already exist before the object is ingested, otherwise it is only used for matching objects to profiles. */ StandardIdentifiers?: StandardIdentifierList; /** * The reference for the key name of the fields map. */ FieldNames?: FieldNameList; } export type ObjectTypeKeyList = ObjectTypeKey[]; export type PartyType = "INDIVIDUAL"|"BUSINESS"|"OTHER"|string; export interface Profile { /** * The unique identifier of a customer profile. */ ProfileId?: uuid; /** * A unique account number that you have given to the customer. */ AccountNumber?: string1To255; /** * Any additional information relevant to the customer's profile. */ AdditionalInformation?: string1To1000; /** * The type of profile used to describe the customer. */ PartyType?: PartyType; /** * The name of the customer’s business. */ BusinessName?: string1To255; /** * The customer’s first name. */ FirstName?: string1To255; /** * The customer’s middle name. */ MiddleName?: string1To255; /** * The customer’s last name. */ LastName?: string1To255; /** * The customer’s birth date. */ BirthDate?: string1To255; /** * The gender with which the customer identifies. */ Gender?: Gender; /** * The customer's phone number, which has not been specified as a mobile, home, or business number. */ PhoneNumber?: string1To255; /** * The customer’s mobile phone number. */ MobilePhoneNumber?: string1To255; /** * The customer’s home phone number. */ HomePhoneNumber?: string1To255; /** * The customer’s home phone number. */ BusinessPhoneNumber?: string1To255; /** * The customer's email address, which has not been specified as a personal or business address. */ EmailAddress?: string1To255; /** * The customer’s personal email address. */ PersonalEmailAddress?: string1To255; /** * The customer’s business email address. */ BusinessEmailAddress?: string1To255; /** * A generic address associated with the customer that is not mailing, shipping, or billing. */ Address?: Address; /** * The customer’s shipping address. */ ShippingAddress?: Address; /** * The customer’s mailing address. */ MailingAddress?: Address; /** * The customer’s billing address. */ BillingAddress?: Address; /** * A key value pair of attributes of a customer profile. */ Attributes?: Attributes; } export type ProfileList = Profile[]; export type ProfileObjectList = ListProfileObjectsItem[]; export type ProfileObjectTypeList = ListProfileObjectTypeItem[]; export type ProfileObjectTypeTemplateList = ListProfileObjectTypeTemplateItem[]; export interface PutIntegrationRequest { /** * The unique name of the domain. */ DomainName: name; /** * The URI of the S3 bucket or any other type of data source. */ Uri: string1To255; /** * The name of the profile object type. */ ObjectTypeName: typeName; /** * The tags used to organize, track, or control access for this resource. */ Tags?: TagMap; } export interface PutIntegrationResponse { /** * The unique name of the domain. */ DomainName: name; /** * The URI of the S3 bucket or any other type of data source. */ Uri: string1To255; /** * The name of the profile object type. */ ObjectTypeName: typeName; /** * The timestamp of when the domain was created. */ CreatedAt: timestamp; /** * The timestamp of when the domain was most recently edited. */ LastUpdatedAt: timestamp; /** * The tags used to organize, track, or control access for this resource. */ Tags?: TagMap; } export interface PutProfileObjectRequest { /** * The name of the profile object type. */ ObjectTypeName: typeName; /** * A string that is serialized from a JSON object. */ Object: stringifiedJson; /** * The unique name of the domain. */ DomainName: name; } export interface PutProfileObjectResponse { /** * The unique identifier of the profile object generated by the service. */ ProfileObjectUniqueKey?: string1To255; } export interface PutProfileObjectTypeRequest { /** * The unique name of the domain. */ DomainName: name; /** * The name of the profile object type. */ ObjectTypeName: typeName; /** * Description of the profile object type. */ Description: text; /** * A unique identifier for the object template. */ TemplateId?: name; /** * The number of days until the data in the object expires. */ ExpirationDays?: expirationDaysInteger; /** * The customer-provided key to encrypt the profile object that will be created in this profile object type. */ EncryptionKey?: encryptionKey; /** * Indicates whether a profile should be created when data is received if one doesn’t exist for an object of this type. The default is FALSE. If the AllowProfileCreation flag is set to FALSE, then the service tries to fetch a standard profile and associate this object with the profile. If it is set to TRUE, and if no match is found, then the service creates a new standard profile. */ AllowProfileCreation?: boolean; /** * A map of the name and ObjectType field. */ Fields?: FieldMap; /** * A list of unique keys that can be used to map data to the profile. */ Keys?: KeyMap; /** * The tags used to organize, track, or control access for this resource. */ Tags?: TagMap; } export interface PutProfileObjectTypeResponse { /** * The name of the profile object type. */ ObjectTypeName: typeName; /** * Description of the profile object type. */ Description: text; /** * A unique identifier for the object template. */ TemplateId?: name; /** * The number of days until the data in the object expires. */ ExpirationDays?: expirationDaysInteger; /** * The customer-provided key to encrypt the profile object that will be created in this profile object type. */ EncryptionKey?: encryptionKey; /** * Indicates whether a profile should be created when data is received if one doesn’t exist for an object of this type. The default is FALSE. If the AllowProfileCreation flag is set to FALSE, then the service tries to fetch a standard profile and associate this object with the profile. If it is set to TRUE, and if no match is found, then the service creates a new standard profile. */ AllowProfileCreation?: boolean; /** * A map of the name and ObjectType field. */ Fields?: FieldMap; /** * A list of unique keys that can be used to map data to the profile. */ Keys?: KeyMap; /** * The timestamp of when the domain was created. */ CreatedAt?: timestamp; /** * The timestamp of when the domain was most recently edited. */ LastUpdatedAt?: timestamp; /** * The tags used to organize, track, or control access for this resource. */ Tags?: TagMap; } export interface SearchProfilesRequest { /** * The pagination token from the previous SearchProfiles API call. */ NextToken?: token; /** * The maximum number of objects returned per page. */ MaxResults?: maxSize100; /** * The unique name of the domain. */ DomainName: name; /** * A searchable identifier of a customer profile. The predefined keys you can use to search include: _account, _profileId, _fullName, _phone, _email, _ctrContactId, _marketoLeadId, _salesforceAccountId, _salesforceContactId, _zendeskUserId, _zendeskExternalId, _serviceNowSystemId. */ KeyName: name; /** * A list of key values. */ Values: requestValueList; } export interface SearchProfilesResponse { /** * The list of SearchProfiles instances. */ Items?: ProfileList; /** * The pagination token from the previous SearchProfiles API call. */ NextToken?: token; } export type StandardIdentifier = "PROFILE"|"UNIQUE"|"SECONDARY"|"LOOKUP_ONLY"|"NEW_ONLY"|string; export type StandardIdentifierList = StandardIdentifier[]; export type TagArn = string; export type TagKey = string; export type TagKeyList = TagKey[]; export type TagMap = {[key: string]: TagValue}; export interface TagResourceRequest { /** * The ARN of the resource that you're adding tags to. */ resourceArn: TagArn; /** * The tags used to organize, track, or control access for this resource. */ tags: TagMap; } export interface TagResourceResponse { } export type TagValue = string; export interface UntagResourceRequest { /** * The ARN of the resource from which you are removing tags. */ resourceArn: TagArn; /** * The list of tag keys to remove from the resource. */ tagKeys: TagKeyList; } export interface UntagResourceResponse { } export interface UpdateAddress { /** * The first line of a customer address. */ Address1?: string0To255; /** * The second line of a customer address. */ Address2?: string0To255; /** * The third line of a customer address. */ Address3?: string0To255; /** * The fourth line of a customer address. */ Address4?: string0To255; /** * The city in which a customer lives. */ City?: string0To255; /** * The county in which a customer lives. */ County?: string0To255; /** * The state in which a customer lives. */ State?: string0To255; /** * The province in which a customer lives. */ Province?: string0To255; /** * The country in which a customer lives. */ Country?: string0To255; /** * The postal code of a customer address. */ PostalCode?: string0To255; } export type UpdateAttributes = {[key: string]: string0To255}; export interface UpdateDomainRequest { /** * The unique name for the domain. */ DomainName: name; /** * The default number of days until the data within the domain expires. */ DefaultExpirationDays?: expirationDaysInteger; /** * The default encryption key, which is an AWS managed key, is used when no specific type of encryption key is specified. It is used to encrypt all data before it is placed in permanent or semi-permanent storage. If specified as an empty string, it will clear any existing value. */ DefaultEncryptionKey?: encryptionKey; /** * The URL of the SQS dead letter queue, which is used for reporting errors associated with ingesting data from third party applications. If specified as an empty string, it will clear any existing value. You must set up a policy on the DeadLetterQueue for the SendMessage operation to enable Amazon Connect Customer Profiles to send messages to the DeadLetterQueue. */ DeadLetterQueueUrl?: sqsQueueUrl; /** * The tags used to organize, track, or control access for this resource. */ Tags?: TagMap; } export interface UpdateDomainResponse { /** * The unique name for the domain. */ DomainName: name; /** * The default number of days until the data within the domain expires. */ DefaultExpirationDays?: expirationDaysInteger; /** * The default encryption key, which is an AWS managed key, is used when no specific type of encryption key is specified. It is used to encrypt all data before it is placed in permanent or semi-permanent storage. */ DefaultEncryptionKey?: encryptionKey; /** * The URL of the SQS dead letter queue, which is used for reporting errors associated with ingesting data from third party applications. */ DeadLetterQueueUrl?: sqsQueueUrl; /** * The timestamp of when the domain was created. */ CreatedAt: timestamp; /** * The timestamp of when the domain was most recently edited. */ LastUpdatedAt: timestamp; /** * The tags used to organize, track, or control access for this resource. */ Tags?: TagMap; } export interface UpdateProfileRequest { /** * The unique name of the domain. */ DomainName: name; /** * The unique identifier of a customer profile. */ ProfileId: uuid; /** * Any additional information relevant to the customer's profile. */ AdditionalInformation?: string0To1000; /** * A unique account number that you have given to the customer. */ AccountNumber?: string0To255; /** * The type of profile used to describe the customer. */ PartyType?: PartyType; /** * The name of the customer’s business. */ BusinessName?: string0To255; /** * The customer’s first name. */ FirstName?: string0To255; /** * The customer’s middle name. */ MiddleName?: string0To255; /** * The customer’s last name. */ LastName?: string0To255; /** * The customer’s birth date. */ BirthDate?: string0To255; /** * The gender with which the customer identifies. */ Gender?: Gender; /** * The customer's phone number, which has not been specified as a mobile, home, or business number. */ PhoneNumber?: string0To255; /** * The customer’s mobile phone number. */ MobilePhoneNumber?: string0To255; /** * The customer’s home phone number. */ HomePhoneNumber?: string0To255; /** * The customer’s business phone number. */ BusinessPhoneNumber?: string0To255; /** * The customer's email address, which has not been specified as a personal or business address. */ EmailAddress?: string0To255; /** * The customer’s personal email address. */ PersonalEmailAddress?: string0To255; /** * The customer’s business email address. */ BusinessEmailAddress?: string0To255; /** * A generic address associated with the customer that is not mailing, shipping, or billing. */ Address?: UpdateAddress; /** * The customer’s shipping address. */ ShippingAddress?: UpdateAddress; /** * The customer’s mailing address. */ MailingAddress?: UpdateAddress; /** * The customer’s billing address. */ BillingAddress?: UpdateAddress; /** * A key value pair of attributes of a customer profile. */ Attributes?: UpdateAttributes; } export interface UpdateProfileResponse { /** * The unique identifier of a customer profile. */ ProfileId: uuid; } export type encryptionKey = string; export type expirationDaysInteger = number; export type long = number; export type maxSize100 = number; export type message = string; export type requestValueList = string1To255[]; export type sqsQueueUrl = string; export type string0To1000 = string; export type string0To255 = string; export type string1To1000 = string; export type string1To255 = string; export type stringifiedJson = string; export type text = string; export type timestamp = Date; export type token = string; export type typeName = string; export type uuid = string; /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2020-08-15"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the CustomerProfiles client. */ export import Types = CustomerProfiles; } export = CustomerProfiles;
the_stack
import {ModelBase} from "../config/model.base"; import {DataEntityType} from "../api/entity/data-entity.base"; import {Paris} from "../paris"; import {combineLatest, Observable, of} from "rxjs"; import {map} from "rxjs/operators"; import {valueObjectsService} from "../config/services/value-objects.service"; import {EntityConfigBase, ModelConfig} from "../config/model-config"; import {ModelEntity} from "../config/entity.config"; import {FIELD_DATA_SELF} from "../config/entity-field.config"; import {cloneDeep, get} from "lodash-es"; import {DataTransformersService} from "./data-transformers.service"; import {Field} from "../api/entity/entity-field"; import {EntityModelBase} from "../config/entity-model.base"; import {DataOptions, defaultDataOptions} from "../data_access/data.options"; import {DataQuery} from "../data_access/data-query"; import {ReadonlyRepository} from "../api/repository/readonly-repository"; import {DataSet} from "../data_access/dataset"; import {entitiesService} from "../config/services/entities.service"; const DEFAULT_ALL_ITEMS_PROPERTY = 'items'; export class Modeler { constructor(private paris:Paris){} /** * Models an Entity or ValueObject, according to raw data and configuration. * In Domain-Driven Design terms, this method creates an Aggregate Root. It does the actual heavy lifting required for modeling * an Entity or ValueObject - parses the fields, models sub-models, etc. * * @template TEntity The entity to model * @template TRawData The raw data * @template TConcreteEntity An optional entity derived from `TEntity` that will be used if `TEntity` uses `modelWith` * @param {TRawData} rawData * @param {ModelConfig<TEntity, TRawData>} entity * @param {DataOptions} [options=defaultDataOptions] * @param {DataQuery} [query] * @returns {Observable<TEntity> | Observable<TConcreteEntity>} */ modelEntity<TEntity extends ModelBase, TRawData extends any = any, TConcreteEntity extends TEntity = TEntity>(rawData: TRawData, entity: ModelConfig<TEntity, TRawData>, options: DataOptions = defaultDataOptions, query?: DataQuery) : Observable<TEntity> { let entityIdProperty: keyof TRawData = entity.idProperty || this.paris.config.entityIdProperty, modelData: Partial<TEntity> = {}, subModels: Array<Observable<ModelPropertyValue<TEntity>>> = []; if (entity instanceof ModelEntity) modelData.id = rawData[entityIdProperty]; let getModelDataError:Error = new Error(`Failed to create ${entity.singularName}.`); if (typeof entity.modelWith === 'function') { const modelWithEntityOrString = entity.modelWith(rawData, query); if (modelWithEntityOrString) { const modelWithEntity = typeof modelWithEntityOrString === "string" ? (entitiesService.getEntityByName(modelWithEntityOrString) || valueObjectsService.getEntityByName(modelWithEntityOrString)) : (modelWithEntityOrString.entityConfig || modelWithEntityOrString.valueObjectConfig); if (!modelWithEntity){ getModelDataError.message = `${getModelDataError.message} modelWith: Couldn't find '${modelWithEntity}'. Did you add a 'forwardRefName' to the corresponding entity config?`; throw getModelDataError; } return this.modelEntity<TConcreteEntity, TRawData>( rawData, modelWithEntity, options, query ); } } entity.fields.forEach((entityField: Field) => { if (!this.validateFieldData(entityField, rawData)){ modelData[<keyof TEntity>entityField.id] = null; return; } let entityFieldRawData: any = Modeler.getFieldRawData<TRawData>(entityField, rawData); if (entityField.parse) { try { entityFieldRawData = entityField.parse(entityFieldRawData, rawData, query); } catch(e){ getModelDataError.message = getModelDataError.message + ` Error parsing field ${entityField.id}: ` + e.message; throw getModelDataError; } } try { const fieldData = this.getFieldData(entityField, entityFieldRawData, options); if (fieldData instanceof Observable) { subModels.push(fieldData.pipe( map((fieldData: ModelBase | Array<ModelBase>) => { let subModelIndex: ModelPropertyValue<TEntity> = <ModelPropertyValue<TEntity>>{}; subModelIndex[<keyof TEntity>entityField.id] = fieldData; return subModelIndex; } ))); } else modelData[<keyof TEntity>entityField.id] = fieldData; } catch(e){ getModelDataError.message = getModelDataError.message + ' ' + e.message; throw getModelDataError; } }); let model$:Observable<TEntity>; if (subModels.length) { model$ = combineLatest(subModels).pipe( map((propertyEntityValues: Array<ModelPropertyValue<TEntity>>) => { propertyEntityValues.forEach((propertyEntityValue: ModelPropertyValue<TEntity>) => Object.assign(modelData, propertyEntityValue)); let model: TEntity; try { model = new entity.entityConstructor(modelData, rawData); } catch (e) { getModelDataError.message = getModelDataError.message + " Error: " + e.message; throw getModelDataError; } this.setModelLinks(model); return model; }) ); } else { let model: TEntity; try { model = new entity.entityConstructor(modelData, rawData); } catch (e) { getModelDataError.message = getModelDataError.message + " Error: " + e.message; throw getModelDataError; } model$ = of(model); } return entity.readonly ? model$.pipe(map(model => Object.freeze(model))) : model$; } private validateFieldData(entityField:Field, rawData:any):boolean{ let isValid:boolean = true; if (entityField.require) { if (entityField.require instanceof Function && !entityField.require(rawData, this.paris.config)) isValid = false; else if (typeof(entityField.require) === "string") { let rawDataPropertyValue: any = rawData[entityField.require]; if (rawDataPropertyValue === undefined || rawDataPropertyValue === null) isValid = false; } } return isValid; } /** * For all the sub models in a model that are not readonly, add a $parent property, which points to the model * @param {TEntity} model */ private setModelLinks<TEntity extends ModelBase>(model:TEntity):void{ const modelDataType = <DataEntityType<TEntity>>model.constructor; const { fieldsArray } = modelDataType.entityConfig || modelDataType.valueObjectConfig; fieldsArray.forEach((field:Field) => { const modelValue = model[<keyof TEntity>field.id]; if (modelValue && modelValue instanceof Object){ if (modelValue instanceof ModelBase && !Object.isFrozen(modelValue)) (<ModelBase>modelValue).$parent = model; else if (modelValue instanceof Array && modelValue.length && modelValue[0] instanceof ModelBase){ modelValue.forEach((modelValueItem: ModelBase) => { if (!Object.isFrozen(modelValueItem)) modelValueItem.$parent = model; }); } } }); } /** * Given an EntityField configuration and the raw data provided to the entity's modeler, returns the raw data to use for that field. */ static getFieldRawData<TRawData extends any = any>(entityField: Field, rawData:TRawData):any{ let fieldRawData: any; if (entityField.data) { if (entityField.data instanceof Array) { for (let i = 0, path:string; i < entityField.data.length && fieldRawData === undefined; i++) { path = entityField.data[i]; const value = path === FIELD_DATA_SELF ? rawData : get(rawData, path); if (value !== undefined && value !== null) fieldRawData = value; } } else fieldRawData = entityField.data === FIELD_DATA_SELF ? rawData : get(rawData, entityField.data); } else fieldRawData = rawData[entityField.id]; return fieldRawData; } /** * Gets the data to be assigned in a model to the specified field. * If no data is available in the raw data, a default value is assigned, if specified. * If the field's type is of another model, it'll be modeled as well. Otherwise, the data is parsed according to the DataTransformersService parsers. */ private getFieldData<TData = any>(entityField:Field, entityFieldRawData:any, options: DataOptions = defaultDataOptions):TData | Observable<TData | Array<TData>> { if (entityFieldRawData === undefined || entityFieldRawData === null) { let fieldRepository:ReadonlyRepository<EntityModelBase> = this.paris.getRepository(<DataEntityType>entityField.type); let fieldValueObjectType:EntityConfigBase = !fieldRepository && valueObjectsService.getEntityByType(<DataEntityType>entityField.type); let defaultValue:any = fieldRepository && fieldRepository.modelConfig.getDefaultValue() || fieldValueObjectType && fieldValueObjectType.getDefaultValue() || (entityField.isArray ? [] : entityField.defaultValue !== undefined && entityField.defaultValue !== null ? cloneDeep(entityField.defaultValue) : null); if ((defaultValue === undefined || defaultValue === null) && entityField.required) throw new Error(` Field ${entityField.id} is required but it's ${entityFieldRawData}.`); entityFieldRawData = defaultValue; } if (entityFieldRawData !== undefined && entityFieldRawData !== null && !(entityFieldRawData instanceof ModelBase)) { const fieldData$ = this.getSubModel<TData>(entityField, entityFieldRawData, options); if (fieldData$) return fieldData$; else { return entityField.isArray ? entityFieldRawData ? entityFieldRawData.map((elementValue: any) => DataTransformersService.parse(entityField.type, elementValue)) : [] : DataTransformersService.parse(entityField.type, entityFieldRawData); } } else return entityFieldRawData; } private getSubModel<TData extends ModelBase = ModelBase>(entityField:Field, value:any, options: DataOptions = defaultDataOptions):Observable<TData | Array<TData>>{ let repository:ReadonlyRepository<EntityModelBase> = this.paris.getRepository(<DataEntityType>entityField.type); let valueObjectType:EntityConfigBase = !repository && valueObjectsService.getEntityByType(<DataEntityType>entityField.type); if (!repository && !valueObjectType) return null; let data$:Observable<TData | Array<TData>>; const getItem = repository ? Modeler.getEntityItem.bind(null, repository) : this.getValueObjectItem.bind(null, valueObjectType); if (entityField.isArray) { if (value.length) { let propertyMembers$: Array<Observable<TData>> = value.map((memberData: any) => getItem(memberData, options)); data$ = combineLatest(propertyMembers$); } else data$ = of([]); } else data$ = getItem(value, options); return data$; } private static getEntityItem<U extends EntityModelBase>(repository: ReadonlyRepository<U>, data: any, options: DataOptions = defaultDataOptions): Observable<U> { return Object(data) === data ? repository.createItem(data, options) : repository.getItemById(data, options); } private getValueObjectItem<U extends ModelBase>(valueObjectType: EntityConfigBase, data: any, options: DataOptions = defaultDataOptions): Observable<U> { // If the value object is one of a list of values, just set it to the model if (valueObjectType.values) return of(valueObjectType.getValueById(data) || valueObjectType.getDefaultValue() || null); return this.modelEntity(data, valueObjectType, options); } rawDataToDataSet<TEntity extends ModelBase, TRawData = any, TDataSet extends any = any>( rawDataSet:TDataSet, entityConstructor:DataEntityType<TEntity>, allItemsProperty:string, dataOptions:DataOptions = defaultDataOptions, query?:DataQuery):Observable<DataSet<TEntity>>{ let dataSet:DataSet<TRawData> = Modeler.parseDataSet<TRawData, TDataSet>(rawDataSet, allItemsProperty, entityConstructor.entityConfig && entityConstructor.entityConfig.parseDataSet); if (!dataSet.items || !dataSet.items.length) return of({ count: 0, items: [] }); return this.modelArray<TEntity, TRawData>(dataSet.items, entityConstructor, dataOptions, query).pipe( map((items:Array<TEntity>) => { return Object.freeze(Object.assign(dataSet, { items: items, })); }) ); } static parseDataSet<TRawData = any, TDataSet extends any = any>(rawDataSet:TDataSet, allItemsProperty:string = DEFAULT_ALL_ITEMS_PROPERTY, parseDataSet?:(rawDataSet:TDataSet) => DataSet<TRawData>):DataSet<TRawData>{ return rawDataSet instanceof Array ? { count: 0, items: rawDataSet } : parseDataSet ? parseDataSet(rawDataSet) || { count: 0, items: [] } : { count: rawDataSet.count, items: rawDataSet[allItemsProperty], next: rawDataSet.next }; } modelArray<TEntity extends ModelBase, TRawData = any>( rawData:Array<TRawData>, entityConstructor:DataEntityType<TEntity>, dataOptions:DataOptions = defaultDataOptions, query?:DataQuery):Observable<Array<TEntity>>{ if (!rawData.length) return of([]); else { const itemCreators: Array<Observable<TEntity>> = rawData.map((itemData: TRawData) => this.modelItem<TEntity, TRawData>(entityConstructor, itemData, dataOptions, query)); return combineLatest.apply(this, itemCreators); } } private modelItem<TEntity extends ModelBase, TRawData = any>(entityConstructor:DataEntityType<TEntity>, rawData:TRawData, dataOptions: DataOptions = defaultDataOptions, query?:DataQuery):Observable<TEntity>{ return this.modelEntity(rawData, entityConstructor.entityConfig || entityConstructor.valueObjectConfig, dataOptions, query); } /** * Serializes a model (entity/value object) into raw data, so it can be sent back to backend. * @param model The model to serialize * @param entity The configuration of the model * @param serializationData Any data that should be passed to serialization methods */ serializeModel<TEntity extends ModelBase, TRawData = object>(model:Partial<TEntity>, entity:ModelConfig<TEntity, TRawData>, serializationData?:any):TRawData { ReadonlyRepository.validateItem(model, entity); let modelData: TRawData = <TRawData>{}; entity.fields.forEach((entityField:Field) => { if (entityField.serialize !== false) { let itemFieldValue: any = (<any>model)[entityField.id], fieldRepository = this.paris.getRepository(<DataEntityType>entityField.type), fieldValueObjectType: EntityConfigBase = !fieldRepository && valueObjectsService.getEntityByType(<DataEntityType>entityField.type), isNilValue = itemFieldValue === undefined || itemFieldValue === null; let modelValue: any; if (entityField.serialize) modelValue = entityField.serialize(itemFieldValue, serializationData); else if (entityField.isArray) { if (itemFieldValue) { if (fieldRepository || fieldValueObjectType) modelValue = itemFieldValue.map((element: any) => this.serializeModel(element, fieldRepository ? fieldRepository.modelConfig : fieldValueObjectType, serializationData)); else modelValue = itemFieldValue.map((item: any) => DataTransformersService.serialize(entityField.arrayOf, item)); } else modelValue = null; } else if (fieldRepository && fieldRepository.entity) modelValue = isNilValue ? fieldRepository.modelConfig.getDefaultValue() || null : itemFieldValue.id; else if (fieldValueObjectType) modelValue = isNilValue ? fieldValueObjectType.getDefaultValue() || null : this.serializeModel(itemFieldValue, fieldValueObjectType, serializationData); else modelValue = DataTransformersService.serialize(entityField.type, itemFieldValue); let modelProperty: keyof TRawData = <keyof TRawData>(entityField.data ? entityField.data instanceof Array ? entityField.data[0] : entityField.data : entityField.id); modelData[modelProperty] = modelValue; } }); if (entity.serializeItem) modelData = entity.serializeItem(model, modelData, entity, this.paris.config, serializationData); return modelData; } } type ModelPropertyValue<TEntity> = { [P in keyof TEntity]: ModelBase | Array<ModelBase> };
the_stack
import path from 'path'; import React, { ChangeEvent, useEffect, useRef, useState } from 'react'; import uniqueId from 'lodash.uniqueid'; // import core base styles import 'hds-core'; import composeAriaDescribedBy from '../../utils/composeAriaDescribedBy'; import classNames from '../../utils/classNames'; import { Button } from '../button'; import { IconPlus, IconPhoto, IconCross, IconDocument, IconUpload } from '../../icons'; import { InputWrapper } from '../../internal/input-wrapper/InputWrapper'; import styles from './FileInput.module.scss'; type Language = 'en' | 'fi' | 'sv'; type FileInputProps = { /** * A comma-separated list of unique file type specifiers describing file types to allow. If present, the filename extension or filetype property is validated against the list. If the file(s) do not match the acceptance criteria, the component will not add the file(s), and it will show an error message with the file name. */ accept?: string; /** * The label for the file button. Overrides default text. The button is not visible for assistive technology */ buttonLabel?: string; /** * Additional class names to apply to the file input */ className?: string; /** * If `true`, the file input will be disabled */ disabled?: boolean; /** * If `true`, the file input will have a drag and drop area */ dragAndDrop?: boolean; /** * Overrides default drag and drop area text */ dragAndDropLabel?: string; /** * Overrides default label text between the drag and drop area and the input */ dragAndDropInputLabel?: string; /** * The error text content that will be shown below the input */ errorText?: string; /** * The helper text content that will be shown below the input */ helperText?: string; /** * The id of the input element */ id: string; /** * The info text content that will be shown below the input */ infoText?: string; /** * The label for the input */ label: string; /** * The language of the component. It affects which language is used to present component-specific messages, labels, and aria-labels * * @default "fi" */ language?: Language; /** * Maximum file size in bytes. If present, the file size is compared to this property. If the file(s) size property is larger than the max size, the component will not add the file(s), and it will show an error message with the file name. */ maxSize?: number; /** * A Boolean that indicates that more than one file can be chosen */ multiple?: boolean; /** * Callback fired when the list of files changes */ onChange: (files: File[]) => void; /** * If `true`, the label is displayed as required and the `input` element will be required */ required?: boolean; /** * Override or extend the styles applied to the component */ style?: React.CSSProperties; /** * The success text content that will be shown below the input */ successText?: string; }; type FileItem = { uiId: string; file: File; }; const convertFileToFileItem = (file: File): FileItem => ({ file, uiId: uniqueId(file.name) }); const convertFileItemToFile = (fileItem: FileItem): File => fileItem.file; export const formatBytes = (bytes: number): string => { if (bytes === 0) { return '0 B'; } const sizeUnits: string[] = ['B', 'KB', 'MB', 'GB', 'TB']; const sizeUnitIndex = Math.floor(Math.log(bytes) / Math.log(1024)); const sizeInUnit = bytes / 1024 ** sizeUnitIndex; return `${sizeUnitIndex < 2 || sizeInUnit % 1 === 0 ? Math.round(sizeInUnit) : sizeInUnit.toFixed(1)} ${ sizeUnits[sizeUnitIndex] }`; }; const getButtonLabel = (language: Language, multiple: boolean): string => { return { en: `Add ${multiple ? 'files' : 'a file'}`, fi: `Lisää ${multiple ? 'tiedostoja' : 'tiedosto'}`, sv: `Välj ${multiple ? 'filer' : 'en fil'}`, }[language]; }; const getDragAndDropLabel = (language: Language): string => { return { en: 'Drag files here', fi: 'Raahaa tiedostot tähän', sv: 'Dra filerna hit', }[language]; }; const getDragAndDropInputLabel = (language: Language): string => { return { en: 'or browse from your device', fi: 'tai valitse tiedostot laitteeltasi', sv: 'eller välj filerna från din enhet', }[language]; }; const getNoFilesAddedMessage = (language: Language): string => { return { en: 'No file has been selected.', fi: 'Yhtään tiedostoa ei ole valittu.', sv: 'Ingen fil har valts.', }[language]; }; const getRemoveButtonLabel = (language: Language): string => { return { en: 'Remove', fi: 'Poista', sv: 'Ta bort', }[language]; }; const getRemoveButtonAriaLabel = (language: Language, fileName: string): string => { return { en: `Remove ${fileName} from the added files.`, fi: `Poista tiedosto ${fileName} lisätyistä tiedostoista.`, sv: `Ta bort ${fileName} från filerna som lagts till.`, }[language]; }; const getFileListAriaLabel = (language: Language, totalAddedFiles: number): string => { return { en: `${totalAddedFiles === 0 ? '1 file' : `${totalAddedFiles} files`} added.`, fi: `${totalAddedFiles === 0 ? '1 tiedosto' : `${totalAddedFiles} tiedostoa`} added.`, sv: `${totalAddedFiles === 0 ? '1 fil' : `${totalAddedFiles} filer`} har lagts till.`, }[language]; }; const getRemoveSuccessMessage = (language: Language): string => { return { en: 'The file has been deleted.', fi: 'Tiedosto poistettu.', sv: 'Filen har tagits bort.', }[language]; }; const getAddSuccessMessage = (language: Language, numberOfAdded: number, numberOfTotal: number): string => { const partOfTotalStr = numberOfAdded === numberOfTotal ? numberOfAdded : `${numberOfAdded}/${numberOfTotal}`; return { en: `${partOfTotalStr} file(s) added.`, fi: `${partOfTotalStr} tiedosto(a) lisätty.`, sv: `${partOfTotalStr} fil(er) har lagts till.`, }[language]; }; const getMaxSizeMessage = (language: Language, maxSize: number): string => { const formattedMaxSize = formatBytes(maxSize); return { en: `The maximum file size is ${formattedMaxSize}.`, fi: `Suurin sallittu tiedostokoko on ${formattedMaxSize}.`, sv: `Den maximala filstorleken är ${formattedMaxSize}.`, }[language]; }; const getAcceptString = (accept: string, conjunction: string): string => { const acceptList = accept.split(','); if (acceptList.length === 1) { return acceptList.toString(); } const last = acceptList.pop(); return `${acceptList.join(', ')} ${conjunction} ${last}`; }; const getAcceptMessage = (language: Language, accept: string): string => { return { en: `Only ${getAcceptString(accept, 'and')} files.`, fi: `Vain ${getAcceptString(accept, 'ja')} tiedostoja.`, sv: `Endast ${getAcceptString(accept, 'och')} filer.`, }[language]; }; const getFailedValidationTitle = (language: Language, numberOfFailed: number, numberOfTotal: number): string => { const partOfTotalStr = `${numberOfFailed}/${numberOfTotal}`; return { en: `File processing failed for ${partOfTotalStr} files:\n`, fi: `Tiedostonlisäys epäonnistui ${partOfTotalStr} tiedoston kohdalla:\n`, sv: `Filprocesseringen av filerna ${partOfTotalStr} misslyckades:\n`, }[language]; }; const getAcceptErrorMessage = (language: Language, file: File, accept: string): string => { const acceptMessage = getAcceptMessage(language, accept); return { en: `The file type, ${file.name}, is not supported. ${acceptMessage}`, fi: `Tiedoston, ${file.name}, tyyppi ei vastaa hyväksyttyjä tiedostotyppejä. ${acceptMessage}`, sv: `Filformatet, ${file.name}, stöds inte. ${acceptMessage}`, }[language]; }; const getMaxSizeErrorMessage = (language: Language, file: File, maxSize: number): string => { const fileSize = formatBytes(file.size); return { en: `File, ${file.name}, is too large (${fileSize}). ${getMaxSizeMessage(language, maxSize)}`, fi: `Tiedosto, ${file.name} on liian suuri (${fileSize}). ${getMaxSizeMessage(language, maxSize)}`, sv: `Filen, ${file.name}, är för stor (${fileSize}). ${getMaxSizeMessage(language, maxSize)}`, }[language]; }; enum ValidationErrorType { accept = 'accept', maxSize = 'maxSize', } type ValidationError = { type: ValidationErrorType; text: string; }; const validateAccept = (language: Language, accept: string) => (file: File): true | ValidationError => { const extension = path.extname(file.name); const fileType = file.type; const acceptedExtensions = accept.split(',').map((str) => str.trim()); const isMatchingType = !!acceptedExtensions.find( (acceptExtension) => acceptExtension.includes(fileType) || acceptExtension.includes(`${fileType.split('/')[0]}/*`), ); const hasMatchingFileExtension = !!acceptedExtensions.find((acceptExtension) => acceptExtension === extension); return ( (!!fileType && (isMatchingType || hasMatchingFileExtension)) || { type: ValidationErrorType.accept, text: getAcceptErrorMessage(language, file, accept), } ); }; const validateMaxSize = (language: Language, maxSize: number) => (file: File): true | ValidationError => { return ( file.size < maxSize || { type: ValidationErrorType.maxSize, text: getMaxSizeErrorMessage(language, file, maxSize), } ); }; export const FileInput = ({ id, label, buttonLabel, language = 'fi', disabled, dragAndDrop, dragAndDropLabel, dragAndDropInputLabel, maxSize, className = '', successText, errorText, helperText, infoText, onChange, required, style, accept, multiple, }: FileInputProps) => { const inputRef = useRef<HTMLInputElement>(null); const didMountRef = useRef<boolean>(false); const [selectedFileItems, setSelectedFileItems] = useState<FileItem[]>([]); const [inputStateText, setInputStateText] = useState<string | undefined>(); const [invalidText, setInvalidText] = useState<string | undefined>(); const [processSuccessText, setProcessSuccessText] = useState<string | undefined>(); const hasFileItems = selectedFileItems && selectedFileItems.length > 0; const fileListId = `${id}-list`; const fileListRef = useRef<HTMLUListElement>(null); const fileListFocusIndexRef = useRef<number>(); const dropAreaRef = useRef<HTMLDivElement>(null); const [isDragOverDrop, setIsDragOverDrop] = useState<boolean>(false); const instructionsText = [ accept && getAcceptMessage(language, accept), maxSize && getMaxSizeMessage(language, maxSize), ] .filter((t) => !!t) .join(' '); const helperTextToUse = helperText || instructionsText; const successTextToUse = successText || processSuccessText; const errorTextToUse = errorText || invalidText; const infoTextToUse = infoText || inputStateText; const wrapperProps = { className, helperText: helperTextToUse, successText: successTextToUse, errorText: errorTextToUse, infoText: disabled ? undefined : infoTextToUse, id, label, required, style, }; const passClickToInput = () => { if (inputRef.current) { inputRef.current.click(); } }; const passFocusToInput = () => { if (inputRef.current) { inputRef.current.focus(); } }; const resetInputValue = () => { if (inputRef.current) { inputRef.current.value = ''; } }; const clearState = () => { setProcessSuccessText(undefined); setInputStateText(undefined); setInvalidText(undefined); fileListFocusIndexRef.current = null; }; const validationFns: ((file: File) => true | ValidationError)[] = [ accept ? validateAccept(language, accept) : undefined, maxSize ? validateMaxSize(language, maxSize) : undefined, ].filter((fn) => !!fn); const runValidations = (files: File[]): { validFiles: File[]; validationErrors: ValidationError[][] } => { if (validationFns.length === 0) { return { validFiles: files, validationErrors: [] }; } return files.reduce( (acc: { validFiles: File[]; validationErrors: ValidationError[][] }, file) => { const errors = validationFns.map((fn) => fn(file)).filter((r) => r !== true) as ValidationError[]; if (errors.length > 0) { return { ...acc, validationErrors: [...acc.validationErrors, errors] }; } return { ...acc, validFiles: [...acc.validFiles, file] }; }, { validFiles: [], validationErrors: [] }, ); }; const getValidationErrorsMessage = (errors: (ValidationError | ValidationError[])[], totalNumberOfFiles: number) => `${getFailedValidationTitle(language, errors.length, totalNumberOfFiles)}${errors .map((errorSet) => `- ${errorSet[0].text}`) .join('\n')}`; const afterFileItemsChange = (fileItems: FileItem[]) => { if (onChange) { const selectedFiles: File[] = fileItems.map(convertFileItemToFile); onChange(selectedFiles); } // Clear input value on every change to ensure it triggers a onChange event when files are added resetInputValue(); }; const handleSingleFileChange = (files: File[]) => { if (files.length > 0) { const { validFiles, validationErrors } = runValidations(files); if (validationErrors.length > 0) { setInvalidText(getValidationErrorsMessage(validationErrors, 1)); } else { const newFileItems: FileItem[] = [convertFileToFileItem(validFiles[0])]; setSelectedFileItems(newFileItems); setProcessSuccessText(getAddSuccessMessage(language, 1, 1)); afterFileItemsChange(newFileItems); } } }; const handleMultipleChange = (files: File[]) => { if (files.length > 0) { const { validFiles, validationErrors } = runValidations(files); if (validationErrors.length > 0) { setInvalidText(getValidationErrorsMessage(validationErrors, files.length)); } if (validFiles.length > 0) { const newFileItems: FileItem[] = validFiles.map(convertFileToFileItem); const allFileItems: FileItem[] = [...selectedFileItems, ...newFileItems]; setSelectedFileItems(allFileItems); setProcessSuccessText(getAddSuccessMessage(language, validFiles.length, files.length)); afterFileItemsChange(allFileItems); } } }; const onFilesChange = (files: File[]) => { clearState(); if (multiple) { handleMultipleChange(files); } else { handleSingleFileChange(files); } }; const onRemoveFileFromList = (fileItemToRemove: FileItem, indexToRemove: number) => { clearState(); const selectedFileItemsWithoutRemoved: FileItem[] = selectedFileItems.filter( (fileItem: FileItem) => fileItem.uiId !== fileItemToRemove.uiId, ); setSelectedFileItems(selectedFileItemsWithoutRemoved); if (selectedFileItemsWithoutRemoved.length > 0) { fileListFocusIndexRef.current = indexToRemove > 0 ? indexToRemove - 1 : 0; setInputStateText(getRemoveSuccessMessage(language)); } else { passFocusToInput(); setInputStateText(getNoFilesAddedMessage(language)); } afterFileItemsChange(selectedFileItemsWithoutRemoved); }; const onDragEnter = (event: React.DragEvent<HTMLDivElement>) => { event.preventDefault(); event.stopPropagation(); setIsDragOverDrop(true); }; const onDragLeave = (event: React.DragEvent<HTMLDivElement>) => { event.preventDefault(); event.stopPropagation(); setIsDragOverDrop(false); }; const onDrop = (event: React.DragEvent<HTMLDivElement>) => { const { dataTransfer }: { dataTransfer: DataTransfer } = event; onDragLeave(event); onFilesChange(Array.from(dataTransfer.files)); }; useEffect(() => { if (!didMountRef.current) { setInputStateText(getNoFilesAddedMessage(language)); didMountRef.current = true; } }, [setInputStateText, language]); // Compose aria-describedby attribute const ariaDescribedBy: string = [ composeAriaDescribedBy(id, helperTextToUse, errorTextToUse, successText, infoTextToUse), hasFileItems && fileListId, ] .filter((text) => !!text) .join(' '); return ( <> <InputWrapper {...wrapperProps}> <div className={styles.fileInputContainer}> {dragAndDrop && ( <> <div aria-hidden className={classNames( styles.dragAndDrop, isDragOverDrop && styles.dragAndDropActive, disabled && styles.dragAndDropDisabled, )} ref={dropAreaRef} {...(disabled ? {} : { onClick: () => passClickToInput(), onDragEnter, onDragOver: onDragEnter, onDragLeave, onDrop, })} > <div className={styles.dragAndDropLabel}> <IconUpload aria-hidden /> <span className={styles.dragAndDropLabelText}> {dragAndDropLabel || getDragAndDropLabel(language)} </span> </div> </div> <div className={styles.dragAndDropHelperText}> {dragAndDropInputLabel || getDragAndDropInputLabel(language)} </div> </> )} <div className={styles.fileInputWrapper}> <Button aria-hidden tabIndex={-1} variant="secondary" iconLeft={<IconPlus aria-hidden />} onClick={(event) => { event.preventDefault(); event.stopPropagation(); passFocusToInput(); passClickToInput(); }} disabled={disabled} > {buttonLabel || getButtonLabel(language, multiple)} </Button> <input type="file" ref={inputRef} id={id} disabled={disabled} required={required} aria-describedby={ariaDescribedBy} className={styles.fileInput} onChange={(event: ChangeEvent<HTMLInputElement>) => { onFilesChange(Array.from(event.target.files)); }} {...(accept ? { accept } : {})} {...(multiple ? { multiple } : {})} /> </div> </div> </InputWrapper> <ul id={fileListId} ref={fileListRef} tabIndex={-1} className={styles.fileList} aria-label={ hasFileItems ? getFileListAriaLabel(language, selectedFileItems.length) : getNoFilesAddedMessage(language) } > {selectedFileItems.map((item: FileItem, index: number) => ( <li key={item.uiId} className={styles.fileListItem} tabIndex={-1} ref={(el) => { if (el && fileListRef.current && fileListFocusIndexRef.current === index) { el.focus(); } }} > {item.file.type.startsWith('image') ? <IconPhoto aria-hidden /> : <IconDocument aria-hidden />} <div className={styles.fileListItemTitle}> <span className={styles.fileListItemName}>{item.file.name}</span> <span className={styles.fileListItemSize}>({formatBytes(item.file.size)})</span> </div> <Button onClick={(event) => { event.preventDefault(); event.stopPropagation(); onRemoveFileFromList(item, index); }} variant="supplementary" size="small" theme="black" iconLeft={<IconCross />} aria-label={getRemoveButtonAriaLabel(language, item.file.name)} className={styles.fileListItemButton} disabled={disabled} > {getRemoveButtonLabel(language)} </Button> </li> ))} </ul> </> ); };
the_stack
import MultiFormat from '@requestnetwork/multi-format'; import Utils from '@requestnetwork/utils'; import { EventEmitter } from 'events'; import { DataAccessTypes, EncryptionTypes, TransactionTypes } from '@requestnetwork/types'; import { TransactionManager } from '../src/index'; import TransactionsFactory from '../src/transactions-factory'; import * as TestData from './unit/utils/test-data'; const extraTopics = ['topic1', 'topic2']; const fakeTxHash = '0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; const data = '{ "what": "ever", "it": "is,", "this": "must", "work": true }'; const data2 = '{"or": "can", "be":false}'; const tx: DataAccessTypes.ITimestampedTransaction = { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: { data }, }; const tx2: DataAccessTypes.ITimestampedTransaction = { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: { data: data2 }, }; const dataHash = Utils.crypto.normalizeKeccak256Hash(JSON.parse(data)); const channelId = MultiFormat.serialize(dataHash); const dataHash2 = Utils.crypto.normalizeKeccak256Hash(JSON.parse(data2)); const channelId2 = MultiFormat.serialize(dataHash2); const fakeMetaDataAccessPersistReturn: DataAccessTypes.IReturnPersistTransaction = Object.assign( new EventEmitter(), { meta: { transactionStorageLocation: 'fakeDataId', topics: extraTopics }, result: {}, }, ); const fakeMetaDataAccessGetReturn: DataAccessTypes.IReturnGetTransactions = { meta: { transactionsStorageLocation: ['fakeDataId1', 'fakeDataId2'] }, result: { transactions: [tx, tx2] }, }; const fakeMetaDataAccessGetChannelsReturn: DataAccessTypes.IReturnGetChannelsByTopic = { meta: { transactionsStorageLocation: { [channelId]: ['fakeDataId1', 'fakeDataId2'] } }, result: { transactions: { [channelId]: [tx, tx2] } }, }; let fakeDataAccess: DataAccessTypes.IDataAccess; /* eslint-disable @typescript-eslint/no-unused-expressions */ describe('index', () => { beforeEach(() => { fakeDataAccess = { _getStatus: jest.fn(), getChannelsByMultipleTopics: jest.fn().mockReturnValue(fakeMetaDataAccessGetChannelsReturn), getChannelsByTopic: jest.fn().mockReturnValue(fakeMetaDataAccessGetChannelsReturn), getTransactionsByChannelId: jest.fn().mockReturnValue(fakeMetaDataAccessGetReturn), initialize: jest.fn(), // persistTransaction: jest.fn().mockReturnValue(fakeMetaDataAccessPersistReturn), persistTransaction: jest.fn((): any => { setTimeout(() => { fakeMetaDataAccessPersistReturn.emit( 'confirmed', { meta: { transactionStorageLocation: 'fakeDataId', topics: extraTopics }, result: { topics: [fakeTxHash] }, }, // eslint-disable-next-line no-magic-numbers 100, ); }); return fakeMetaDataAccessPersistReturn; }), }; }); describe('persistTransaction', () => { describe('in a new channel', () => { it('can persist a clear transaction in a new channel', async () => { const transactionManager = new TransactionManager(fakeDataAccess); const ret = await transactionManager.persistTransaction(data, channelId, extraTopics); const resultConfirmed1 = await new Promise((resolve) => ret.on('confirmed', resolve)); // 'result Confirmed wrong' expect(resultConfirmed1).toEqual({ meta: { dataAccessMeta: { transactionStorageLocation: 'fakeDataId', topics: extraTopics }, encryptionMethod: undefined, }, result: {}, }); // 'ret.result is wrong' expect(ret.result).toEqual({}); // 'ret.meta is wrong' expect(ret.meta).toEqual({ dataAccessMeta: fakeMetaDataAccessPersistReturn.meta, encryptionMethod: undefined, }); expect(fakeDataAccess.persistTransaction).toHaveBeenCalledWith( await TransactionsFactory.createClearTransaction(data), channelId, extraTopics.concat([channelId]), ); }); it('can persist an encrypted transaction in a new channel', async () => { const transactionManager = new TransactionManager(fakeDataAccess); const ret = await transactionManager.persistTransaction(data, channelId, extraTopics, [ TestData.idRaw1.encryptionParams, TestData.idRaw2.encryptionParams, TestData.idRaw3.encryptionParams, ]); // 'ret.result is wrong' expect(ret.result).toEqual({}); // 'ret.meta is wrong' expect(ret.meta).toEqual({ dataAccessMeta: fakeMetaDataAccessPersistReturn.meta, encryptionMethod: 'ecies-aes256-gcm', }); expect(fakeDataAccess.persistTransaction).toHaveBeenCalledTimes(1); }); it('cannot persist a transaction if data access emit error', async () => { const fakeDataAccessEmittingError = Object.assign({}, fakeDataAccess); fakeDataAccessEmittingError.persistTransaction = jest.fn((): any => { const persistWithEvent = Object.assign( new EventEmitter(), fakeMetaDataAccessPersistReturn, ); setTimeout(() => { // eslint-disable-next-line no-magic-numbers persistWithEvent.emit('error', 'error for test purpose', 100); }); return persistWithEvent; }); const transactionManager = new TransactionManager(fakeDataAccess); const ret = await transactionManager.persistTransaction(data, channelId, extraTopics); ret.on('error', (error) => { // 'result Confirmed wrong' expect(error).toBe('error for test purpose'); }); // 'ret.result is wrong' expect(ret.result).toEqual({}); // 'ret.meta is wrong' expect(ret.meta).toEqual({ dataAccessMeta: fakeMetaDataAccessPersistReturn.meta, encryptionMethod: undefined, }); expect(fakeDataAccess.persistTransaction).toHaveBeenCalledWith( await TransactionsFactory.createClearTransaction(data), channelId, extraTopics.concat([channelId]), ); }); }); describe('in an existing new channel', () => { afterEach(() => { jest.clearAllMocks(); }); it('can persist a clear transaction in an existing channel', async () => { const transactionManager = new TransactionManager(fakeDataAccess); const ret = await transactionManager.persistTransaction(data2, channelId, extraTopics); // 'ret.result is wrong' expect(ret.result).toEqual({}); // 'ret.meta is wrong' expect(ret.meta).toEqual({ dataAccessMeta: fakeMetaDataAccessPersistReturn.meta, encryptionMethod: undefined, }); expect(fakeDataAccess.persistTransaction).toHaveBeenCalledWith( await TransactionsFactory.createClearTransaction(data2), channelId, extraTopics.concat([channelId2]), ); }); it('can persist a encrypted transaction in an existing channel', async () => { const encryptedTx = await TransactionsFactory.createEncryptedTransactionInNewChannel(data, [ TestData.idRaw1.encryptionParams, ]); const fakeMetaDataAccessGetReturnWithEncryptedTransaction: DataAccessTypes.IReturnGetTransactions = { meta: { transactionsStorageLocation: ['fakeDataId1'], }, result: { transactions: [ { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: encryptedTx, }, ], }, }; fakeDataAccess = { _getStatus: jest.fn(), getChannelsByMultipleTopics: jest.fn(), getChannelsByTopic: jest.fn(), getTransactionsByChannelId: jest .fn() .mockReturnValue(fakeMetaDataAccessGetReturnWithEncryptedTransaction), initialize: jest.fn(), persistTransaction: jest.fn().mockReturnValue(fakeMetaDataAccessPersistReturn), }; const transactionManager = new TransactionManager( fakeDataAccess, TestData.fakeDecryptionProvider, ); const ret = await transactionManager.persistTransaction(data2, channelId, extraTopics); // 'ret.result is wrong' expect(ret.result).toEqual({}); // 'ret.meta is wrong' expect(ret.meta).toEqual({ dataAccessMeta: fakeMetaDataAccessPersistReturn.meta, encryptionMethod: 'ecies-aes256-gcm', }); // TODO challenge this expect(fakeDataAccess.persistTransaction).toHaveBeenCalledWith( { encryptedData: expect.stringMatching(/^04.{76}/), }, channelId, extraTopics.concat([channelId2]), ); }); it('cannot persist a encrypted transaction on a channel not found', async () => { const fakeMetaDataAccessGetReturnEmpty: DataAccessTypes.IReturnGetTransactions = { meta: { transactionsStorageLocation: [], }, result: { transactions: [], }, }; fakeDataAccess = { _getStatus: jest.fn(), getChannelsByMultipleTopics: jest.fn(), getChannelsByTopic: jest.fn(), getTransactionsByChannelId: jest.fn().mockReturnValue(fakeMetaDataAccessGetReturnEmpty), initialize: jest.fn(), persistTransaction: jest.fn().mockReturnValue(fakeMetaDataAccessPersistReturn), }; const transactionManager = new TransactionManager( fakeDataAccess, TestData.fakeDecryptionProvider, ); await expect( transactionManager.persistTransaction(data2, channelId, extraTopics), ).rejects.toThrowError(`Impossible to retrieve the channel: ${channelId}`); }); it('cannot persist a encrypted transaction in an existing channel with encryption parameters given', async () => { const encryptedTx = await TransactionsFactory.createEncryptedTransactionInNewChannel(data, [ TestData.idRaw1.encryptionParams, ]); const fakeMetaDataAccessGetReturnWithEncryptedTransaction: DataAccessTypes.IReturnGetTransactions = { meta: { transactionsStorageLocation: ['fakeDataId1'], }, result: { transactions: [ { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: encryptedTx, }, ], }, }; fakeDataAccess = { _getStatus: jest.fn(), getChannelsByMultipleTopics: jest.fn(), getChannelsByTopic: jest.fn(), getTransactionsByChannelId: jest .fn() .mockReturnValue(fakeMetaDataAccessGetReturnWithEncryptedTransaction), initialize: jest.fn(), persistTransaction: jest.fn().mockReturnValue(fakeMetaDataAccessPersistReturn), }; const transactionManager = new TransactionManager( fakeDataAccess, TestData.fakeDecryptionProvider, ); await expect( transactionManager.persistTransaction(data2, channelId, extraTopics, [ TestData.idRaw1.encryptionParams, ]), ).rejects.toThrowError('Impossible to add new stakeholder to an existing channel'); }); }); }); describe('getTransactionsByChannelId', () => { it('can get transactions by channel id', async () => { const transactionManager = new TransactionManager(fakeDataAccess); const ret = await transactionManager.getTransactionsByChannelId(channelId); // 'ret.result is wrong' expect(ret.result).toEqual(fakeMetaDataAccessGetReturn.result); // 'ret.meta is wrong' expect(ret.meta).toEqual({ dataAccessMeta: fakeMetaDataAccessGetReturn.meta, ignoredTransactions: [null, null], }); expect(fakeDataAccess.getTransactionsByChannelId).toHaveBeenCalledWith(channelId, undefined); }); it('can getTransactionsByChannelId() with channelId not matching the first transaction hash', async () => { const txWrongHash: DataAccessTypes.ITimestampedTransaction = { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: { data: '{"wrong": "hash"}' }, }; const fakeMetaDataAccessGetReturnFirstHashWrong: DataAccessTypes.IReturnGetTransactions = { meta: { transactionsStorageLocation: ['fakeDataId1', 'fakeDataId1', 'fakeDataId2'] }, result: { transactions: [txWrongHash, tx, tx2] }, }; fakeDataAccess = { _getStatus: jest.fn(), getChannelsByMultipleTopics: jest.fn(), getChannelsByTopic: jest.fn(), getTransactionsByChannelId: jest .fn() .mockReturnValue(fakeMetaDataAccessGetReturnFirstHashWrong), initialize: jest.fn(), persistTransaction: jest.fn(), }; const transactionManager = new TransactionManager(fakeDataAccess); const ret = await transactionManager.getTransactionsByChannelId(channelId); // 'ret.meta is wrong' expect(ret.meta).toEqual({ dataAccessMeta: fakeMetaDataAccessGetReturnFirstHashWrong.meta, ignoredTransactions: [ { reason: 'as first transaction, the hash of the transaction do not match the channelId', transaction: txWrongHash, }, null, null, ], }); // 'ret.result is wrong' expect(ret.result).toEqual({ transactions: [null, tx, tx2], }); expect(fakeDataAccess.getTransactionsByChannelId).toHaveBeenCalledWith(channelId, undefined); }); it('can getTransactionsByChannelId() the first transaction data not parsable', async () => { const txWrongHash: DataAccessTypes.ITimestampedTransaction = { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: { data: 'Not parsable' }, }; const fakeMetaDataAccessGetReturnFirstHashWrong: DataAccessTypes.IReturnGetTransactions = { meta: { transactionsStorageLocation: ['fakeDataId1', 'fakeDataId1', 'fakeDataId2'] }, result: { transactions: [txWrongHash, tx, tx2] }, }; fakeDataAccess = { _getStatus: jest.fn(), getChannelsByMultipleTopics: jest.fn(), getChannelsByTopic: jest.fn(), getTransactionsByChannelId: jest .fn() .mockReturnValue(fakeMetaDataAccessGetReturnFirstHashWrong), initialize: jest.fn(), persistTransaction: jest.fn(), }; const transactionManager = new TransactionManager(fakeDataAccess); const ret = await transactionManager.getTransactionsByChannelId(channelId); // 'ret.meta is wrong' expect(ret.meta).toEqual({ dataAccessMeta: fakeMetaDataAccessGetReturnFirstHashWrong.meta, ignoredTransactions: [ { reason: 'Impossible to JSON parse the transaction', transaction: txWrongHash, }, null, null, ], }); // 'ret.result is wrong' expect(ret.result).toEqual({ transactions: [null, tx, tx2], }); expect(fakeDataAccess.getTransactionsByChannelId).toHaveBeenCalledWith(channelId, undefined); }); it('can get a transaction from an encrypted channel', async () => { const encryptedTx = await TransactionsFactory.createEncryptedTransactionInNewChannel(data, [ TestData.idRaw1.encryptionParams, TestData.idRaw2.encryptionParams, TestData.idRaw3.encryptionParams, ]); const fakeMetaDataAccessGetReturnWithEncryptedTransaction: DataAccessTypes.IReturnGetTransactions = { meta: { transactionsStorageLocation: ['fakeDataId1'] }, result: { transactions: [ { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: encryptedTx, }, ], }, }; fakeDataAccess = { _getStatus: jest.fn(), getChannelsByMultipleTopics: jest.fn(), getChannelsByTopic: jest.fn(), getTransactionsByChannelId: jest .fn() .mockReturnValue(fakeMetaDataAccessGetReturnWithEncryptedTransaction), initialize: jest.fn(), persistTransaction: jest.fn(), }; const transactionManager = new TransactionManager( fakeDataAccess, TestData.fakeDecryptionProvider, ); const ret = await transactionManager.getTransactionsByChannelId(channelId); // 'return is wrong' expect(ret).toEqual({ meta: { dataAccessMeta: { transactionsStorageLocation: ['fakeDataId1'] }, encryptionMethod: 'ecies-aes256-gcm', ignoredTransactions: [null], }, result: { transactions: [ { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: { data }, }, ], }, }); }); it('cannot get a transaction from an encrypted channel without decryption provider', async () => { const encryptedTx = await TransactionsFactory.createEncryptedTransactionInNewChannel(data, [ TestData.idRaw1.encryptionParams, TestData.idRaw2.encryptionParams, TestData.idRaw3.encryptionParams, ]); const fakeMetaDataAccessGetReturnWithEncryptedTransaction: DataAccessTypes.IReturnGetTransactions = { meta: { transactionsStorageLocation: ['fakeDataId1'] }, result: { transactions: [ { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: encryptedTx, }, ], }, }; fakeDataAccess = { _getStatus: jest.fn(), getChannelsByMultipleTopics: jest.fn(), getChannelsByTopic: jest.fn(), getTransactionsByChannelId: jest .fn() .mockReturnValue(fakeMetaDataAccessGetReturnWithEncryptedTransaction), initialize: jest.fn(), persistTransaction: jest.fn(), }; const transactionManager = new TransactionManager(fakeDataAccess); const ret = await transactionManager.getTransactionsByChannelId(channelId); // 'return is wrong' expect(ret).toEqual({ meta: { dataAccessMeta: { transactionsStorageLocation: ['fakeDataId1'] }, ignoredTransactions: [ { reason: 'No decryption provider given', transaction: { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: encryptedTx, }, }, ], }, result: { transactions: [null] }, }); }); it('can get two transactions with different encryptions from the same encrypted channel', async () => { const encryptedTx = await TransactionsFactory.createEncryptedTransactionInNewChannel(data, [ TestData.idRaw1.encryptionParams, TestData.idRaw2.encryptionParams, ]); const encryptedTx2 = await TransactionsFactory.createEncryptedTransactionInNewChannel(data2, [ TestData.idRaw3.encryptionParams, ]); const fakeMetaDataAccessGetReturnWithEncryptedTransaction: DataAccessTypes.IReturnGetTransactions = { meta: { transactionsStorageLocation: ['fakeDataId1', 'fakeDataId2'], }, result: { transactions: [ { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: encryptedTx, }, { state: TransactionTypes.TransactionState.PENDING, timestamp: 2, transaction: encryptedTx2, }, ], }, }; fakeDataAccess = { _getStatus: jest.fn(), getChannelsByMultipleTopics: jest.fn(), getChannelsByTopic: jest.fn(), getTransactionsByChannelId: jest .fn() .mockReturnValue(fakeMetaDataAccessGetReturnWithEncryptedTransaction), initialize: jest.fn(), persistTransaction: jest.fn(), }; const transactionManager = new TransactionManager( fakeDataAccess, TestData.fakeDecryptionProvider, ); const ret = await transactionManager.getTransactionsByChannelId(channelId); // 'return is wrong' expect(ret).toEqual({ meta: { dataAccessMeta: { transactionsStorageLocation: ['fakeDataId1', 'fakeDataId2'], }, encryptionMethod: 'ecies-aes256-gcm', ignoredTransactions: [ null, { reason: 'the properties "encryptionMethod" and "keys" have been already given for this channel', transaction: { state: TransactionTypes.TransactionState.PENDING, timestamp: 2, transaction: encryptedTx2, }, }, ], }, result: { transactions: [ { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: { data }, }, null, ], }, }); }); it('can get two transactions with different encryptions from the same encrypted channel the first has the right hash but wrong data', async () => { const encryptedTxFakeHash = await TransactionsFactory.createEncryptedTransactionInNewChannel( data2, [TestData.idRaw3.encryptionParams], ); const encryptedTx = await TransactionsFactory.createEncryptedTransactionInNewChannel(data, [ TestData.idRaw1.encryptionParams, TestData.idRaw2.encryptionParams, ]); const fakeMetaDataAccessGetReturnWithEncryptedTransaction: DataAccessTypes.IReturnGetTransactions = { meta: { transactionsStorageLocation: ['fakeDataId1', 'fakeDataId2'], }, result: { transactions: [ { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: encryptedTxFakeHash, }, { state: TransactionTypes.TransactionState.PENDING, timestamp: 2, transaction: encryptedTx, }, ], }, }; fakeDataAccess = { _getStatus: jest.fn(), getChannelsByMultipleTopics: jest.fn(), getChannelsByTopic: jest.fn(), getTransactionsByChannelId: jest .fn() .mockReturnValue(fakeMetaDataAccessGetReturnWithEncryptedTransaction), initialize: jest.fn(), persistTransaction: jest.fn(), }; const transactionManager = new TransactionManager( fakeDataAccess, TestData.fakeDecryptionProvider, ); const ret = await transactionManager.getTransactionsByChannelId(channelId); // 'return is wrong' expect(ret).toEqual({ meta: { dataAccessMeta: { transactionsStorageLocation: ['fakeDataId1', 'fakeDataId2'], }, encryptionMethod: 'ecies-aes256-gcm', ignoredTransactions: [ { reason: 'as first transaction, the hash of the transaction do not match the channelId', transaction: { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: encryptedTxFakeHash, }, }, null, ], }, result: { transactions: [ null, { state: TransactionTypes.TransactionState.PENDING, timestamp: 2, transaction: { data }, }, ], }, }); }); it('can get two transactions, the first is encrypted but the second is clear (will be ignored)', async () => { const encryptedTx = await TransactionsFactory.createEncryptedTransactionInNewChannel(data, [ TestData.idRaw1.encryptionParams, TestData.idRaw2.encryptionParams, ]); const fakeMetaDataAccessGetReturnWithEncryptedTransaction: DataAccessTypes.IReturnGetTransactions = { meta: { transactionsStorageLocation: ['fakeDataId1', 'fakeDataId2'], }, result: { transactions: [ { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: encryptedTx, }, { state: TransactionTypes.TransactionState.PENDING, timestamp: 2, transaction: { data: data2 }, }, ], }, }; fakeDataAccess = { _getStatus: jest.fn(), getChannelsByMultipleTopics: jest.fn(), getChannelsByTopic: jest.fn(), getTransactionsByChannelId: jest .fn() .mockReturnValue(fakeMetaDataAccessGetReturnWithEncryptedTransaction), initialize: jest.fn(), persistTransaction: jest.fn(), }; const transactionManager = new TransactionManager( fakeDataAccess, TestData.fakeDecryptionProvider, ); const ret = await transactionManager.getTransactionsByChannelId(channelId); // 'return is wrong' expect(ret).toEqual({ meta: { dataAccessMeta: { transactionsStorageLocation: ['fakeDataId1', 'fakeDataId2'], }, encryptionMethod: 'ecies-aes256-gcm', ignoredTransactions: [ null, { reason: `Clear transactions are not allowed in encrypted channel`, transaction: { state: TransactionTypes.TransactionState.PENDING, timestamp: 2, transaction: { data: data2 }, }, }, ], }, result: { transactions: [ { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: { data }, }, null, ], }, }); }); it('can get two transactions first encrypted but decrypt impossible and second clear', async () => { const encryptedTx = await TransactionsFactory.createEncryptedTransactionInNewChannel(data, [ { key: '0396212fc129c2f78771218b2e93da7a5aac63490a42bb41b97848c39c14fe65cd', method: EncryptionTypes.METHOD.ECIES, }, ]); const fakeMetaDataAccessGetReturnWithEncryptedTransaction: DataAccessTypes.IReturnGetTransactions = { meta: { transactionsStorageLocation: ['fakeDataId1', 'fakeDataId2'], }, result: { transactions: [ { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: encryptedTx, }, { state: TransactionTypes.TransactionState.PENDING, timestamp: 2, transaction: { data: data2 }, }, ], }, }; fakeDataAccess = { _getStatus: jest.fn(), getChannelsByMultipleTopics: jest.fn(), getChannelsByTopic: jest.fn(), getTransactionsByChannelId: jest .fn() .mockReturnValue(fakeMetaDataAccessGetReturnWithEncryptedTransaction), initialize: jest.fn(), persistTransaction: jest.fn(), }; const transactionManager = new TransactionManager( fakeDataAccess, TestData.fakeDecryptionProvider, ); const ret = await transactionManager.getTransactionsByChannelId(channelId); // 'return is wrong' expect(ret).toEqual({ meta: { dataAccessMeta: { transactionsStorageLocation: ['fakeDataId1', 'fakeDataId2'], }, ignoredTransactions: [ { reason: 'Impossible to decrypt the channel key from this transaction ()', transaction: { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: encryptedTx, }, }, { reason: 'as first transaction, the hash of the transaction do not match the channelId', transaction: { state: TransactionTypes.TransactionState.PENDING, timestamp: 2, transaction: { data: data2 }, }, }, ], }, result: { transactions: [null, null], }, }); }); it('can get two transactions first clear and second encrypted', async () => { const encryptedTx = await TransactionsFactory.createEncryptedTransactionInNewChannel(data2, [ TestData.idRaw1.encryptionParams, TestData.idRaw2.encryptionParams, ]); const fakeMetaDataAccessGetReturnWithEncryptedTransaction: DataAccessTypes.IReturnGetTransactions = { meta: { transactionsStorageLocation: ['fakeDataId1', 'fakeDataId2'], }, result: { transactions: [ { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: { data }, }, { state: TransactionTypes.TransactionState.PENDING, timestamp: 2, transaction: encryptedTx, }, ], }, }; fakeDataAccess = { _getStatus: jest.fn(), getChannelsByMultipleTopics: jest.fn(), getChannelsByTopic: jest.fn(), getTransactionsByChannelId: jest .fn() .mockReturnValue(fakeMetaDataAccessGetReturnWithEncryptedTransaction), initialize: jest.fn(), persistTransaction: jest.fn(), }; const transactionManager = new TransactionManager( fakeDataAccess, TestData.fakeDecryptionProvider, ); const ret = await transactionManager.getTransactionsByChannelId(channelId); // 'return is wrong' expect(ret).toEqual({ meta: { dataAccessMeta: { transactionsStorageLocation: ['fakeDataId1', 'fakeDataId2'], }, ignoredTransactions: [ null, { reason: 'Encrypted transactions are not allowed in clear channel', transaction: { state: TransactionTypes.TransactionState.PENDING, timestamp: 2, transaction: encryptedTx, }, }, ], }, result: { transactions: [ { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: { data }, }, null, ], }, }); }); }); describe('getChannelsByTopic', () => { it('can get channels indexed by topics', async () => { const transactionManager = new TransactionManager(fakeDataAccess); const ret = await transactionManager.getChannelsByTopic(extraTopics[0]); // 'ret.result is wrong' expect(ret.result).toEqual(fakeMetaDataAccessGetChannelsReturn.result); // 'ret.meta is wrong' expect(ret.meta).toEqual({ dataAccessMeta: fakeMetaDataAccessGetChannelsReturn.meta, ignoredTransactions: { '01a98f126de3fab2b5130af5161998bf6e59b2c380deafeff938ff3f798281bf23': [null, null], }, }); expect(fakeDataAccess.getChannelsByTopic).toHaveBeenCalledWith(extraTopics[0], undefined); }); it('can get an encrypted channel indexed by topic', async () => { const encryptedTx = await TransactionsFactory.createEncryptedTransactionInNewChannel(data, [ TestData.idRaw1.encryptionParams, TestData.idRaw2.encryptionParams, TestData.idRaw3.encryptionParams, ]); const fakeMetaDataAccessGetReturnWithEncryptedTransaction: DataAccessTypes.IReturnGetChannelsByTopic = { meta: { transactionsStorageLocation: { [channelId]: ['fakeDataId1'], }, }, result: { transactions: { [channelId]: [ { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: encryptedTx, }, ], }, }, }; fakeDataAccess = { _getStatus: jest.fn(), getChannelsByMultipleTopics: jest.fn(), getChannelsByTopic: jest .fn() .mockReturnValue(fakeMetaDataAccessGetReturnWithEncryptedTransaction), getTransactionsByChannelId: jest.fn(), initialize: jest.fn(), persistTransaction: jest.fn(), }; const transactionManager = new TransactionManager( fakeDataAccess, TestData.fakeDecryptionProvider, ); const ret = await transactionManager.getChannelsByTopic(extraTopics[0]); // 'ret.result is wrong' expect(ret.result).toEqual({ transactions: { [channelId]: [tx], }, }); // 'ret.meta is wrong' expect(ret.meta).toEqual({ dataAccessMeta: fakeMetaDataAccessGetReturnWithEncryptedTransaction.meta, ignoredTransactions: { [channelId]: [null], }, }); expect(fakeDataAccess.getChannelsByTopic).toHaveBeenCalledWith(extraTopics[0], undefined); }); it('cannot get an encrypted channel indexed by topic without decryptionProvider', async () => { const encryptedTx = await TransactionsFactory.createEncryptedTransactionInNewChannel(data, [ TestData.idRaw1.encryptionParams, TestData.idRaw2.encryptionParams, TestData.idRaw3.encryptionParams, ]); const fakeMetaDataAccessGetReturnWithEncryptedTransaction: DataAccessTypes.IReturnGetChannelsByTopic = { meta: { transactionsStorageLocation: { [channelId]: ['fakeDataId1'], }, }, result: { transactions: { [channelId]: [ { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: encryptedTx, }, ], }, }, }; fakeDataAccess = { _getStatus: jest.fn(), getChannelsByMultipleTopics: jest.fn(), getChannelsByTopic: jest .fn() .mockReturnValue(fakeMetaDataAccessGetReturnWithEncryptedTransaction), getTransactionsByChannelId: jest.fn(), initialize: jest.fn(), persistTransaction: jest.fn(), }; const transactionManager = new TransactionManager(fakeDataAccess); const ret = await transactionManager.getChannelsByTopic(extraTopics[0]); // 'ret.result is wrong' expect(ret.result).toEqual({ transactions: { [channelId]: [null], }, }); // 'ret.meta is wrong' expect(ret.meta).toEqual({ dataAccessMeta: fakeMetaDataAccessGetReturnWithEncryptedTransaction.meta, ignoredTransactions: { [channelId]: [ { reason: 'No decryption provider given', transaction: { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: encryptedTx, }, }, ], }, }); expect(fakeDataAccess.getChannelsByTopic).toHaveBeenCalledWith(extraTopics[0], undefined); }); it('can get an clear channel indexed by topic without decryptionProvider even if an encrypted transaction happen first', async () => { const encryptedTx = await TransactionsFactory.createEncryptedTransactionInNewChannel(data, [ TestData.idRaw1.encryptionParams, TestData.idRaw2.encryptionParams, TestData.idRaw3.encryptionParams, ]); const fakeMetaDataAccessGetReturnWithEncryptedTransaction: DataAccessTypes.IReturnGetChannelsByTopic = { meta: { transactionsStorageLocation: { [channelId]: ['fakeDataId1', 'fakeDataId2'], }, }, result: { transactions: { [channelId]: [ { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: encryptedTx, }, { state: TransactionTypes.TransactionState.PENDING, timestamp: 2, transaction: { data }, }, ], }, }, }; fakeDataAccess = { _getStatus: jest.fn(), getChannelsByMultipleTopics: jest.fn(), getChannelsByTopic: jest .fn() .mockReturnValue(fakeMetaDataAccessGetReturnWithEncryptedTransaction), getTransactionsByChannelId: jest.fn(), initialize: jest.fn(), persistTransaction: jest.fn(), }; const transactionManager = new TransactionManager(fakeDataAccess); const ret = await transactionManager.getChannelsByTopic(extraTopics[0]); // 'ret.result is wrong' expect(ret.result).toEqual({ transactions: { [channelId]: [ null, { state: TransactionTypes.TransactionState.PENDING, timestamp: 2, transaction: { data }, }, ], }, }); // 'ret.meta is wrong' expect(ret.meta).toEqual({ dataAccessMeta: fakeMetaDataAccessGetReturnWithEncryptedTransaction.meta, ignoredTransactions: { [channelId]: [ { reason: 'No decryption provider given', transaction: { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: encryptedTx, }, }, null, ], }, }); expect(fakeDataAccess.getChannelsByTopic).toHaveBeenCalledWith(extraTopics[0], undefined); }); it('can get channels indexed by topics with channelId not matching the first transaction hash', async () => { const txWrongHash: DataAccessTypes.ITimestampedTransaction = { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: { data: '{"wrong": "hash"}' }, }; const fakeMetaDataAccessGetReturnFirstHashWrong: DataAccessTypes.IReturnGetChannelsByTopic = { meta: { transactionsStorageLocation: { [channelId]: ['fakeDataId1', 'fakeDataId1', 'fakeDataId2'], }, }, result: { transactions: { [channelId]: [txWrongHash, tx, tx2] } }, }; fakeDataAccess = { _getStatus: jest.fn(), getChannelsByMultipleTopics: jest.fn(), getChannelsByTopic: jest.fn().mockReturnValue(fakeMetaDataAccessGetReturnFirstHashWrong), getTransactionsByChannelId: jest.fn(), initialize: jest.fn(), persistTransaction: jest.fn(), }; const transactionManager = new TransactionManager(fakeDataAccess); const ret = await transactionManager.getChannelsByTopic(extraTopics[0]); // 'ret.result is wrong' expect(ret.result).toEqual({ transactions: { [channelId]: [null, tx, tx2] }, }); // 'ret.meta is wrong' expect(ret.meta).toEqual({ dataAccessMeta: fakeMetaDataAccessGetReturnFirstHashWrong.meta, ignoredTransactions: { [channelId]: [ { reason: 'as first transaction, the hash of the transaction do not match the channelId', transaction: txWrongHash, }, null, null, ], }, }); expect(fakeDataAccess.getChannelsByTopic).toHaveBeenCalledWith(extraTopics[0], undefined); }); it('can get channels encrypted and clear', async () => { const encryptedTx = await TransactionsFactory.createEncryptedTransactionInNewChannel(data, [ TestData.idRaw1.encryptionParams, TestData.idRaw2.encryptionParams, TestData.idRaw3.encryptionParams, ]); const fakeMetaDataAccessGetReturnWithEncryptedTransaction: DataAccessTypes.IReturnGetChannelsByTopic = { meta: { transactionsStorageLocation: { [channelId]: ['fakeDataId1'], [channelId2]: ['fakeDataId2'], }, }, result: { transactions: { [channelId]: [ { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: encryptedTx, }, ], [channelId2]: [ { state: TransactionTypes.TransactionState.PENDING, timestamp: 1, transaction: { data: data2 }, }, ], }, }, }; fakeDataAccess = { _getStatus: jest.fn(), getChannelsByMultipleTopics: jest.fn(), getChannelsByTopic: jest .fn() .mockReturnValue(fakeMetaDataAccessGetReturnWithEncryptedTransaction), getTransactionsByChannelId: jest.fn(), initialize: jest.fn(), persistTransaction: jest.fn(), }; const transactionManager = new TransactionManager( fakeDataAccess, TestData.fakeDecryptionProvider, ); const ret = await transactionManager.getChannelsByTopic(extraTopics[0]); // 'ret.result is wrong' expect(ret.result).toEqual({ transactions: { [channelId]: [tx], [channelId2]: [tx2], }, }); // 'ret.meta is wrong' expect(ret.meta).toEqual({ dataAccessMeta: fakeMetaDataAccessGetReturnWithEncryptedTransaction.meta, ignoredTransactions: { [channelId]: [null], [channelId2]: [null], }, }); expect(fakeDataAccess.getChannelsByTopic).toHaveBeenCalledWith(extraTopics[0], undefined); }); }); describe('getChannelsByMultipleTopic', () => { it('can get channels indexed by topics', async () => { const transactionManager = new TransactionManager(fakeDataAccess); const ret = await transactionManager.getChannelsByMultipleTopics([extraTopics[0]]); // 'ret.result is wrong' expect(ret.result).toEqual(fakeMetaDataAccessGetChannelsReturn.result); // 'ret.meta is wrong' expect(ret.meta).toEqual({ dataAccessMeta: fakeMetaDataAccessGetChannelsReturn.meta, ignoredTransactions: { '01a98f126de3fab2b5130af5161998bf6e59b2c380deafeff938ff3f798281bf23': [null, null], }, }); // eslint-disable-next-line @typescript-eslint/unbound-method expect(fakeDataAccess.getChannelsByMultipleTopics).toHaveBeenCalledWith( [extraTopics[0]], undefined, ); }); }); });
the_stack
declare namespace Proto { export interface webviewView { log?: string; resources?: webviewResource[]; /** * We used to have a setting that allowed users to dynamically * prepend timestamps in logs. */ DEPRECATEDLogTimestamps?: boolean; featureFlags?: object; needsAnalyticsNudge?: boolean; runningTiltBuild?: webviewTiltBuild; DEPRECATEDLatestTiltBuild?: webviewTiltBuild; suggestedTiltVersion?: string; versionSettings?: webviewVersionSettings; tiltCloudUsername?: string; tiltCloudTeamName?: string; tiltCloudSchemeHost?: string; tiltCloudTeamID?: string; fatalError?: string; logList?: webviewLogList; /** * Allows us to synchronize on a running Tilt intance, * so we can tell when Tilt restarted. */ tiltStartTime?: string; tiltfileKey?: string; /** * New API-server based data models. */ uiSession?: v1alpha1UISession; uiResources?: v1alpha1UIResource[]; uiButtons?: v1alpha1UIButton[]; /** * indicates that this view is a complete representation of the app * if false, this view just contains deltas from a previous view. */ isComplete?: boolean; } export interface webviewVersionSettings { checkUpdates?: boolean; } export interface webviewUploadSnapshotResponse { url?: string; } export interface webviewTiltBuild { version?: string; commitSHA?: string; date?: string; dev?: boolean; } export interface webviewTargetSpec { id?: string; type?: string; hasLiveUpdate?: boolean; } export interface webviewSnapshotHighlight { beginningLogID?: string; endingLogID?: string; text?: string; } export interface webviewSnapshot { view?: webviewView; isSidebarClosed?: boolean; path?: string; snapshotHighlight?: webviewSnapshotHighlight; snapshotLink?: string; } export interface webviewResource { name?: string; lastDeployTime?: string; triggerMode?: number; buildHistory?: webviewBuildRecord[]; currentBuild?: webviewBuildRecord; pendingBuildSince?: string; hasPendingChanges?: boolean; endpointLinks?: webviewLink[]; podID?: string; k8sResourceInfo?: webviewK8sResourceInfo; localResourceInfo?: webviewLocalResourceInfo; runtimeStatus?: string; updateStatus?: string; isTiltfile?: boolean; specs?: webviewTargetSpec[]; queued?: boolean; } export interface webviewLogSpan { manifestName?: string; } export interface webviewLogSegment { spanId?: string; time?: string; text?: string; level?: string; /** * When we store warnings in the LogStore, we break them up into lines and * store them as a series of line segments. 'anchor' marks the beginning of a * series of logs that should be kept together. * * Anchor warning1, line1 * warning1, line2 * Anchor warning2, line1 */ anchor?: boolean; /** * Context-specific optional fields for a log segment. * Used for experimenting with new types of log metadata. */ fields?: object; } export interface webviewLogList { spans?: object; segments?: webviewLogSegment[]; /** * [from_checkpoint, to_checkpoint) * * An interval of [0, 0) means that the server isn't using * the incremental load protocol. * * An interval of [-1, -1) means that the server doesn't have new logs * to send down. */ fromCheckpoint?: number; toCheckpoint?: number; } export interface webviewLocalResourceInfo { pid?: string; isTest?: boolean; } export interface webviewLink { url?: string; name?: string; } export interface webviewK8sResourceInfo { podName?: string; podCreationTime?: string; podUpdateStartTime?: string; podStatus?: string; podStatusMessage?: string; allContainersReady?: boolean; podRestarts?: number; spanId?: string; displayNames?: string[]; } export interface webviewBuildRecord { error?: string; warnings?: string[]; startTime?: string; finishTime?: string; isCrashRebuild?: boolean; /** * The span id for this build record's logs in the main logstore. */ spanId?: string; } export interface webviewAckWebsocketResponse {} export interface webviewAckWebsocketRequest { toCheckpoint?: number; /** * Allows us to synchronize on a running Tilt intance, * so we can tell when we're talking to the same Tilt. */ tiltStartTime?: string; } export interface v1Time { /** * Represents seconds of UTC time since Unix epoch * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to * 9999-12-31T23:59:59Z inclusive. */ seconds?: string; /** * Non-negative fractions of a second at nanosecond resolution. Negative * second values with fractions must still have non-negative nanos values * that count forward in time. Must be from 0 to 999,999,999 * inclusive. This field may be limited in precision depending on context. */ nanos?: number; } export interface v1OwnerReference { /** * API version of the referent. */ apiVersion?: string; kind?: string; name?: string; uid?: string; controller?: boolean; blockOwnerDeletion?: boolean; } export interface v1ObjectMeta { name?: string; /** * GenerateName is an optional prefix, used by the server, to generate a unique * name ONLY IF the Name field has not been provided. * If this field is used, the name returned to the client will be different * than the name passed. This value will also be combined with a unique suffix. * The provided value has the same validation rules as the Name field, * and may be truncated by the length of the suffix required to make the value * unique on the server. * * If this field is specified and the generated name exists, the server will * NOT return a 409 - instead, it will either return 201 Created or 500 with Reason * ServerTimeout indicating a unique name could not be found in the time allotted, and the client * should retry (optionally after the time indicated in the Retry-After header). * * Applied only if Name is not specified. * More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency * +optional */ generateName?: string; /** * Namespace defines the space within which each name must be unique. An empty namespace is * equivalent to the "default" namespace, but "default" is the canonical representation. * Not all objects are required to be scoped to a namespace - the value of this field for * those objects will be empty. * * Must be a DNS_LABEL. * Cannot be updated. * More info: http://kubernetes.io/docs/user-guide/namespaces * +optional */ namespace?: string; /** * SelfLink is a URL representing this object. * Populated by the system. * Read-only. * * DEPRECATED * Kubernetes will stop propagating this field in 1.20 release and the field is planned * to be removed in 1.21 release. * +optional */ selfLink?: string; /** * UID is the unique in time and space value for this object. It is typically generated by * the server on successful creation of a resource and is not allowed to change on PUT * operations. * * Populated by the system. * Read-only. * More info: http://kubernetes.io/docs/user-guide/identifiers#uids * +optional */ uid?: string; /** * An opaque value that represents the internal version of this object that can * be used by clients to determine when objects have changed. May be used for optimistic * concurrency, change detection, and the watch operation on a resource or set of resources. * Clients must treat these values as opaque and passed unmodified back to the server. * They may only be valid for a particular resource or set of resources. * * Populated by the system. * Read-only. * Value must be treated as opaque by clients and . * More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency * +optional */ resourceVersion?: string; generation?: string; /** * CreationTimestamp is a timestamp representing the server time when this object was * created. It is not guaranteed to be set in happens-before order across separate operations. * Clients may not set this value. It is represented in RFC3339 form and is in UTC. * * Populated by the system. * Read-only. * Null for lists. * More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata * +optional */ creationTimestamp?: string; /** * DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This * field is set by the server when a graceful deletion is requested by the user, and is not * directly settable by a client. The resource is expected to be deleted (no longer visible * from resource lists, and not reachable by name) after the time in this field, once the * finalizers list is empty. As long as the finalizers list contains items, deletion is blocked. * Once the deletionTimestamp is set, this value may not be unset or be set further into the * future, although it may be shortened or the resource may be deleted prior to this time. * For example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react * by sending a graceful termination signal to the containers in the pod. After that 30 seconds, * the Kubelet will send a hard termination signal (SIGKILL) to the container and after cleanup, * remove the pod from the API. In the presence of network partitions, this object may still * exist after this timestamp, until an administrator or automated process can determine the * resource is fully terminated. * If not set, graceful deletion of the object has not been requested. * * Populated by the system when a graceful deletion is requested. * Read-only. * More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata * +optional */ deletionTimestamp?: string; deletionGracePeriodSeconds?: string; labels?: object; annotations?: object; ownerReferences?: v1OwnerReference[]; finalizers?: string[]; clusterName?: string; /** * ManagedFields maps workflow-id and version to the set of fields * that are managed by that workflow. This is mostly for internal * housekeeping, and users typically shouldn't need to set or * understand this field. A workflow can be the user's name, a * controller's name, or the name of a specific apply path like * "ci-cd". The set of fields is always in the version that the * workflow used when modifying the object. * * +optional */ managedFields?: v1ManagedFieldsEntry[]; } export interface v1MicroTime { /** * Represents seconds of UTC time since Unix epoch * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to * 9999-12-31T23:59:59Z inclusive. */ seconds?: string; /** * Non-negative fractions of a second at nanosecond resolution. Negative * second values with fractions must still have non-negative nanos values * that count forward in time. Must be from 0 to 999,999,999 * inclusive. This field may be limited in precision depending on context. */ nanos?: number; } export interface v1ManagedFieldsEntry { /** * Manager is an identifier of the workflow managing these fields. */ manager?: string; /** * Operation is the type of operation which lead to this ManagedFieldsEntry being created. * The only valid values for this field are 'Apply' and 'Update'. */ operation?: string; /** * APIVersion defines the version of this resource that this field set * applies to. The format is "group/version" just like the top-level * APIVersion field. It is necessary to track the version of a field * set because it cannot be automatically converted. */ apiVersion?: string; time?: string; fieldsType?: string; fieldsV1?: v1FieldsV1; /** * Subresource is the name of the subresource used to update that object, or * empty string if the object was updated through the main resource. The * value of this field is used to distinguish between managers, even if they * share the same name. For example, a status update will be distinct from a * regular update using the same manager name. * Note that the APIVersion field is not related to the Subresource field and * it always corresponds to the version of the main resource. */ subresource?: string; } export interface v1FieldsV1 { /** * Raw is the underlying serialization of this object. */ Raw?: string; } export interface v1alpha1UITextInputStatus { /** * The content of the text input. */ value?: string; } export interface v1alpha1UITextInputSpec { /** * Initial value for this field. * * +optional */ defaultValue?: string; /** * A short hint that describes the expected input of this field. * * +optional */ placeholder?: string; } export interface v1alpha1UISessionStatus { featureFlags?: v1alpha1UIFeatureFlag[]; needsAnalyticsNudge?: boolean; runningTiltBuild?: corev1alpha1TiltBuild; suggestedTiltVersion?: string; versionSettings?: corev1alpha1VersionSettings; tiltCloudUsername?: string; tiltCloudTeamName?: string; tiltCloudSchemeHost?: string; tiltCloudTeamID?: string; fatalError?: string; tiltStartTime?: string; tiltfileKey?: string; } export interface v1alpha1UISessionSpec {} export interface v1alpha1UISession { metadata?: v1ObjectMeta; spec?: v1alpha1UISessionSpec; status?: v1alpha1UISessionStatus; } export interface v1alpha1UIResourceTargetSpec { id?: string; type?: string; hasLiveUpdate?: boolean; } export interface v1alpha1UIResourceStatus { lastDeployTime?: string; triggerMode?: number; buildHistory?: v1alpha1UIBuildTerminated[]; currentBuild?: v1alpha1UIBuildRunning; pendingBuildSince?: string; hasPendingChanges?: boolean; endpointLinks?: v1alpha1UIResourceLink[]; k8sResourceInfo?: v1alpha1UIResourceKubernetes; localResourceInfo?: v1alpha1UIResourceLocal; /** * The RuntimeStatus is a simple, high-level summary of the runtime state of a server. * * Not all resources run servers. * +optional */ runtimeStatus?: string; /** * The UpdateStatus is a simple, high-level summary of any update tasks to bring * the resource up-to-date. * * If the resource runs a server, this may include both build tasks and live-update * syncing. * +optional */ updateStatus?: string; specs?: v1alpha1UIResourceTargetSpec[]; queued?: boolean; /** * Order expresses the relative order of resources in the UI when they're not * otherwise sorted. Lower integers go first. When two resources have the same * order, they should be sorted by name. * * When UIResources are generated from the Tiltfile, we use the order they * were added to the Tiltfile for the Order field. * * +optional */ order?: number; /** * Information about the resource's objects' disabled status. */ disableStatus?: v1alpha1DisableResourceStatus; /** * Waiting provides detail on why the resource is currently blocked from updating. * * +optional */ waiting?: v1alpha1UIResourceStateWaiting; /** * Represents the latest available observations of a UIResource's current state. * * Designed for compatibility with 'wait' and cross-resource status reporting. * https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#typical-status-properties * * +optional */ conditions?: v1alpha1UIResourceCondition[]; } export interface v1alpha1UIResourceStateWaitingOnRef { /** * Group for the object type being waited on. */ group?: string; /** * APIVersion for the object type being waited on. */ apiVersion?: string; /** * Kind of the object type being waited on. */ kind?: string; /** * Name of the object being waiting on. */ name?: string; } export interface v1alpha1UIResourceStateWaiting { /** * Reason is a unique, one-word reason for why the UIResource update is pending. */ reason?: string; /** * HoldingOn is the set of objects blocking this resource from updating. * * These objects might NOT be explicit dependencies of the current resource. For example, if an un-parallelizable * resource is updating, all other resources with queued updates will be holding on it with a reason of * `waiting-for-local`. * * +optional */ on?: v1alpha1UIResourceStateWaitingOnRef[]; } export interface v1alpha1UIResourceSpec {} export interface v1alpha1UIResourceLocal { pid?: string; isTest?: boolean; } export interface v1alpha1UIResourceLink { url?: string; name?: string; } export interface v1alpha1UIResourceKubernetes { /** * The name of the active pod. * * The active pod tends to be what Tilt defaults to for port-forwards, * live-updates, etc. * +optional */ podName?: string; podCreationTime?: string; podUpdateStartTime?: string; podStatus?: string; podStatusMessage?: string; allContainersReady?: boolean; podRestarts?: number; spanID?: string; displayNames?: string[]; } export interface v1alpha1UIResourceCondition { /** * Type of UI Resource condition. */ type?: string; /** * Status of the condition, one of True, False, Unknown. */ status?: string; lastTransitionTime?: string; reason?: string; message?: string; } export interface v1alpha1UIResource { metadata?: v1ObjectMeta; spec?: v1alpha1UIResourceSpec; status?: v1alpha1UIResourceStatus; } export interface v1alpha1UIInputStatus { /** * Name of the input whose status this is. Must match the `Name` of a corresponding * UIInputSpec. */ name?: string; text?: v1alpha1UITextInputStatus; bool?: v1alpha1UIBoolInputStatus; hidden?: v1alpha1UIHiddenInputStatus; } export interface v1alpha1UIInputSpec { /** * Name of this input. Must be unique within the UIButton. */ name?: string; label?: string; text?: v1alpha1UITextInputSpec; bool?: v1alpha1UIBoolInputSpec; hidden?: v1alpha1UIHiddenInputSpec; } export interface v1alpha1UIHiddenInputStatus { value?: string; } export interface v1alpha1UIHiddenInputSpec { value?: string; } export interface v1alpha1UIFeatureFlag { name?: string; value?: boolean; } export interface v1alpha1UIComponentLocation { /** * ComponentID is the identifier of the parent component to associate this component with. * * For example, this is a resource name if the ComponentType is Resource. */ componentID?: string; /** * ComponentType is the type of the parent component. */ componentType?: string; } export interface v1alpha1UIButtonStatus { /** * LastClickedAt is the timestamp of the last time the button was clicked. * * If the button has never clicked before, this will be the zero-value/null. */ lastClickedAt?: string; inputs?: v1alpha1UIInputStatus[]; } export interface v1alpha1UIButtonSpec { /** * Location associates the button with another component for layout. */ location?: v1alpha1UIComponentLocation; /** * Text to appear on the button itself or as hover text (depending on button location). */ text?: string; /** * IconName is a Material Icon to appear next to button text or on the button itself (depending on button location). * * Valid values are icon font ligature names from the Material Icons set. * See https://fonts.google.com/icons for the full list of available icons. * * If both IconSVG and IconName are specified, IconSVG will take precedence. * * +optional */ iconName?: string; /** * IconSVG is an SVG to use as the icon to appear next to button text or on the button itself (depending on button * location). * * This should be an <svg> element scaled for a 24x24 viewport. * * If both IconSVG and IconName are specified, IconSVG will take precedence. * * +optional */ iconSVG?: string; /** * If true, the button will be rendered, but with an effect indicating it's * disabled. It will also be unclickable. * * +optional */ disabled?: boolean; /** * +optional */ requiresConfirmation?: boolean; inputs?: v1alpha1UIInputSpec[]; } export interface v1alpha1UIButton { metadata?: v1ObjectMeta; spec?: v1alpha1UIButtonSpec; status?: v1alpha1UIButtonStatus; } export interface v1alpha1UIBuildTerminated { error?: string; warnings?: string[]; startTime?: string; finishTime?: string; spanID?: string; isCrashRebuild?: boolean; } export interface v1alpha1UIBuildRunning { startTime?: string; spanID?: string; } export interface v1alpha1UIBoolInputStatus { value?: boolean; } export interface v1alpha1UIBoolInputSpec { defaultValue?: boolean; trueString?: string; falseString?: string; } export interface v1alpha1DisableSource { configMap?: v1alpha1ConfigMapDisableSource; } export interface v1alpha1DisableResourceStatus { /** * How many of the resource's sources are enabled. */ enabledCount?: number; /** * How many of the resource's sources are disabled. */ disabledCount?: number; /** * All unique sources that control the resource's objects' disable status. */ sources?: v1alpha1DisableSource[]; } export interface v1alpha1ConfigMapDisableSource { name?: string; /** * The key where the enable/disable state is stored. */ key?: string; } export interface runtimeError { error?: string; code?: number; message?: string; details?: protobufAny[]; } export interface protobufAny { typeUrl?: string; value?: string; } export interface corev1alpha1VersionSettings { checkUpdates?: boolean; } export interface corev1alpha1TiltBuild { version?: string; commitSHA?: string; date?: string; dev?: boolean; } }
the_stack
import { IDataObject, INodeExecutionData } from 'n8n-workflow'; import pgPromise = require('pg-promise'); import pg = require('pg-promise/typescript/pg-subset'); /** * Returns of a shallow copy of the items which only contains the json data and * of that only the define properties * * @param {INodeExecutionData[]} items The items to copy * @param {string[]} properties The properties it should include * @returns */ export function getItemsCopy(items: INodeExecutionData[], properties: string[]): IDataObject[] { let newItem: IDataObject; return items.map(item => { newItem = {}; for (const property of properties) { newItem[property] = item.json[property]; } return newItem; }); } /** * Returns of a shallow copy of the item which only contains the json data and * of that only the define properties * * @param {INodeExecutionData} item The item to copy * @param {string[]} properties The properties it should include * @returns */ export function getItemCopy(item: INodeExecutionData, properties: string[]): IDataObject { const newItem: IDataObject = {}; for (const property of properties) { newItem[property] = item.json[property]; } return newItem; } /** * Returns a returning clause from a comma separated string * @param {pgPromise.IMain<{}, pg.IClient>} pgp The pgPromise instance * @param string returning The comma separated string * @returns string */ export function generateReturning(pgp: pgPromise.IMain<{}, pg.IClient>, returning: string): string { return ' RETURNING ' + returning.split(',').map(returnedField => pgp.as.name(returnedField.trim())).join(', '); } /** * Executes the given SQL query on the database. * * @param {Function} getNodeParam The getter for the Node's parameters * @param {pgPromise.IMain<{}, pg.IClient>} pgp The pgPromise instance * @param {pgPromise.IDatabase<{}, pg.IClient>} db The pgPromise database connection * @param {input[]} input The Node's input data * @returns Promise<Array<IDataObject>> */ export async function pgQuery( getNodeParam: Function, pgp: pgPromise.IMain<{}, pg.IClient>, db: pgPromise.IDatabase<{}, pg.IClient>, items: INodeExecutionData[], continueOnFail: boolean, overrideMode?: string, ): Promise<IDataObject[]> { const additionalFields = getNodeParam('additionalFields', 0) as IDataObject; let valuesArray = [] as string[][]; if (additionalFields.queryParams) { const propertiesString = additionalFields.queryParams as string; const properties = propertiesString.split(',').map(column => column.trim()); const paramsItems = getItemsCopy(items, properties); valuesArray = paramsItems.map((row) => properties.map(col => row[col])) as string[][]; } const allQueries = [] as Array<{query: string, values?: string[]}>; for (let i = 0; i < items.length; i++) { const query = getNodeParam('query', i) as string; const values = valuesArray[i]; const queryFormat = { query, values }; allQueries.push(queryFormat); } const mode = overrideMode ? overrideMode : (additionalFields.mode ?? 'multiple') as string; if (mode === 'multiple') { return (await db.multi(pgp.helpers.concat(allQueries))).flat(1); } else if (mode === 'transaction') { return db.tx(async t => { const result: IDataObject[] = []; for (let i = 0; i < allQueries.length; i++) { try { Array.prototype.push.apply(result, await t.any(allQueries[i].query, allQueries[i].values)); } catch (err) { if (continueOnFail === false) throw err; result.push({ ...items[i].json, code: err.code, message: err.message }); return result; } } return result; }); } else if (mode === 'independently') { return db.task(async t => { const result: IDataObject[] = []; for (let i = 0; i < allQueries.length; i++) { try { Array.prototype.push.apply(result, await t.any(allQueries[i].query, allQueries[i].values)); } catch (err) { if (continueOnFail === false) throw err; result.push({ ...items[i].json, code: err.code, message: err.message }); } } return result; }); } throw new Error('multiple, independently or transaction are valid options'); } /** * Inserts the given items into the database. * * @param {Function} getNodeParam The getter for the Node's parameters * @param {pgPromise.IMain<{}, pg.IClient>} pgp The pgPromise instance * @param {pgPromise.IDatabase<{}, pg.IClient>} db The pgPromise database connection * @param {INodeExecutionData[]} items The items to be inserted * @returns Promise<Array<IDataObject>> */ export async function pgInsert( getNodeParam: Function, pgp: pgPromise.IMain<{}, pg.IClient>, db: pgPromise.IDatabase<{}, pg.IClient>, items: INodeExecutionData[], continueOnFail: boolean, overrideMode?: string, ): Promise<IDataObject[]> { const table = getNodeParam('table', 0) as string; const schema = getNodeParam('schema', 0) as string; const columnString = getNodeParam('columns', 0) as string; const columns = columnString.split(',') .map(column => column.trim().split(':')) .map(([name, cast]) => ({ name, cast })); const columnNames = columns.map(column => column.name); const cs = new pgp.helpers.ColumnSet(columns, { table: { table, schema } }); const additionalFields = getNodeParam('additionalFields', 0) as IDataObject; const mode = overrideMode ? overrideMode : (additionalFields.mode ?? 'multiple') as string; const returning = generateReturning(pgp, getNodeParam('returnFields', 0) as string); if (mode === 'multiple') { const query = pgp.helpers.insert(getItemsCopy(items, columnNames), cs) + returning; return db.any(query); } else if (mode === 'transaction') { return db.tx(async t => { const result: IDataObject[] = []; for (let i = 0; i < items.length; i++) { const itemCopy = getItemCopy(items[i], columnNames); try { result.push(await t.one(pgp.helpers.insert(itemCopy, cs) + returning)); } catch (err) { if (continueOnFail === false) throw err; result.push({ ...itemCopy, code: err.code, message: err.message }); return result; } } return result; }); } else if (mode === 'independently') { return db.task(async t => { const result: IDataObject[] = []; for (let i = 0; i < items.length; i++) { const itemCopy = getItemCopy(items[i], columnNames); try { const insertResult = await t.oneOrNone(pgp.helpers.insert(itemCopy, cs) + returning); if (insertResult !== null) { result.push(insertResult); } } catch (err) { if (continueOnFail === false) { throw err; } result.push({ ...itemCopy, code: err.code, message: err.message }); } } return result; }); } throw new Error('multiple, independently or transaction are valid options'); } /** * Updates the given items in the database. * * @param {Function} getNodeParam The getter for the Node's parameters * @param {pgPromise.IMain<{}, pg.IClient>} pgp The pgPromise instance * @param {pgPromise.IDatabase<{}, pg.IClient>} db The pgPromise database connection * @param {INodeExecutionData[]} items The items to be updated * @returns Promise<Array<IDataObject>> */ export async function pgUpdate( getNodeParam: Function, pgp: pgPromise.IMain<{}, pg.IClient>, db: pgPromise.IDatabase<{}, pg.IClient>, items: INodeExecutionData[], continueOnFail = false, ): Promise<IDataObject[]> { const table = getNodeParam('table', 0) as string; const schema = getNodeParam('schema', 0) as string; const updateKey = getNodeParam('updateKey', 0) as string; const columnString = getNodeParam('columns', 0) as string; const columns = columnString.split(',') .map(column => column.trim().split(':')) .map(([name, cast]) => ({ name, cast })); const updateKeys = updateKey.split(',').map(key => { const [name, cast] = key.trim().split(':'); const updateColumn = { name, cast }; const targetCol = columns.find((column) => column.name === name); if (!targetCol) { columns.unshift(updateColumn); } else if (!targetCol.cast) { targetCol.cast = updateColumn.cast || targetCol.cast; } return updateColumn; }); const additionalFields = getNodeParam('additionalFields', 0) as IDataObject; const mode = additionalFields.mode ?? 'multiple' as string; const cs = new pgp.helpers.ColumnSet(columns, { table: { table, schema } }); // Prepare the data to update and copy it to be returned const columnNames = columns.map(column => column.name); const updateItems = getItemsCopy(items, columnNames); const returning = generateReturning(pgp, getNodeParam('returnFields', 0) as string); if (mode === 'multiple') { const query = pgp.helpers.update(updateItems, cs) + ' WHERE ' + updateKeys.map(updateKey => { const key = pgp.as.name(updateKey.name); return 'v.' + key + ' = t.' + key; }).join(' AND ') + returning; return await db.any(query); } else { const where = ' WHERE ' + updateKeys.map(updateKey => pgp.as.name(updateKey.name) + ' = ${' + updateKey.name + '}').join(' AND '); if (mode === 'transaction') { return db.tx(async t => { const result: IDataObject[] = []; for (let i = 0; i < items.length; i++) { const itemCopy = getItemCopy(items[i], columnNames); try { Array.prototype.push.apply(result, await t.any(pgp.helpers.update(itemCopy, cs) + pgp.as.format(where, itemCopy) + returning)); } catch (err) { if (continueOnFail === false) throw err; result.push({ ...itemCopy, code: err.code, message: err.message }); return result; } } return result; }); } else if (mode === 'independently') { return db.task(async t => { const result: IDataObject[] = []; for (let i = 0; i < items.length; i++) { const itemCopy = getItemCopy(items[i], columnNames); try { Array.prototype.push.apply(result, await t.any(pgp.helpers.update(itemCopy, cs) + pgp.as.format(where, itemCopy) + returning)); } catch (err) { if (continueOnFail === false) throw err; result.push({ ...itemCopy, code: err.code, message: err.message }); } } return result; }); } } throw new Error('multiple, independently or transaction are valid options'); }
the_stack
import * as fs from 'fs'; import * as path from 'path'; import * as iam from '@aws-cdk/aws-iam'; import * as sfn from '@aws-cdk/aws-stepfunctions'; import { Token } from '@aws-cdk/core'; import { RequestContext } from '.'; import { IntegrationConfig, IntegrationOptions, PassthroughBehavior } from '../integration'; import { Method } from '../method'; import { Model } from '../model'; import { AwsIntegration } from './aws'; /** * Options when configuring Step Functions synchronous integration with Rest API */ export interface StepFunctionsExecutionIntegrationOptions extends IntegrationOptions { /** * Which details of the incoming request must be passed onto the underlying state machine, * such as, account id, user identity, request id, etc. The execution input will include a new key `requestContext`: * * { * "body": {}, * "requestContext": { * "key": "value" * } * } * * @default - all parameters within request context will be set as false */ readonly requestContext?: RequestContext; /** * Check if querystring is to be included inside the execution input. The execution input will include a new key `queryString`: * * { * "body": {}, * "querystring": { * "key": "value" * } * } * * @default true */ readonly querystring?: boolean; /** * Check if path is to be included inside the execution input. The execution input will include a new key `path`: * * { * "body": {}, * "path": { * "resourceName": "resourceValue" * } * } * * @default true */ readonly path?: boolean; /** * Check if header is to be included inside the execution input. The execution input will include a new key `headers`: * * { * "body": {}, * "headers": { * "header1": "value", * "header2": "value" * } * } * @default false */ readonly headers?: boolean; /** * If the whole authorizer object, including custom context values should be in the execution input. The execution input will include a new key `authorizer`: * * { * "body": {}, * "authorizer": { * "key": "value" * } * } * * @default false */ readonly authorizer?: boolean; } /** * Options to integrate with various StepFunction API */ export class StepFunctionsIntegration { /** * Integrates a Synchronous Express State Machine from AWS Step Functions to an API Gateway method. * * @example * * const stateMachine = new stepfunctions.StateMachine(this, 'MyStateMachine', { * stateMachineType: stepfunctions.StateMachineType.EXPRESS, * definition: stepfunctions.Chain.start(new stepfunctions.Pass(this, 'Pass')), * }); * * const api = new apigateway.RestApi(this, 'Api', { * restApiName: 'MyApi', * }); * api.root.addMethod('GET', apigateway.StepFunctionsIntegration.startExecution(stateMachine)); */ public static startExecution(stateMachine: sfn.IStateMachine, options?: StepFunctionsExecutionIntegrationOptions): AwsIntegration { return new StepFunctionsExecutionIntegration(stateMachine, options); } } class StepFunctionsExecutionIntegration extends AwsIntegration { private readonly stateMachine: sfn.IStateMachine; constructor(stateMachine: sfn.IStateMachine, options: StepFunctionsExecutionIntegrationOptions = {}) { super({ service: 'states', action: 'StartSyncExecution', options: { credentialsRole: options.credentialsRole, integrationResponses: integrationResponse(), passthroughBehavior: PassthroughBehavior.NEVER, requestTemplates: requestTemplates(stateMachine, options), ...options, }, }); this.stateMachine = stateMachine; } public bind(method: Method): IntegrationConfig { const bindResult = super.bind(method); const credentialsRole = bindResult.options?.credentialsRole ?? new iam.Role(method, 'StartSyncExecutionRole', { assumedBy: new iam.ServicePrincipal('apigateway.amazonaws.com'), }); this.stateMachine.grantStartSyncExecution(credentialsRole); let stateMachineName; if (this.stateMachine instanceof sfn.StateMachine) { const stateMachineType = (this.stateMachine as sfn.StateMachine).stateMachineType; if (stateMachineType !== sfn.StateMachineType.EXPRESS) { throw new Error('State Machine must be of type "EXPRESS". Please use StateMachineType.EXPRESS as the stateMachineType'); } //if not imported, extract the name from the CFN layer to reach the //literal value if it is given (rather than a token) stateMachineName = (this.stateMachine.node.defaultChild as sfn.CfnStateMachine).stateMachineName; } else { //imported state machine stateMachineName = `StateMachine-${this.stateMachine.stack.node.addr}`; } let deploymentToken; if (stateMachineName !== undefined && !Token.isUnresolved(stateMachineName)) { deploymentToken = JSON.stringify({ stateMachineName }); } for (const methodResponse of METHOD_RESPONSES) { method.addMethodResponse(methodResponse); } return { ...bindResult, options: { ...bindResult.options, credentialsRole, }, deploymentToken, }; } } /** * Defines the integration response that passes the result on success, * or the error on failure, from the synchronous execution to the caller. * * @returns integrationResponse mapping */ function integrationResponse() { const errorResponse = [ { /** * Specifies the regular expression (regex) pattern used to choose * an integration response based on the response from the back end. * In this case it will match all '4XX' HTTP Errors */ selectionPattern: '4\\d{2}', statusCode: '400', responseTemplates: { 'application/json': `{ "error": "Bad request!" }`, }, }, { /** * Match all '5XX' HTTP Errors */ selectionPattern: '5\\d{2}', statusCode: '500', responseTemplates: { 'application/json': '"error": $input.path(\'$.error\')', }, }, ]; const integResponse = [ { statusCode: '200', responseTemplates: { /* eslint-disable */ 'application/json': [ '#set($inputRoot = $input.path(\'$\'))', '#if($input.path(\'$.status\').toString().equals("FAILED"))', '#set($context.responseOverride.status = 500)', '{', '"error": "$input.path(\'$.error\')",', '"cause": "$input.path(\'$.cause\')"', '}', '#else', '$input.path(\'$.output\')', '#end', /* eslint-enable */ ].join('\n'), }, }, ...errorResponse, ]; return integResponse; } /** * Defines the request template that will be used for the integration * @param stateMachine * @param options * @returns requestTemplate */ function requestTemplates(stateMachine: sfn.IStateMachine, options: StepFunctionsExecutionIntegrationOptions) { const templateStr = templateString(stateMachine, options); const requestTemplate: { [contentType:string] : string } = { 'application/json': templateStr, }; return requestTemplate; } /** * Reads the VTL template and returns the template string to be used * for the request template. * * @param stateMachine * @param includeRequestContext * @param options * @reutrns templateString */ function templateString( stateMachine: sfn.IStateMachine, options: StepFunctionsExecutionIntegrationOptions): string { let templateStr: string; let requestContextStr = ''; const includeHeader = options.headers?? false; const includeQueryString = options.querystring?? true; const includePath = options.path?? true; const includeAuthorizer = options.authorizer ?? false; if (options.requestContext && Object.keys(options.requestContext).length > 0) { requestContextStr = requestContext(options.requestContext); } templateStr = fs.readFileSync(path.join(__dirname, 'stepfunctions.vtl'), { encoding: 'utf-8' }); templateStr = templateStr.replace('%STATEMACHINE%', stateMachine.stateMachineArn); templateStr = templateStr.replace('%INCLUDE_HEADERS%', String(includeHeader)); templateStr = templateStr.replace('%INCLUDE_QUERYSTRING%', String(includeQueryString)); templateStr = templateStr.replace('%INCLUDE_PATH%', String(includePath)); templateStr = templateStr.replace('%INCLUDE_AUTHORIZER%', String(includeAuthorizer)); templateStr = templateStr.replace('%REQUESTCONTEXT%', requestContextStr); return templateStr; } function requestContext(requestContextObj: RequestContext | undefined): string { const context = { accountId: requestContextObj?.accountId? '$context.identity.accountId': undefined, apiId: requestContextObj?.apiId? '$context.apiId': undefined, apiKey: requestContextObj?.apiKey? '$context.identity.apiKey': undefined, authorizerPrincipalId: requestContextObj?.authorizerPrincipalId? '$context.authorizer.principalId': undefined, caller: requestContextObj?.caller? '$context.identity.caller': undefined, cognitoAuthenticationProvider: requestContextObj?.cognitoAuthenticationProvider? '$context.identity.cognitoAuthenticationProvider': undefined, cognitoAuthenticationType: requestContextObj?.cognitoAuthenticationType? '$context.identity.cognitoAuthenticationType': undefined, cognitoIdentityId: requestContextObj?.cognitoIdentityId? '$context.identity.cognitoIdentityId': undefined, cognitoIdentityPoolId: requestContextObj?.cognitoIdentityPoolId? '$context.identity.cognitoIdentityPoolId': undefined, httpMethod: requestContextObj?.httpMethod? '$context.httpMethod': undefined, stage: requestContextObj?.stage? '$context.stage': undefined, sourceIp: requestContextObj?.sourceIp? '$context.identity.sourceIp': undefined, user: requestContextObj?.user? '$context.identity.user': undefined, userAgent: requestContextObj?.userAgent? '$context.identity.userAgent': undefined, userArn: requestContextObj?.userArn? '$context.identity.userArn': undefined, requestId: requestContextObj?.requestId? '$context.requestId': undefined, resourceId: requestContextObj?.resourceId? '$context.resourceId': undefined, resourcePath: requestContextObj?.resourcePath? '$context.resourcePath': undefined, }; const contextAsString = JSON.stringify(context); // The VTL Template conflicts with double-quotes (") for strings. // Before sending to the template, we replace double-quotes (") with @@ and replace it back inside the .vtl file const doublequotes = '"'; const replaceWith = '@@'; return contextAsString.split(doublequotes).join(replaceWith); } /** * Method response model for each HTTP code response */ const METHOD_RESPONSES = [ { statusCode: '200', responseModels: { 'application/json': Model.EMPTY_MODEL, }, }, { statusCode: '400', responseModels: { 'application/json': Model.ERROR_MODEL, }, }, { statusCode: '500', responseModels: { 'application/json': Model.ERROR_MODEL, }, }, ];
the_stack
import fs from 'fs'; import path from 'path'; import url from 'url'; // @ts-ignore: html-to-react-components does not have type definitions import HtmlToJsx from 'html-to-react-components/lib/html2jsx'; import { deleteFolderRecursive, ensureDirectoryExistence, isUrlExternal, mapUrlToFilePath, } from './helpers'; import Downloader from './downloader'; import { formatJsx, replaceRootJsxElement, renameJsxElement, } from './jsx-parser'; import HtmlParser from './html-parser'; import { ComponentScope, HtmlToComponents, HtmlToComponentsSettings, } from './html-to-components'; import ResourcesFromCssExtractor from './resources-from-css'; import debug from './debug'; import type { MigrationApiType } from './migrationApi'; const DEFAULT_PAGE_INDEX_FILE = 'index.jsx'; export type PageCreatorParams = { /** * directory where pages should be created */ pagesDir: string, /** * whether the pages should be created * default: true */ isEnabled?: boolean | ((pageUrl: string) => boolean), /** * name of the page index file * default: index.jsx */ pageIndexFile?: string | ((pageUrl: string) => string), /** * migration api object * stores path to the directory containing page data */ migrationApi: MigrationApiType, staticDir: string, templatePath: string, templateDangerousHtml: string, pageUrl: string, headHtml: string, bodyHtml: string, scripts: Array<string>, inlineScripts: Array<string>, styles: Array<string>, inlineStyles: Array<string>, images: Array<string>, videos?: Array<string>, htmlTag: string, bodyTag: string, downloadAssets: boolean, htmlToComponents: boolean, htmlToComponentsSettings?: HtmlToComponentsSettings, reservedPaths?: Array<string>, allowFallbackHtml?: boolean, }; export class PageCreator { params: PageCreatorParams; downloader: Downloader; constructor(params: PageCreatorParams) { this.params = { isEnabled: true, ...params, }; this.downloader = new Downloader( this.params.pageUrl, this.params.staticDir, this.params.reservedPaths, ); } public get pageIndexFile() { return typeof this.params.pageIndexFile === 'function' ? this.params.pageIndexFile(this.params.pageUrl) : (this.params.pageIndexFile || DEFAULT_PAGE_INDEX_FILE); } public get isEnabled() { return typeof this.params.isEnabled === 'function' ? this.params.isEnabled(this.params.pageUrl) : this.params.isEnabled; } async createPage() { if (this.isEnabled) { this.createJsxPage(); } if (this.params.downloadAssets) { await this.downloadAssets(); } } private getPageFilePath(pageUrl: string, fileName?: string): string { const filePath = this.params.migrationApi.getPagePath(pageUrl); const fileName$ = fileName || this.pageIndexFile; return filePath === '/' ? fileName$ : path.join(filePath, fileName$); } getHtmlFilePath(pageUrl: string): string { return `./${this.getPageFilePath(pageUrl).replace('.jsx', '.html')}`; } mapStaticPath(assetUrl: string): string | undefined { return mapUrlToFilePath(assetUrl, this.params.staticDir); } getResourcesFromCSS(items: Array<string>): Array<string> { const resources = items .map(item => { if (this.isUrlExternal(item)) { return []; } const filePath = this.mapStaticPath(item); if (filePath !== undefined) { const content = fs.readFileSync(filePath).toString(); return ResourcesFromCssExtractor.extractResourcesFromCSS(content) .filter(cssResource => !this.isUrlExternal(cssResource)) .map(cssResource => url.resolve(item, cssResource)); } return []; }, this) // flatten resources .reduce((a, b) => a.concat(b), []); return resources; } private async downloadAssetsGroup(items: Array<string>) { await this.downloader.downloadFiles(items); } private async downloadAssets() { await this.downloadAssetsGroup(this.params.styles); const cssResources = this.getResourcesFromCSS(this.params.styles); await Promise.all( [ this.downloadAssetsGroup(this.params.images), this.downloadAssetsGroup(this.params.videos || []), this.downloadAssetsGroup(this.params.scripts), this.downloadAssetsGroup(cssResources), ], ); } private convertToComponents() { if (this.params.htmlToComponents && this.params.htmlToComponentsSettings !== undefined) { const settings = this.params.htmlToComponentsSettings; const sourceComponentsPath = path.resolve(__dirname, '../.cache'); deleteFolderRecursive(sourceComponentsPath); fs.mkdirSync(sourceComponentsPath); const localComponents: Array<string> = this.params.htmlToComponentsSettings.rules .filter(item => item.scope === ComponentScope.Local) .map(item => `${item.component}.jsx`); const htmlToComponents = new HtmlToComponents(settings); const targetPageJsxPath = this.getPageFilePath(this.params.pageUrl, 'Page.jsx'); try { htmlToComponents.convert(this.params.bodyHtml); } catch (error) { if (this.params.allowFallbackHtml) { this.writeContent(targetPageJsxPath, this.wrapHtmlDangerously(this.params.bodyHtml)); debug(`[WARNING] An error occurred while processing html to jsx component conversion for page: ${this.params.pageUrl}. Component created with dangerouslySetInnerHTML.`); return; } throw error; } const targetComponentsPath = path.resolve(this.params.pagesDir, '../../components'); let pageJsxContent = fs.readFileSync(path.resolve(sourceComponentsPath, 'Page.jsx')).toString(); fs.readdirSync(sourceComponentsPath) .filter(file => !localComponents.includes(file) && file !== 'Page.jsx') .forEach(file => { const fileName = path.parse(file).name; pageJsxContent = pageJsxContent.replace(`import ${fileName} from "./${fileName}`, `import ${fileName} from "src/components/${fileName}`); const sourcePath = path.resolve(sourceComponentsPath, file); const targetPath = path.resolve(targetComponentsPath, file); fs.copyFileSync(sourcePath, targetPath); }); this.writeContent(targetPageJsxPath, pageJsxContent); localComponents.forEach(component => { const sourcePath = path.resolve(sourceComponentsPath, component); if (fs.existsSync(sourcePath)) { const targetPath = this.getPageFilePath(this.params.pageUrl, component); fs.copyFileSync(sourcePath, targetPath); } }); } } private createJsxPage() { let content = this.processTemplate(); this.convertToComponents(); const pageFilePath = this.getPageFilePath(this.params.pageUrl); content = formatJsx(content); this.writeContent(pageFilePath, content); } private writeContent(targetPath: string, content: string) { debug(`trying writing to ${targetPath}`); ensureDirectoryExistence(targetPath); fs.writeFileSync(targetPath, content); } private wrapHtmlDangerously(content: string) { const html = `\`${content.replace(/`/g, '\\`')}\``; const templateContent = fs.readFileSync(this.params.templateDangerousHtml).toString(); return templateContent.replace('%html%', html); } private processTemplate(): string { // handle exception if templatePath does not exist let templateContent = fs.readFileSync(this.params.templatePath).toString(); templateContent = this.replaceHead(templateContent); return templateContent; } private isUrlExternal(item: string) { return isUrlExternal(this.params.pageUrl, item); } private convertTextToAttribute(html: string) { let wrappedHtml = html; if (!HtmlParser.contains(html, 'body')) { wrappedHtml = `<html><body>${html}</body></html>`; } const htmlParser = new HtmlParser(wrappedHtml); htmlParser.transformElementTextToAttribute('style', 'cssText'); htmlParser.transformElementTextToAttribute('script', 'innerHtml'); return htmlParser.getBodyHtml(); } private replaceHead(template: string): string { // the goal is to inject body and html attributes to helmet // as an option, we can make it by setting html and body tags as helmet children // html and body tags should be converted to jsx // html2jsx library is responsible for converting html to jsx // html2jsx uses dom innerHTML attribute that ignores html and body tags // (the same behavior in browser) // hereby, if we want to have html and body processed, we need to rename them // once html to jsx conversion is complement, // we need to replace the fake element to html/body back // there is another option to reach the goal // we can convert head to jsx without html and body // and inject bodyAttributes and htmlAttributes as props to jsx element // there is a plugin that allows to do it - @svgr/babel-plugin-add-jsx-attribute // but the plugin does not support object literals // sticking with this hacky solution, probably we will refactor it // once we find a better way how to handle it const headWithHtmlAndBody = this.params.htmlTag.replace('<html', '<fakehtml').replace('</html>', '</fakehtml>') + this.params.bodyTag.replace('<body', '<fakebody').replace('</body>', '</fakebody>') + this.params.headHtml; const headWithCssText = this.convertTextToAttribute(headWithHtmlAndBody); const htmlToJsx = new HtmlToJsx({ createClass: false }); const headJsx = htmlToJsx.convert(headWithCssText); const withHelmet = replaceRootJsxElement(headJsx, 'Helmet'); const withHelmet$ = renameJsxElement(withHelmet, 'fakehtml', 'html'); const withHelmet$$ = renameJsxElement(withHelmet$, 'fakebody', 'body'); return template.replace('%head%', withHelmet$$); } }
the_stack
import { T, Val, EmptyArray, IterType, FalseyValues, isTruthy } from "./common"; import { Result, Ok, Err } from "./result"; export type Some<T> = OptionType<T> & { [T]: true }; export type None = OptionType<never> & { [T]: false }; export type Option<T> = OptionType<T>; type From<T> = Exclude<T, Error | FalseyValues>; type OptionTypes<O> = { [K in keyof O]: O[K] extends Option<infer T> ? T : never; }; class OptionType<T> { readonly [T]: boolean; readonly [Val]: T; constructor(val: T, some: boolean) { this[T] = some; this[Val] = val; } [Symbol.iterator](this: Option<T>): IterType<T> { return this[T] ? (this[Val] as any)[Symbol.iterator]() : EmptyArray[Symbol.iterator](); } /** * Return the contained `T`, or `none` if the option is `None`. The `none` * value must be falsey and defaults to `undefined`. * * ``` * const x: Option<number> = Some(1); * assert.equal(x.into(), 1); * * const x: Option<number> = None; * assert.equal(x.into(), undefined); * * const x: Option<number> = None; * assert.equal(x.into(null), null); * ``` */ into(this: Option<T>): T | undefined; into<U extends FalseyValues>(this: Option<T>, none: U): T | U; into(this: Option<T>, none?: FalseyValues): T | FalseyValues { return this[T] ? this[Val] : none; } /** * Compares the Option to `cmp`, returns true if both are `Some` or both * are `None` and acts as a type guard. * * ``` * const s: Option<number> = Some(1); * const n: Option<number> = None; * * assert.equal(s.isLike(Some(10)), true); * assert.equal(n.isLike(None), true); * assert.equal(s.isLike(n), false); * ``` */ isLike(this: Option<T>, cmp: unknown): cmp is Option<unknown> { return cmp instanceof OptionType && this[T] === cmp[T]; } /** * Returns true if the Option is `Some` and acts as a type guard. * * ``` * const x = Some(10); * assert.equal(x.Is(), true); * * const x: Option<number> = None; * assert.equal(x.Is(), false); * ``` */ isSome(this: Option<T>): this is Some<T> { return this[T]; } /** * Returns true if the Option is `None` and acts as a type guard. * * ``` * const x = Some(10); * assert.equal(x.isNone(), false); * * const x: Option<number> = None; * assert.equal(x.isNone(), true); * ``` */ isNone(this: Option<T>): this is None { return !this[T]; } /** * Calls `f` with the contained `Some` value, converting `Some` to `None` if * the filter returns false. * * For more advanced filtering, consider `match`. * * ``` * const x = Some(1); * assert.equal(x.filter((v) => v < 5).unwrap(), 1); * * const x = Some(10); * assert.equal(x.filter((v) => v < 5).isNone(), true); * * const x: Option<number> = None; * assert.equal(x.filter((v) => v < 5).isNone(), true); * ``` */ filter(this: Option<T>, f: (val: T) => boolean): Option<T> { return this[T] && f(this[Val]) ? this : None; } /** * Returns the contained `Some` value and throws `Error(msg)` if `None`. * * To avoid throwing, consider `Is`, `unwrapOr`, `unwrapOrElse` or * `match` to handle the `None` case. * * ``` * const x = Some(1); * assert.equal(x.expect("Is empty"), 1); * * const x: Option<number> = None; * const y = x.expect("Is empty"); // throws * ``` */ expect(this: Option<T>, msg: string): T { if (this[T]) { return this[Val]; } else { throw new Error(msg); } } /** * Returns the contained `Some` value and throws if `None`. * * To avoid throwing, consider `isSome`, `unwrapOr`, `unwrapOrElse` or * `match` to handle the `None` case. To throw a more informative error use * `expect`. * * ``` * const x = Some(1); * assert.equal(x.unwrap(), 1); * * const x: Option<number> = None; * const y = x.unwrap(); // throws * ``` */ unwrap(this: Option<T>): T { return this.expect("Failed to unwrap Option (found None)"); } /** * Returns the contained `Some` value or a provided default. * * The provided default is eagerly evaluated. If you are passing the result * of a function call, consider `unwrapOrElse`, which is lazily evaluated. * * ``` * const x = Some(10); * assert.equal(x.unwrapOr(1), 10); * * const x: Option<number> = None; * assert.equal(x.unwrapOr(1), 1); * ``` */ unwrapOr(this: Option<T>, def: T): T { return this[T] ? this[Val] : def; } /** * Returns the contained `Some` value or computes it from a function. * * ``` * const x = Some(10); * assert.equal(x.unwrapOrElse(() => 1 + 1), 10); * * const x: Option<number> = None; * assert.equal(x.unwrapOrElse(() => 1 + 1), 2); * ``` */ unwrapOrElse(this: Option<T>, f: () => T): T { return this[T] ? this[Val] : f(); } /** * Returns the contained `Some` value or undefined if `None`. * * Most problems are better solved using one of the other `unwrap_` methods. * This method should only be used when you are certain that you need it. * * ``` * const x = Some(10); * assert.equal(x.unwrapUnchecked(), 10); * * const x: Option<number> = None; * assert.equal(x.unwrapUnchecked(), undefined); * ``` */ unwrapUnchecked(this: Option<T>): T | undefined { return this[Val]; } /** * Returns the Option if it is `Some`, otherwise returns `optb`. * * `optb` is eagerly evaluated. If you are passing the result of a function * call, consider `orElse`, which is lazily evaluated. * * ``` * const x = Some(10); * const xor = x.or(Some(1)); * assert.equal(xor.unwrap(), 10); * * const x: Option<number> = None; * const xor = x.or(Some(1)); * assert.equal(xor.unwrap(), 1); * ``` */ or(this: Option<T>, optb: Option<T>): Option<T> { return this[T] ? this : optb; } /** * Returns the Option if it is `Some`, otherwise returns the value of `f()`. * * ``` * const x = Some(10); * const xor = x.orElse(() => Some(1)); * assert.equal(xor.unwrap(), 10); * * const x: Option<number> = None; * const xor = x.orElse(() => Some(1)); * assert.equal(xor.unwrap(), 1); * ``` */ orElse(this: Option<T>, f: () => Option<T>): Option<T> { return this[T] ? this : f(); } /** * Returns `None` if the Option is `None`, otherwise returns `optb`. * * ``` * const x = Some(10); * const xand = x.and(Some(1)); * assert.equal(xand.unwrap(), 1); * * const x: Option<number> = None; * const xand = x.and(Some(1)); * assert.equal(xand.isNone(), true); * * const x = Some(10); * const xand = x.and(None); * assert.equal(xand.isNone(), true); * ``` */ and<U>(this: Option<T>, optb: Option<U>): Option<U> { return this[T] ? optb : None; } /** * Returns `None` if the option is `None`, otherwise calls `f` with the * `Some` value and returns the result. * * ``` * const x = Some(10); * const xand = x.andThen((n) => n + 1); * assert.equal(xand.unwrap(), 11); * * const x: Option<number> = None; * const xand = x.andThen((n) => n + 1); * assert.equal(xand.isNone(), true); * * const x = Some(10); * const xand = x.andThen(() => None); * assert.equal(xand.isNone(), true); * ``` */ andThen<U>(this: Option<T>, f: (val: T) => Option<U>): Option<U> { return this[T] ? f(this[Val]) : None; } /** * Maps an `Option<T>` to `Option<U>` by applying a function to the `Some` * value. * * ``` * const x = Some(10); * const xmap = x.map((n) => `number ${n}`); * assert.equal(xmap.unwrap(), "number 10"); * ``` */ map<U>(this: Option<T>, f: (val: T) => U): Option<U> { return this[T] ? new OptionType(f(this[Val]), true) : None; } /** * Returns the provided default if `None`, otherwise calls `f` with the * `Some` value and returns the result. * * The provided default is eagerly evaluated. If you are passing the result * of a function call, consider `mapOrElse`, which is lazily evaluated. * * ``` * const x = Some(10); * const xmap = x.mapOr(1, (n) => n + 1); * assert.equal(xmap.unwrap(), 11); * * const x: Option<number> = None; * const xmap = x.mapOr(1, (n) => n + 1); * assert.equal(xmap.unwrap(), 1); * ``` */ mapOr<U>(this: Option<T>, def: U, f: (val: T) => U): U { return this[T] ? f(this[Val]) : def; } /** * Computes a default return value if `None`, otherwise calls `f` with the * `Some` value and returns the result. * * const x = Some(10); * const xmap = x.mapOrElse(() => 1 + 1, (n) => n + 1); * assert.equal(xmap.unwrap(), 11); * * const x: Option<number> = None; * const xmap = x.mapOrElse(() => 1 + 1, (n) => n + 1); * assert.equal(xmap.unwrap(), 2); * ``` */ mapOrElse<U>(this: Option<T>, def: () => U, f: (val: T) => U): U { return this[T] ? f(this[Val]) : def(); } /** * Transforms the `Option<T>` into a `Result<T, E>`, mapping `Some(v)` to * `Ok(v)` and `None` to `Err(err)`. * * ``` * const x = Some(10); * const res = x.okOr("Is empty"); * assert.equal(x.isOk(), true); * assert.equal(x.unwrap(), 10); * * const x: Option<number> = None; * const res = x.okOr("Is empty"); * assert.equal(x.isErr(), true); * assert.equal(x.unwrap_err(), "Is empty"); * ``` */ okOr<E>(this: Option<T>, err: E): Result<T, E> { return this[T] ? Ok(this[Val]) : Err(err); } /** * Transforms the `Option<T>` into a `Result<T, E>`, mapping `Some(v)` to * `Ok(v)` and `None` to `Err(f())`. * * ``` * const x = Some(10); * const res = x.okOrElse(() => ["Is", "empty"].join(" ")); * assert.equal(x.isOk(), true); * assert.equal(x.unwrap(), 10); * * const x: Option<number> = None; * const res = x.okOrElse(() => ["Is", "empty"].join(" ")); * assert.equal(x.isErr(), true); * assert.equal(x.unwrap_err(), "Is empty"); * ``` */ okOrElse<E>(this: Option<T>, f: () => E): Result<T, E> { return this[T] ? Ok(this[Val]) : Err(f()); } } /** * An Option represents either something, or nothing. If we hold a value * of type `Option<T>`, we know it is either `Some<T>` or `None`. * * As a function, `Option` is an alias for `Option.from`. * * ``` * const users = ["Fry", "Bender"]; * function fetch_user(username: string): Option<string> { * return users.includes(username) ? Some(username) : None; * } * * function greet(username: string): string { * return fetch_user(username) * .map((user) => `Good news everyone, ${user} is here!`) * .unwrapOr("Wha?"); * } * * assert.equal(greet("Bender"), "Good news everyone, Bender is here!"); * assert.equal(greet("SuperKing"), "Wha?"); * ``` */ export function Option<T>(val: T): Option<From<T>> { return from(val); } Option.is = is; Option.from = from; Option.nonNull = nonNull; Option.qty = qty; Option.safe = safe; Option.all = all; Option.any = any; /** * Creates a `Some<T>` value, which can be used where an `Option<T>` is * required. See Option for more examples. * * ``` * const x = Some(10); * assert.equal(x.isSome(), true); * assert.equal(x.unwrap(), 10); * ``` */ export function Some<T>(val: T): Some<T> { return new OptionType(val, true) as Some<T>; } /** * The `None` value, which can be used where an `Option<T>` is required. * See Option for more examples. * * ``` * const x = None; * assert.equal(x.isNone(), true); * const y = x.unwrap(); // throws * ``` */ export const None = Object.freeze( new OptionType<never>(undefined as never, false) ); /** * Tests whether the provided `val` is an Option, and acts as a type guard. * * ``` * assert.equal(Option.is(Some(1), true); * assert.equal(Option.is(None, true)); * assert.equal(Option.is(Ok(1), false)); * ``` */ function is(val: unknown): val is Option<unknown> { return val instanceof OptionType; } /** * Creates a new `Option<T>` which is `Some` unless the provided `val` is * falsey, an instance of `Error` or an invalid `Date`. This function is * aliased by `Option`. * * The `T` type is narrowed to exclude falsey orError values. * * ``` * assert.equal(Option.from(1).unwrap(), 1); * assert.equal(from(0).isNone(), true); * * const err = Option.from(new Error("msg")); * assert.equal(err.isNone(), true); * ``` */ function from<T>(val: T): Option<From<T>> { return isTruthy(val) && !(val instanceof Error) ? (Some(val) as any) : None; } /** * Creates a new `Option<T>` which is `Some` unless the provided `val` is * `undefined`, `null` or `NaN`. * * ``` * assert.equal(Option.nonNull(1).unwrap(), 1); * assert.equal(Option.nonNull(0).unwrap(), 0); * assert.equal(Option.nonNull(null).isNone(), true); * ``` */ function nonNull<T>(val: T): Option<NonNullable<T>> { return val === undefined || val === null || val !== val ? None : Some(val as NonNullable<T>); } /** * Creates a new Option<number> which is `Some` when the provided `val` is a * finite integer greater than or equal to 0. * * ``` * const x = Option.qty("test".indexOf("s")); * assert.equal(x.unwrap(), 2); * * const x = Option.qty("test".indexOf("z")); * assert.equal(x.isNone(), true); * ``` */ function qty<T extends number>(val: T): Option<number> { return val >= 0 && Number.isInteger(val) ? Some(val) : None; } /** * Capture the outcome of a function or Promise as an `Option<T>`, preventing * throwing (function) or rejection (Promise). * * ### Usage for functions * * Calls `fn` with the provided `args` and returns an `Option<T>`. The Option * is `Some` if the provided function returned, or `None` if it threw. * * **Note:** Any function which returns a Promise (or PromiseLike) value is * rejected by the type signature. `Option<Promise<T>>` is not a useful type, * and using it in this way is likely to be a mistake. * * ``` * function mightThrow(throws: boolean) { * if (throws) { * throw new Error("Throw"); * } * return "Hello World"; * } * * const x: Option<string> = Option.safe(mightThrow, true); * assert.equal(x.isNone(), true); * * const x = Option.safe(() => mightThrow(false)); * assert.equal(x.unwrap(), "Hello World"); * ``` * * ### Usage for Promises * * Accepts `promise` and returns a new Promise which always resolves to * `Option<T>`. The Result is `Some` if the original promise resolved, or * `None` if it rejected. * * ``` * async function mightThrow(throws: boolean) { * if (throws) { * throw new Error("Throw") * } * return "Hello World"; * } * * const x = await Option.safe(mightThrow(true)); * assert.equal(x.isNone(), true); * * const x = await Option.safe(mightThrow(false)); * assert.equal(x.unwrap(), "Hello World"); * ``` */ function safe<T, A extends any[]>( fn: (...args: A) => T extends PromiseLike<any> ? never : T, ...args: A ): Option<T>; function safe<T>(promise: Promise<T>): Promise<Option<T>>; function safe<T, A extends any[]>( fn: ((...args: A) => T) | Promise<T>, ...args: A ): Option<T> | Promise<Option<T>> { if (fn instanceof Promise) { return fn.then( (val) => Some(val), () => None ); } try { return Some(fn(...args)); } catch { return None; } } /** * Converts a number of `Option`s into a single Option. If any of the provided * Options are `None` then the new Option is also None. Otherwise the new * Option is `Some` and contains an array of all the unwrapped values. * * ``` * function num(val: number): Option<number> { * return val > 10 ? Some(val) : None; * } * * const xyz = Option.all(num(20), num(30), num(40)); * const [x, y, z] = xyz.unwrap(); * assert.equal(x, 20); * assert.equal(y, 30); * assert.equal(z, 40); * * const x = Option.all(num(20), num(5), num(40)); * assert.equal(x.isNone(), true); * ``` */ function all<O extends Option<any>[]>(...options: O): Option<OptionTypes<O>> { const some = []; for (const option of options) { if (option.isSome()) { some.push(option.unwrapUnchecked()); } else { return None; } } return Some(some) as Some<OptionTypes<O>>; } /** * Converts a number of `Options`s into a single Option. The first `Some` found * (if any) is returned, otherwise the new Option is `None`. * * ``` * function num(val: number): Option<number> { * return val > 10 ? Some(val) : None; * } * * const x = Option.any(num(5), num(20), num(2)); * assert.equal(x.unwrap(), 20); * * const x = Option.any(num(2), num(5), num(8)); * assert.equal(x.isNone(), true); * ``` */ function any<O extends Option<any>[]>( ...options: O ): Option<OptionTypes<O>[number]> { for (const option of options) { if (option.isSome()) { return option as Option<OptionTypes<O>[number]>; } } return None; }
the_stack
import { getAncestorsTree } from './ancestor-chart'; import { HierarchyNode, HierarchyPointNode } from 'd3-hierarchy'; import { IdGenerator } from './id-generator'; import { layOutDescendants } from './descendant-chart'; import { max, min } from 'd3-array'; import { Chart, ChartInfo, ChartOptions, DataProvider, Fam, Indi, TreeNode, } from './api'; import { ChartUtil, getChartInfo, getChartInfoWithoutMargin, H_SPACING, V_SPACING, } from './chart-util'; /** A view of a family that hides one child individual. */ class FilterChildFam implements Fam { constructor(private fam: Fam, private childId: string) {} getId(): string { return this.fam.getId(); } getFather(): string | null { return this.fam.getFather(); } getMother(): string | null { return this.fam.getMother(); } getChildren(): string[] { const children = [...this.fam.getChildren()]; const index = children.indexOf(this.childId); if (index !== -1) { children.splice(index, 1); } return children; } } /** Data provider proxy that filters out a specific child individual. */ class FilterChildData implements DataProvider<Indi, Fam> { constructor(private data: DataProvider<Indi, Fam>, private childId: string) {} getIndi(id: string): Indi | null { return this.data.getIndi(id); } getFam(id: string): Fam | null { return new FilterChildFam(this.data.getFam(id)!, this.childId); } } /** Information about the subtree of descendants of an ancestor. */ interface AncestorData { // Descendants. descendantNodes: Array<HierarchyPointNode<TreeNode>>; // Dimensions of the subtree bounding box. width: number; height: number; // Position of the ancestors relative to the top-left corner of the subtree // bounding box. x: number; y: number; // Whether the chart is expanded leftwards. Rightwards otherwise. left?: boolean; // Set to true when the ancstor should be drawn horizontally in the middle // of the chart. middle?: boolean; } /** Chart layout showing all relatives of a person. */ export class RelativesChart<IndiT extends Indi, FamT extends Fam> implements Chart { readonly util: ChartUtil; constructor(readonly options: ChartOptions) { this.util = new ChartUtil(options); this.options.idGenerator = this.options.idGenerator || new IdGenerator(); } layOutAncestorDescendants( ancestorsRoot: HierarchyNode<TreeNode>, focusedNode: HierarchyPointNode<TreeNode> ) { // let ancestorDescentants: Array<HierarchyPointNode<TreeNode>> = []; const ancestorData = new Map<string, AncestorData>(); ancestorsRoot.eachAfter((node) => { if (!node.parent) { return; } const descendantOptions = { ...this.options }; descendantOptions.startFam = node.data.family!.id; descendantOptions.startIndi = undefined; const child = node.id === node.parent.data.spouseParentNodeId ? node.parent.data.spouse!.id : node.parent.data.indi!.id; descendantOptions.data = new FilterChildData( descendantOptions.data, child ); descendantOptions.baseGeneration = (this.options.baseGeneration || 0) - node.depth; const descendantNodes = layOutDescendants(descendantOptions); // The id could be modified because of duplicates. This can happen when // drawing one family in multiple places of the chart). node.data.id = descendantNodes[0].id!; const chartInfo = getChartInfoWithoutMargin(descendantNodes); const parentData = (node.children || []).map((childNode) => ancestorData.get(childNode.data.id) ); const parentHeight = parentData .map((data) => data!.height) .reduce((a, b) => a + b + V_SPACING, 0); const data: AncestorData = { descendantNodes, width: chartInfo.size[0], height: chartInfo.size[1] + parentHeight, x: chartInfo.origin[0], y: chartInfo.origin[1] + parentHeight, }; ancestorData.set(node.data.id, data); }); ancestorsRoot.each((node) => { if (!node.parent) { return; } const data = ancestorData.get(node.data.id); const parentData = ancestorData.get(node.parent.data.id); data!.left = parentData && !parentData.middle ? parentData.left : node.parent.data.indiParentNodeId === node.id; data!.middle = (!parentData || parentData.middle) && node.parent.children!.length === 1; }); ancestorsRoot.each((node) => { const data = ancestorData.get(node.data.id); const thisNode = data ? data.descendantNodes[0] : focusedNode; (node.children || []).forEach((child) => { const childNode = ancestorData.get(child.data.id)!.descendantNodes[0]; childNode.parent = thisNode; }); if (node.data.indiParentNodeId && node.children) { thisNode.data.indiParentNodeId = node.children!.find( (childNode) => childNode.id === node.data.indiParentNodeId )!.data.id; } if (node.data.spouseParentNodeId && node.children) { thisNode.data.spouseParentNodeId = node.children!.find( (childNode) => childNode.id === node.data.spouseParentNodeId )!.data.id; } }); ancestorsRoot.each((node) => { const nodeData = ancestorData.get(node.data.id); // Lay out the nodes produced by laying out descendants of ancestors // instead of the ancestor nodes from ancestorsRoot. const thisNode = nodeData ? nodeData.descendantNodes[0] : focusedNode; const indiParent = node.children && node.children.find((child) => child.id === node.data.indiParentNodeId); const spouseParent = node.children && node.children.find( (child) => child.id === node.data.spouseParentNodeId ); const nodeX = thisNode.x; const nodeY = thisNode.y; const nodeWidth = thisNode.data.width!; const nodeHeight = thisNode.data.height!; const indiWidth = thisNode.data.indi ? thisNode.data.indi.width! : 0; const spouseWidth = thisNode.data.spouse ? thisNode.data.spouse.width! : 0; // Lay out the individual's ancestors and their descendants. if (indiParent) { const data = ancestorData.get(indiParent.data.id)!; const parentNode = data.descendantNodes[0]; const parentData = parentNode.data; const spouseTreeHeight = spouseParent ? ancestorData.get(spouseParent.data.id)!.height + V_SPACING : 0; const dx = nodeX + data.x - nodeWidth / 2 + indiWidth / 2 + (data.left ? -data.width - H_SPACING : H_SPACING); const dy = nodeY + data.y - nodeHeight / 2 - data.height + (data.left ? -V_SPACING : -spouseTreeHeight - V_SPACING); // Move all nodes by (dx, dy). The ancestor node, // ie. data.descendantNodes[0] is now at (0, 0). data.descendantNodes.forEach((node) => { node.x += dx; node.y += dy; }); // Set the ancestor's horizontal position independently. const middleX = indiWidth / 2 - nodeWidth / 2 + parentData.width! / 2 - (parentData.indi ? parentData.indi.width! : parentData.spouse!.width!); if (data.middle) { parentNode.x = 0; } else if (!nodeData || nodeData.middle) { parentNode.x = -nodeWidth / 2 - parentData.width! / 2 + indiWidth - H_SPACING / 2; } else if (data.left) { parentNode.x = nodeX + min([ nodeWidth / 2 - parentData.width! / 2 - spouseWidth / 2 - H_SPACING, middleX, ])!; } else { parentNode.x = nodeX + max([parentData.width! / 2 - nodeWidth / 2, middleX])!; } } // Lay out the spouse's ancestors and their descendants. if (spouseParent) { const data = ancestorData.get(spouseParent.data.id)!; const parentNode = data.descendantNodes[0]; const parentData = parentNode.data; const indiTreeHeight = indiParent ? ancestorData.get(indiParent.data.id)!.height + V_SPACING : 0; const dx = nodeX + data.x + nodeWidth / 2 - spouseWidth / 2 + (data.left ? -data.width - H_SPACING : H_SPACING); const dy = nodeY + data.y - nodeHeight / 2 - data.height + (data.left ? -indiTreeHeight - V_SPACING : -V_SPACING); // Move all nodes by (dx, dy). The ancestor node, // ie. data.descendantNodes[0] is now at (0, 0). data.descendantNodes.forEach((node) => { node.x += dx; node.y += dy; }); // Set the ancestor's horizontal position independently. const middleX = nodeWidth / 2 - spouseWidth / 2 + parentData.width! / 2 - (parentData.indi ? parentData.indi.width! : parentData.spouse!.width!); if (data.middle) { parentNode.x = 0; } else if (!nodeData || nodeData.middle) { parentNode.x = nodeWidth / 2 + parentData.width! / 2 - spouseWidth + H_SPACING / 2; } else if (data.left) { parentNode.x = nodeX + min([nodeWidth / 2 - parentData.width! / 2, middleX])!; } else { parentNode.x = nodeX + max([ parentData.width! / 2 - nodeWidth / 2 + indiWidth / 2 + H_SPACING, middleX, ])!; } } }); return Array.from(ancestorData.values()) .map((data) => data.descendantNodes) .reduce((a, b) => a.concat(b), []); } render(): ChartInfo { const descendantNodes = layOutDescendants(this.options); // Don't use common id generator because these nodes will not be drawn. const ancestorOptions = Object.assign({}, this.options, { idGenerator: undefined, }); const ancestorsRoot = getAncestorsTree(ancestorOptions); const ancestorDescentants = this.layOutAncestorDescendants( ancestorsRoot, descendantNodes[0] ); const nodes = descendantNodes.concat(ancestorDescentants); const animationPromise = this.util.renderChart(nodes); const info = getChartInfo(nodes); this.util.updateSvgDimensions(info); return Object.assign(info, { animationPromise }); } }
the_stack
import StreamID, { CommitID } from '@ceramicnetwork/streamid' import { AnchorService, AnchorStatus, CommitType, Context, CreateOpts, LoadOpts, PinningOpts, PublishOpts, StreamState, StreamStateHolder, StreamUtils, SyncOptions, UpdateOpts, } from '@ceramicnetwork/common' import { PinStore } from '../store/pin-store' import { DiagnosticsLogger } from '@ceramicnetwork/common' import { ExecutionQueue } from './execution-queue' import { RunningState } from './running-state' import { StateManager } from './state-manager' import type { Dispatcher } from '../dispatcher' import type { ConflictResolution } from '../conflict-resolution' import type { HandlersMap } from '../handlers-map' import type { StateValidation } from './state-validation' import { Observable } from 'rxjs' import { StateCache } from './state-cache' import { SnapshotState } from './snapshot-state' import Utils from '../utils' export type RepositoryDependencies = { dispatcher: Dispatcher pinStore: PinStore context: Context handlers: HandlersMap anchorService: AnchorService conflictResolution: ConflictResolution stateValidation: StateValidation } const DEFAULT_LOAD_OPTS = { sync: SyncOptions.PREFER_CACHE, syncTimeoutSeconds: 3 } export class Repository { /** * Serialize loading operations per streamId. */ readonly loadingQ: ExecutionQueue /** * Serialize operations on state per streamId. */ readonly executionQ: ExecutionQueue /** * In-memory cache of the currently running streams. */ readonly inmemory: StateCache<RunningState> /** * Various dependencies. */ #deps: RepositoryDependencies /** * Instance of StateManager for performing operations on stream state. */ stateManager: StateManager /** * @param cacheLimit - Maximum number of streams to store in memory cache. * @param logger - Where we put diagnostics messages. * @param concurrencyLimit - Maximum number of concurrently running tasks on the streams. */ constructor( cacheLimit: number, concurrencyLimit: number, private readonly logger: DiagnosticsLogger ) { this.loadingQ = new ExecutionQueue(concurrencyLimit, logger) this.executionQ = new ExecutionQueue(concurrencyLimit, logger) this.inmemory = new StateCache(cacheLimit, (state$) => state$.complete()) this.updates$ = this.updates$.bind(this) } // Ideally this would be provided in the constructor, but circular dependencies in our initialization process make this necessary for now setDeps(deps: RepositoryDependencies): void { this.#deps = deps this.stateManager = new StateManager( deps.dispatcher, deps.pinStore, this.executionQ, deps.anchorService, deps.conflictResolution, this.logger, (streamId) => this.get(streamId), (streamId, opts) => this.load(streamId, opts) ) } private fromMemory(streamId: StreamID): RunningState | undefined { return this.inmemory.get(streamId.toString()) } private async fromStateStore(streamId: StreamID): Promise<RunningState | undefined> { const streamState = await this.#deps.pinStore.stateStore.load(streamId) if (streamState) { const runningState = new RunningState(streamState) this.add(runningState) const toRecover = runningState.value.anchorStatus === AnchorStatus.PENDING || runningState.value.anchorStatus === AnchorStatus.PROCESSING if (toRecover && this.stateManager.anchorService) { this.stateManager.confirmAnchorResponse(runningState) } return runningState } else { return undefined } } private async fromNetwork(streamId: StreamID): Promise<RunningState> { const handler = this.#deps.handlers.get(streamId.typeName) const genesisCid = streamId.cid const commitData = await Utils.getCommitData(this.#deps.dispatcher, genesisCid) if (commitData == null) { throw new Error(`No genesis commit found with CID ${genesisCid.toString()}`) } // Do not check for possible key revocation here, as we will do so later after loading the tip (or learning that the genesis commit *is* the current tip), when we will have timestamp information for when the genesis commit was anchored. commitData.disableTimecheck = true const state = await handler.applyCommit(commitData, this.#deps.context) await this.#deps.stateValidation.validate(state, state.content) const state$ = new RunningState(state) this.add(state$) this.logger.verbose(`Genesis commit for stream ${streamId.toString()} successfully loaded`) return state$ } /** * Returns a stream from wherever we can get information about it. * Starts by checking if the stream state is present in the in-memory cache, if not then * checks the state store, and finally loads the stream from pubsub. */ async load(streamId: StreamID, opts: LoadOpts): Promise<RunningState> { opts = { ...DEFAULT_LOAD_OPTS, ...opts } const state$ = await this.loadingQ.forStream(streamId).run(async () => { let fromStateStore = false let stream = this.fromMemory(streamId) if (!stream) { stream = await this.fromStateStore(streamId) if (stream) { fromStateStore = true } } if (stream && opts.sync == SyncOptions.PREFER_CACHE) { if (!fromStateStore || this.stateManager.wasPinnedStreamSynced(streamId)) { // If the stream was from the in-memory cache we know it's up to date, so no need to sync. // If the stream from the state store then we check if we've already synced the stream at // least once in the lifetime of this process: if so we know the state is up to date, so // no need to sync. If not, then it could be out of date due to updates made while the // node was offline, in which case we fall through to calling `stateManager.sync()` below. return stream } } if (!stream) { stream = await this.fromNetwork(streamId) } if (opts.sync == SyncOptions.NEVER_SYNC) { return this.stateManager.verifyLoneGenesis(stream) } await this.stateManager.sync(stream, opts.syncTimeoutSeconds * 1000, fromStateStore) return this.stateManager.verifyLoneGenesis(stream) }) await this.handlePinOpts(state$, opts) return state$ } /** * Load the state for a stream at a specific CommitID. * @param commitId * @param opts */ async loadAtCommit(commitId: CommitID, opts: LoadOpts): Promise<SnapshotState> { // Start by loading the current state of the stream. This might cause us to load more commits // for the stream than is ultimately necessary, but doing so increases the chances that we // detect that the CommitID specified is rejected by the conflict resolution rules due to // conflict with the stream's canonical branch of history. const base$ = await this.load(commitId.baseID, opts) return this.stateManager.atCommit(base$, commitId) } /** * Load the state for a stream as it was at a specified wall clock time, based on the anchor * timestamps of AnchorCommits in the log. * @param streamId * @param opts - must contain an 'atTime' parameter */ async loadAtTime(streamId: StreamID, opts: LoadOpts): Promise<SnapshotState> { const base$ = await this.load(streamId.baseID, opts) return this.stateManager.atTime(base$, opts.atTime) } /** * Applies commit to the existing state * * @param streamId - Stream ID to update * @param commit - Commit data * @param opts - Stream initialization options (request anchor, wait, etc.) */ async applyCommit( streamId: StreamID, commit: any, opts: CreateOpts | UpdateOpts ): Promise<RunningState> { const state$ = await this.stateManager.applyCommit(streamId, commit, opts) await this.applyWriteOpts(state$, opts) return state$ } /** * Apply options relating to authoring a new commit * * @param state$ - Running State * @param opts - Initialization options (request anchor, publish to pubsub, etc.) * @private */ async applyWriteOpts(state$: RunningState, opts: CreateOpts | UpdateOpts) { this.stateManager.applyWriteOpts(state$, opts) await this.handlePinOpts(state$, opts) } async handlePinOpts(state$: RunningState, opts: PinningOpts) { if (opts.pin) { await this.pin(state$) } else if (opts.pin === false) { await this.unpin(StreamUtils.streamIdFromState(state$.value)) } } /** * Handles new stream creation by loading genesis commit into memory and then handling the given * CreateOpts for the genesis commit. * @param streamId * @param opts */ async applyCreateOpts(streamId: StreamID, opts: CreateOpts): Promise<RunningState> { const state = await this.load(streamId, opts) await this.applyWriteOpts(state, opts) return state } /** * Return a stream, either from cache or re-constructed from state store, but will not load from the network. * Adds the stream to cache. */ async get(streamId: StreamID): Promise<RunningState | undefined> { return this.loadingQ.forStream(streamId).run(async () => { const fromMemory = this.fromMemory(streamId) if (fromMemory) return fromMemory return this.fromStateStore(streamId) }) } /** * Return a stream state, either from cache or from state store. */ async streamState(streamId: StreamID): Promise<StreamState | undefined> { const fromMemory = this.inmemory.get(streamId.toString()) if (fromMemory) { return fromMemory.state } else { return this.#deps.pinStore.stateStore.load(streamId) } } /** * Adds the stream's RunningState to the in-memory cache and subscribes the Repository's global feed$ to receive changes emitted by that RunningState */ add(state$: RunningState): void { this.inmemory.set(state$.id.toString(), state$) } pin(streamStateHolder: StreamStateHolder): Promise<void> { return this.#deps.pinStore.add(streamStateHolder) } async unpin(streamId: StreamID, opts?: PublishOpts): Promise<void> { if (opts?.publish) { // load the stream's current state from cache or the pin store and publish it to pubsub const state$ = await this.load(streamId, { sync: SyncOptions.NEVER_SYNC }) this.stateManager.publishTip(state$) } return this.#deps.pinStore.rm(streamId) } /** * List pinned streams as array of StreamID strings. * If `streamId` is passed, indicate if it is pinned. */ async listPinned(streamId?: StreamID): Promise<string[]> { return this.#deps.pinStore.ls(streamId) } /** * Updates for the StreamState, even if a (pinned or not pinned) stream has already been evicted. * Marks the stream as durable, that is not subject to cache eviction. * * First, we try to get the running state from memory or state store. If found, it is used as a source * of updates. If not found, we use StreamState passed as `init` param as a future source of updates. * Anyway, we mark it as unevictable. * * When a subscription to the observable stops, we check if there are other subscriptions to the same * RunningState. We only consider the RunningState free, if there are no more subscriptions. * This RunningState is subject to future cache eviction. * * @param init */ updates$(init: StreamState): Observable<StreamState> { return new Observable<StreamState>((subscriber) => { const id = new StreamID(init.type, init.log[0].cid) this.get(id).then((found) => { const state$ = found || new RunningState(init) this.inmemory.endure(id.toString(), state$) state$.subscribe(subscriber).add(() => { if (state$.observers.length === 0) { this.inmemory.free(id.toString()) } }) }) }) } async close(): Promise<void> { await this.loadingQ.close() await this.executionQ.close() Array.from(this.inmemory).forEach(([id, stream]) => { this.inmemory.delete(id) stream.complete() }) await this.#deps.pinStore.close() } }
the_stack
declare enum AdjustmentReference { ABSOLUTE, RELATIVE } /** * The point around which to transform an object. This is the point that does * not move when an object is rotated or resized using methods in ArtLayer, * LayerSet, and Selection, or when the entire canvas is resized with * Document.resizeCanvas(). */ declare enum AnchorPosition { BOTTOMCENTER, BOTTOMLEFT, BOTTOMRIGHT, MIDDLECENTER, MIDDLELEFT, MIDDLERIGHT, TOPCENTER, TOPLEFT, TOPRIGHT } /** * Method to use to smooth edges by softening the color transition between edge * pixels and background pixels. Used in a TextItem.antiAliasMethod. */ declare enum AntiAlias { CRISP, NONE, SHARP, SMOOTH, STRONG } /** * The type of kerning to use for characters. Used in TextItem.autoKerning. */ declare enum AutoKernType { MANUAL, METRICS, OPTICAL } /** * The destination, if any, for batch-processed files, specified in the * BatchOptions used with the Application.batch() method: FOLDER: Save modified * versions of the files to a new location (leaving the originals unchanged). * NODESTINATIONTYPE: Leave all files open. SAVEANDCLOSE: Save changes and close * the files. Adobe Photoshop CC JavaScript Scripting Reference Scripting * Constants 198 */ declare enum BatchDestinationType { FOLDER, NODESTINATION, SAVEANDCLOSE } /** * Specifies the quality of an image you are converting to bitmap mode. Used in * BitmapConversionOptions. */ declare enum BitmapConversionType { CUSTOMPATTERN, DIFFUSIONDITHER, HALFTHRESHOLD, HALFTONESCREEN, PATTERNDITHER } /** * Specifies the shape of the dots (ink deposits) in the halftone screen. Used * in BitmapConversionOptions. */ declare enum BitmapHalfToneType { CROSS, DIAMOND, ELLIPSE, LINE, ROUND, SQUARE } /** * The number of bits per color channel. Value of Document.bitsPerChannel; pass * to Documents.add(). Also used in PDFOpenOptions and CameraRAWOpenOptions. */ declare enum BitsPerChannelType { EIGHT, ONE, SIXTEEN, THIRTYTWO } /** * Controls how pixels in an image are blended when a filter is applied. The * value of ArtLayer.blendMode and LayerSet.blendMode. */ declare enum BlendMode { COLORBLEND, COLORBURN, COLORDODGE, DARKEN, DIFFERENCE, DISSOLVE, DIVIDE, EXCLUSION, HARDLIGHT, HARDMIX, HUE, LIGHTEN, LINEARBURN, LINEARDODGE, LINEARLIGHT, LUMINOSITY, MULTIPLY, NORMAL, OVERLAY, PASSTHROUGH, PINLIGHT, SATURATION, SCREEN, SOFTLIGHT, SUBTRACT, VIVIDLIGHT } /** * The number of bits per channel (also called pixel depth or color depth). The * number selected indicates the exponent of 2. For example, a pixel with a * bit-depth of EIGHT has 28, or 256, possible color values. Used in * BMPSaveOptions. Constant type Values What it means Adobe Photoshop CC * JavaScript Scripting Reference Scripting Constants 199 */ declare enum BMPDepthType { BMP_A1R5G5B5, BMP_A4R4G4B4, BMP_A8R8G8B8, BMP_R5G6B5, BMP_R8G8B8, BMP_X1R5G5B5, BMP_X4R4G4B4, BMP_X8R8G8B8, EIGHT, FOUR, ONE, SIXTEEN, THIRTYTWO, TWENTYFOUR } /** * The platform-specific order in which multibyte values are read. */ declare enum ByteOrder { IBM, MACOS } /** * The default CameraRaw settings to use: the camera settings, custom settings, * or the settings of the selected image. Set in CameraRAWOpenOptions. */ declare enum CameraRAWSettingsType { CAMERA, CUSTOM, SELECTEDIMAGE } /** * The camera RAW size type options:. EXTRALARGE=5120 x 4096 LARGE=4096 x 2731 * MAXIMUM=6144 X 4096 MEDIUM=3072 x 2048 MINIMUM=1536 x 1024 SMALL=2048 x 1365 * Set in CameraRAWOpenOptions. */ declare enum CameraRAWSize { EXTRALARGE, LARGE, MAXIMUM, MEDIUM, MINIMUM, SMALL } /** * The new color profile or mode for a document, specified in * Document.changeMode(). Note: Color images must be changed to GRAYSCALE mode * before you can change them to BITMAP mode. */ declare enum ChangeMode { BITMAP, CMYK, GRAYSCALE, INDEXEDCOLOR, LAB, MULTICHANNEL, RGB } /** * The type of a color channel: COMPONENT: related to document color mode. * MASKEDAREA: Alpha channel where color indicates masked area. SELECTEDAREA: * Alpha channel where color indicates selected are. SPOTCOLOR: Alpha channel to * store a spot color. Constant type Values What it means Adobe Photoshop CC * JavaScript Scripting Reference Scripting Constants 200 */ declare enum ChannelType { COMPONENT, MASKEDAREA, SELECTEDAREA, SPOTCOLOR } /** * The way color should be blended in a fill or stroke operation. Pass to * PathItem.fillPath(), Selection.fill(), Selection.stroke() */ declare enum ColorBlendMode { BEHIND, CLEAR, COLOR, COLORBURN, COLORDODGE, DARKEN, DARKERCOLOR, DIFFERENCE, DISSOLVE, EXCLUSION, HARDLIGHT, HARDMIXBLEND, HUE, LIGHTEN, LIGHTERCOLOR, LINEARBURN, LINEARDODGE, LINEARLIGHT, LUMINOSITY, MULTIPLY, NORMAL, OVERLAY, PINLIGHT, SATURATION, SCREEN, SOFTLIGHT, VIVIDLIGHT } /** * The color model to use for a SolidColor. */ declare enum ColorModel { CMYK, GRAYSCALE, HSB, LAB, NONE, RGB } /** * The preferred color-selection tool, set in Preferences. */ declare enum ColorPicker { ADOBE, APPLE, PLUGIN, WINDOWS } /** * The type of color profile used to manage this document, set in * Document.colorProfileType. */ declare enum ColorProfileType { CUSTOM, NONE, WORKING } /** * The color reduction algorithm option for ExportOptionsSaveForWeb. */ declare enum ColorReductionType { ADAPTIVE, BLACKWHITE, CUSTOM, GRAYSCALE, MACINTOSH, PERCEPTUAL, RESTRICTIVE, SELECTIVE, WINDOWS } /** * The type of color space to use in CameraRAWOpenOptions. */ declare enum ColorSpaceType { ADOBERGB, COLORMATCHRGB, PROPHOTORGB, SRGB } /** * The copyright status of a document. Used in * DocumentPrintSettings.copyrighted. Constant type Values What it means Adobe * Photoshop CC JavaScript Scripting Reference Scripting Constants 201 */ declare enum CopyrightedType { COPYRIGHTEDWORK, PUBLICDOMAIN, UNMARKED } /** * The method to use for creating fields. Pass to ArtLayer.applyDeInterlace(). */ declare enum CreateFields { DUPLICATION, INTERPOLATION } /** * The style to use when cropping a page in a PDF document. Set in * PDFOpenOptions.cropPage. */ declare enum CropToType { ARTBOX, BLEEDBOX, BOUNDINGBOX, CROPBOX, MEDIABOX, TRIMBOX } /** * The type of composite DCS file to create with DCS1_SaveOptions or * DCS2_SaveOptions: COLORCOMPOSITE: Creates a color composite file in addition * to DCS files. GRAYSCALECOMPOSITE: Creates a grayscale composite file in * addition to DCS files. NOCOMPOSITE: Does not create a composite file. */ declare enum DCSType { COLORCOMPOSITE, GRAYSCALECOMPOSITE, NOCOMPOSITE } /** * The source to use for the depth map. Pass to ArtLayer.applyLensBlur(). */ declare enum DepthMapSource { IMAGEHIGHLIGHT, LAYERMASK, NONE, TRANSPARENCYCHANNEL } /** * The value type of an action key, returned by ActionDescriptor.getType() and * ActionList.getType(). */ declare enum DescValueType { ALIASTYPE, BOOLEANTYPE, CLASSTYPE, DOUBLETYPE, ENUMERATEDTYPE, INTEGERTYPE, LARGEINTEGERTYPE, LISTTYPE, OBJECTTYPE, RAWTYPE, REFERENCETYPE, STRINGTYPE, UNITDOUBLE } /** * Controls the type of dialogs Photoshop displays when running scripts. */ declare enum DialogModes { ALL, ERROR, NO } /** * ● The direction in which to flip the document canvas, passed to * Document.flipCanvas(). ● The orientation of text in TextItem.direction. ● The * direction of text warping in TextItem.warpDirection. Constant type Values * What it means Adobe Photoshop CC JavaScript Scripting Reference Scripting * Constants 202 */ declare enum Direction { HORIZONTAL, VERTICAL } /** * Describes how the displacement map fits the image if the image is not the * same size as the map. Pass to ArtLayer.applyDisplace(). */ declare enum DisplacementMapType { STRETCHTOFIT, TILE } /** * The type of dithering to use in GIFSaveOptions, IndexedConversionOptions and * ExportOptionsSaveForWeb. */ declare enum Dither { DIFFUSION, NOISE, NONE, PATTERN } /** * The type of positioning to use in DocPosition */ declare enum DocPositionStyle { PRINTCENTERED, USERDEFINED } /** * The fill type of a new document, passed to Documents.add(). */ declare enum DocumentFill { BACKGROUNDCOLOR, TRANSPARENT, WHITE } /** * The color mode of a open document, Document.mode. See also * Document.changeMode(). */ declare enum DocumentMode { BITMAP, CMYK, DUOTONE, GRAYSCALE, INDEXEDCOLOR, LAB, MULTICHANNEL, RGB } /** * The preferred level of detail in th history log, set in Preferences: CONCISE: * Save a concise history log. DETAILED: Save a detailed history log. * SESSIONONLY: Save history log only for the session. */ declare enum EditLogItemsType { CONCISE, DETAILED, SESSIONONLY } /** * The object’s position in the Layers palette. Note: Not all values are valid * for all object types. See the specific object description to make sure you * are using a valid value. */ declare enum ElementPlacement { INSIDE, PLACEATBEGINNING, PLACEATEND, PLACEBEFORE, PLACEAFTER } /** * The type of fields to eliminate. Pass to ArtLayer.applyDeInterlace(). */ declare enum EliminateFields { EVENFIELDS, ODDFIELDS } /** * The type of export for Document.exportDocument(). This is equivalent to * choosing File > Export > Paths To Illustrator, or File > Save For Web and * Devices. */ declare enum ExportType { ILLUSTRATORPATHS, SAVEFORWEB } /** * The policy and format for appending an extension to the filename when saving * with Document.saveAs(). Constant type Values What it means Adobe Photoshop CC * JavaScript Scripting Reference Scripting Constants 203 */ declare enum Extension { LOWERCASE, NONE, UPPERCASE } /** * File naming options for the BatchOptions used with the Application.batch() * method. */ declare enum FileNamingType { DDMM, DDMMYY, DOCUMENTNAMELOWER, DOCUMENTNAMEMIXED, DOCUMENTNAMEUPPER, EXTENSIONLOWER, EXTENSIONUPPER, MMDD, MMDDYY, SERIALLETTERLOWER, SERIALLETTERUPPER, SERIALNUMBER1, SERIALNUMBER2, SERIALNUMBER3, SERIALNUMBER4, YYDDMM, YYMMDD, YYYYMMDD } /** * The preferred type size to use for font previews in the type tool font menus * , set in Preferences. */ declare enum FontPreviewType { HUGE, EXTRALARGE, LARGE, MEDIUM, NONE, SMALL } /** * The preferred type size to use for panels and dialogs, set in Preferences. */ declare enum FontSize { LARGE, MEDIUM, SMALL } /** * The type of colors to be included the color table regardless of their usage. * Used in GIFSaveOptions and IndexedConversionOptions. BLACKWHITE: Pure black * and pure white. NONE: None PRIMARIES: Red, green, blue, cyan, magenta, * yellow, black, and white. WEB: the 216 web-safe colors. */ declare enum ForcedColors { BLACKWHITE, NONE, PRIMARIES, WEB } /** * The option with which to save a JPEG file, in JPEGSaveOptions. * OPTIMIZEDBASELINE: Optimized color and a slightly reduced file size. * PROGRESSIVE: Displays a series of increasingly detailed scans as the image * downloads. STANDARDBASELINE: Format recognized by most web browsers. */ declare enum FormatOptions { OPTIMIZEDBASELINE, PROGRESSIVE, STANDARDBASELINE } /** * The type of proportions to constrain for images. Used in * GalleryImagesOptions. Constant type Values What it means Adobe Photoshop CC * JavaScript Scripting Reference Scripting Constants 204 */ declare enum GalleryConstrainType { CONSTRAINBOTH, CONSTRAINHEIGHT, CONSTRAINWIDTH } /** * The fonts to use for the Web photo gallery captions and other text. Used in * GalleryBannerOptions, GalleryImagesOptions, and GalleryThumbnailOptions. Also * used in PicturePackageOptions. */ declare enum GalleryFontType { ARIAL, COURIERNEW, HELVETICA, TIMESNEWROMAN } /** * The color to use for text displayed over gallery images as an antitheft * deterrent. Used in GallerySecurityOptions. */ declare enum GallerySecurityTextColorType { BLACK, CUSTOM, WHITE } /** * The position of the text displayed over gallery images as an antitheft * deterrent. Used in GallerySecurityOptions. Also used in PicturePackageOptions. */ declare enum GallerySecurityTextPositionType { CENTERED, LOWERLEFT, LOWERRIGHT, UPPERLEFT, UPPERRIGHT } /** * The orientation of the text displayed over gallery images as an antitheft * deterrent. Used in GallerySecurityOptions. Also used in PicturePackageOptions. */ declare enum GallerySecurityTextRotateType { CLOCKWISE45, CLOCKWISE90, COUNTERCLOCKWISE45, COUNTERCLOCKWISE90, ZERO } /** * The content to use for text displayed over gallery images as an antitheft * deterrent. Used in GallerySecurityOptions. Note: All types draw from the * image’s file information except CUSTOMTEXT. */ declare enum GallerySecurityType { CAPTION, COPYRIGHT, CREDIT, CUSTOMTEXT, FILENAME, NONE, TITLE } /** * The size of thumbnail images in the web photo gallery. Used in * GalleryThumbnailOptions. */ declare enum GalleryThumbSizeType { CUSTOM, LARGE, MEDIUM, SMALL } /** * Geometric options for shapes, such as the iris shape in the Lens Blur Filter. * Pass to ArtLayer.applyLensBlur(). */ declare enum Geometry { HEPTAGON, HEXAGON, OCTAGON, PENTAGON, SQUARE, TRIANGLE } /** * The preferred line style for the nonprinting grid displayed over images, set * in Preferences. */ declare enum GridLineStyle { DASHED, DOTTED, SOLID } /** * The preferred size of grid line spacing, set in Preferences. Constant type * Values What it means Adobe Photoshop CC JavaScript Scripting Reference * Scripting Constants 205 */ declare enum GridSize { LARGE, MEDIUM, NONE, SMALL } /** * The preferred line style for nonprinting guides displayed over images, set in * Preferences. */ declare enum GuideLineStyle { DASHED, SOLID } /** * The paths to export to an Illustrator file using Document.exportDocument(). */ declare enum IllustratorPathType { ALLPATHS, DOCUMENTBOUNDS, NAMEDPATH } /** * The rendering intent to use when converting from one color space to another * with Document.convertProfile() or Document.print() */ declare enum Intent { ABSOLUTECOLORIMETRIC, PERCEPTUAL, RELATIVECOLORIMETRIC, SATURATION } /** * The placement of paragraph text within the bounding box. Used in * TextItem.justification. */ declare enum Justification { CENTER, CENTERJUSTIFIED, FULLYJUSTIFIED, LEFT, LEFTJUSTIFIED, RIGHT, RIGHTJUSTIFIED } /** * The language to use for text. Used in TextItem.language. */ declare enum Language { BRAZILLIANPORTUGUESE, CANADIANFRENCH, DANISH, DUTCH, ENGLISHUK, ENGLISHUSA, FINNISH, FRENCH, GERMAN, ITALIAN, NORWEGIAN, NYNORSKNORWEGIAN, OLDGERMAN, PORTUGUESE, SPANISH, SWEDISH, SWISSGERMAN } /** * Compression methods for data for pixels in layers, when saving to TIFF * format. Used in TiffSaveOptions. Constant type Values What it means Adobe * Photoshop CC JavaScript Scripting Reference Scripting Constants 206 */ declare enum LayerCompression { RLE, ZIP } /** * The type of a layer object, in ArtLayer.kind. Note: You can create a text * layer only from an empty art layer. */ declare enum LayerKind { BLACKANDWHITE, BRIGHTNESSCONTRAST, CHANNELMIXER, COLORBALANCE, CURVES, EXPOSURE, GRADIENTFILL, GRADIENTMAP, HUESATURATION, INVERSION, LEVELS, NORMAL, PATTERNFILL, PHOTOFILTER, POSTERIZE, SELECTIVECOLOR, SMARTOBJECT, SOLIDFILL, TEXT, THRESHOLD, LAYER3D, VIBRANCE, VIDEO } /** * The type of lens to use. Pass to ArtLayer.applyLensFlare(). */ declare enum LensType { MOVIEPRIME, PRIME105, PRIME35, ZOOMLENS } /** * The type of magnification to use when viewing an image. Used in * PresentationOptions. */ declare enum MagnificationType { ACTUALSIZE, FITPAGE } /** * The color to use to fill anti-aliased edges adjacent to transparent areas of * the image. When transparency is turned off for an image, the matte color is * applied to transparent areas. Used in GIFSaveOptions, * IndexedConversionOptions, and JPEGSaveOptions. */ declare enum MatteType { BACKGROUND, BLACK, FOREGROUND, NETSCAPE, NONE, SEMIGRAY, WHITE } /** * The measurement to act upon. Pass to MeasurementLog methods. */ declare enum MeasurementRange { ALLMEASUREMENTS, ACTIVEMEASUREMENTS } /** * The source for recording measurements. Pass to Document.recordMeasurements(). */ declare enum MeasurementSource { MEASURESELECTION, MEASURECOUNTTOOL, MEASURERULERTOOL } /** * The color profile to use for a new document. Pass to Documents.add(). Also * used in ContactSheetOptions and PicturePackageOptions. Constant type Values * What it means Adobe Photoshop CC JavaScript Scripting Reference Scripting * Constants 207 */ declare enum NewDocumentMode { BITMAP, CMYK, GRAYSCALE, LAB, RGB } /** * Distribution method to use when applying an Add Noise filter. Pass to * ArtLayer.applyAddNoise(). */ declare enum NoiseDistribution { GAUSSIAN, UNIFORM } /** * Method to use to fill the empty space left by offsetting a an image or * selection. Pass to ArtLayer.applyOffset(). */ declare enum OffsetUndefinedAreas { REPEATEDGEPIXELS, SETTOBACKGROUND, WRAPAROUND } /** * The color profile to use when opening an EPS or PDF document. Pass to * app.open() in EPSOpenOptions or PDFOpenOptions. */ declare enum OpenDocumentMode { CMYK, GRAYSCALE, LAB, RGB } /** * The format in which to open the document, using app.open(). Note: PHOTOCD is * deprecated. Kodak PhotoCD is now found in the Goodies folder on the Adobe * Photoshop CC Install DVD. Note: The DICOM option is for the Extended version * only. */ declare enum OpenDocumentType { ALIASPIX, BMP, CAMERARAW, COMPUSERVEGIF, DICOM, ELECTRICIMAGE, EPS, EPSPICTPREVIEW, EPSTIFFPREVIEW, FILMSTRIP, JPEG, PCX, PDF, PHOTOCD, PHOTOSHOP, PHOTOSHOPDCS_1, PHOTOSHOPDCS_2, PHOTOSHOPEPS, PHOTOSHOPPDF, PICTFILEFORMAT, PICTRESOURCEFORMAT, PIXAR, PNG, PORTABLEBITMAP, RAW, SCITEXCT, SGIRGB, SOFTIMAGE, TARGA, TIFF, WAVEFRONTRLA, WIRELESSBITMAP } /** * The target operating system in BMPSaveOptions. */ declare enum OperatingSystem { OS2, WINDOWS } /** * Page orientation for PhotoCDOpenOptions, deprecated in Photoshop CS3. Note: * Kodak PhotoCD is now found in the Goodies folder on the Adobe Photoshop CC * Install DVD. Constant type Values What it means Adobe Photoshop CC JavaScript * Scripting Reference Scripting Constants 208 */ declare enum Orientation { LANDSCAPE, PORTRAIT } /** * The preferred pointer for the following tools: Eraser, Pencil, Paintbrush, * Healing Brush, Rubber Stamp, Pattern Stamp, Smudge, Blur, Sharpen, Dodge, * Burn, Sponge. Set in Preferences. */ declare enum OtherPaintingCursors { PRECISEOTHER, STANDARDOTHER } /** * The preferred pointer for the following tools: Marquee, Lasso, Polygonal * Lasso, Magic Wand, Crop, Slice, Patch Eyedropper, Pen, Gradient, Line, Paint * Bucket, Magnetic Lasso, Magnetic Pen, Freeform Pen, Measure, Color Sampler. * Set in Preferences. */ declare enum PaintingCursors { BRUSHSIZE, PRECISE, STANDARD } /** * The palette type to use in GIFSaveOptions and IndexedConversionOptions. */ declare enum PaletteType { EXACT, LOCALADAPTIVE, LOCALPERCEPTUAL, LOCALSELECTIVE, MACOSPALETTE, MASTERADAPTIVE, MASTERPERCEPTUAL, MASTERSELECTIVE, PREVIOUSPALETTE, UNIFORM, WEBPALETTE, WINDOWSPALETTE } /** * The type of a PathItem. */ declare enum PathKind { CLIPPINGPATH, NORMALPATH, TEXTMASK, VECTORMASK, WORKPATH } /** * The PDF version to make the document compatible with. Used in PDFSaveOptions. */ declare enum PDFCompatibility { PDF13, PDF14, PDF15, PDF16, PDF17 } /** * The type of compression to use when saving a document in PDF format. Used in * PDFSaveOptions. Constant type Values What it means Adobe Photoshop CC * JavaScript Scripting Reference Scripting Constants 209 */ declare enum PDFEncoding { JPEG, JPEG2000HIGH, JPEG2000LOSSLESS, JPEG2000LOW, JPEG2000MED, JPEG2000MEDHIGH, JPEG2000MEDLOW, JPEGHIGH, JPEGLOW, JPEGMED, JPEGMEDHIGH, JPEGMEDLOW, NONE, PDFZIP, PDFZIP4BIT } /** * The down sample method to use. Used in PDFSaveOptions. */ declare enum PDFResample { NONE, PDFAVERAGE, PDFBICUBIC, PDFSUBSAMPLE } /** * The PDF standard to make the document compatible with. Used in PDFSaveOptions. */ declare enum PDFStandard { NONE, PDFX1A2001, PDFX1A2003, PDFX32002, PDFX32003, PDFX42008 } /** * The color space for PhotoCDOpenOptions, deprecated in Photoshop CS3. Note: * Kodak PhotoCD is now found in the Goodies folder on the Adobe Photoshop CC * Install DVD. */ declare enum PhotoCDColorSpace { LAB16, LAB8, RGB16, RGB8 } /** * The pixel dimensions of the image in PhotoCDOpenOptions, deprecated in * Photoshop CS3. EXTRALARGE = 1024x1536 LARGE = 512x768 MAXIMUM = 2048x3072 * MEDIUM = 256x384 MINIMUM = 64x96 SMALL = 128x192 Note: Kodak PhotoCD is now * found in the Goodies folder on the Adobe Photoshop CC Install DVD. */ declare enum PhotoCDSize { EXTRALARGE, LARGE, MAXIMUM, MEDIUM, MINIMUM, SMALL } /** * The number of bits per pixel to use when compression a PICT file. Used in * PICTFileSaveOptions and PICTResourceSaveOptions. Note: Use 16 or 32 for RGB * images; use 2, 4, or 8 for bitmap and grayscale images. */ declare enum PICTBitsPerPixels { EIGHT, FOUR, SIXTEEN, THIRTYTWO, TWO } /** * The type of compression to use when saving an image as a PICT file. Used in * PICTFileSaveOptions and PICTResourceSaveOptions. */ declare enum PICTCompression { JPEGHIGHPICT, JPEGLOWPICT, JPEGMAXIMUMPICT, JPEGMEDIUMPICT, NONE } /** * The function or meaning of text in a Picture Package. Used in * PicturePackageOptions. Constant type Values What it means Adobe Photoshop CC * JavaScript Scripting Reference Scripting Constants 210 */ declare enum PicturePackageTextType { CAPTION, COPYRIGHT, CREDIT, FILENAME, NONE, ORIGIN, USER } /** * The role a PathPoint plays in a PathItem. */ declare enum PointKind { CORNERPOINT, SMOOTHPOINT } /** * The preferred measurement to use for type points, set in * Preferences.pointSize: POSTSCRIPT = 72 points/inch. TRADITIONAL = 72.27 * points/inch. */ declare enum PointType { POSTSCRIPT, TRADITIONAL } /** * The method of polar distortion to use. Pass to * ArtLayer.applyPolarCoordinates(). */ declare enum PolarConversionType { POLARTORECTANGULAR, RECTANGULARTOPOLAR } /** * The type of image to use as a low-resolution preview in the destination * application. Used in DCS1_SaveOptions, DCS2_SaveOptions, and EPSSaveOptions. */ declare enum Preview { EIGHTBITTIFF, MACOSEIGHTBIT, MACOSJPEG, MACOSMONOCHROME, MONOCHROMETIFF, NONE } /** * The type of color handling to use for ColorHandling */ declare enum PrintColorHandling { PRINTERMANAGED, PHOTOSHOPMANAGED, SEPARATIONS } /** * Cache to be targeted in an Application.purge() operation. */ declare enum PurgeTarget { ALLCACHES, CLIPBOARDCACHE, HISTORYCACHES, UNDOCACHES } /** * The preferred policy for checking whether to maximize compatibility when * opening PSD files, set in Preferences.maximizeCompatibility. */ declare enum QueryStateType { ALWAYS, ASK, NEVER } /** * The blur method to use. Pass to ArtLayer.applyRadialBlur(). */ declare enum RadialBlurMethod { SPIN, ZOOM } /** * The smoothness or graininess of the blurred image. Pass to * ArtLayer.applyRadialBlur(). */ declare enum RadialBlurQuality { BEST, DRAFT, GOOD } /** * The layer element to rasterize, using ArtLayer.rasterize(). */ declare enum RasterizeType { ENTIRELAYER, FILLCONTENT, LAYERCLIPPINGPATH, LINKEDLAYERS, SHAPE, TEXTCONTENTS } /** * The type of an ActionReference object, returned by getForm(). Constant type * Values What it means Adobe Photoshop CC JavaScript Scripting Reference * Scripting Constants 211 */ declare enum ReferenceFormType { CLASSTYPE, ENUMERATED, IDENTIFIER, INDEX, NAME, OFFSET, PROPERTY } /** * The method to use for image interpolation. Passed to Document.resizeImage(), * and used as the value of Preferences.interpolation. */ declare enum ResampleMethod { AUTOMATIC, BICUBIC, BICUBICAUTOMATIC, BICUBICSHARPER, BICUBICSMOOTHER, BILINEAR, NEARESTNEIGHBOR, NONE, PRESERVEDETAILS } /** * The size of undulations to use. Pass to ArtLayer.applyRipple(). */ declare enum RippleSize { LARGE, MEDIUM, SMALL } /** * The application’s preferred behavior when saving a document. See * Preferences.appendExtension and imagePreviews */ declare enum SaveBehavior { ALWAYSSAVE, ASKWHENSAVING, NEVERSAVE } /** * The format in which to save a document when exporting with * Document.exportDocument(). Pass in ExportOptionsSaveForWeb.format, to to * specify the type of file to write. Only the following are supported for * export: COMPUSERVEGIF, JPEG, PNG-8, PNG-24, and BMP. */ declare enum SaveDocumentType { ALIASPIX, BMP, COMPUSERVEGIF, ELECTRICIMAGE, JPEG, PCX, PHOTOSHOP, PHOTOSHOPDCS_1, PHOTOSHOPDCS_2, PHOTOSHOPEPS, PHOTOSHOPPDF, PICTFILEFORMAT, PICTRESOURCEFORMAT, PIXAR, PNG, PORTABLEBITMAP, RAW, SCITEXCT, SGIRGB, SOFTIMAGE, TARGA, TIFF, WAVEFRONTRLA, WIRELESSBITMAP } /** * The type of encoding to use when saving a file to DCS or EPS with * Document.saveAs(). */ declare enum SaveEncoding { ASCII, BINARY, JPEGHIGH, JPEGLOW, JPEGMAXIMUM, JPEGMEDIUM } /** * The preferred location of history log data, set in Preferences.saveLogItems. */ declare enum SaveLogItemsType { LOGFILE, LOGFILEANDMETADATA, METADATA } /** * The policy for closing a document with Document.close(). Constant type Values * What it means Adobe Photoshop CC JavaScript Scripting Reference Scripting * Constants 212 */ declare enum SaveOptions { DONOTSAVECHANGES, PROMPTTOSAVECHANGES, SAVECHANGES } /** * The selection behavior when a selection already exists: DIMINISH: Remove the * selection from the already selected area. EXTEND: Add the selection to an * already selected area. INTERSECT: Make the selection only the area where the * new selection intersects the already selected area. REPLACE: Replace the * selected area. Used in PathItem.makeSelection(), Selection.load(), * Selection.select(), and Selection.store(). */ declare enum SelectionType { DIMINISH, EXTEND, INTERSECT, REPLACE } /** * How to combine the shapes if the destination path already has a selection. * Set for SubPathInfo.operation, stored in the resulting SubPathItem. */ declare enum ShapeOperation { SHAPEADD, SHAPEINTERSECT, SHAPESUBTRACT, SHAPEXOR } /** * The method to use for smart blurring: EDGEONLY, OVERLAYEDGES: Apply blur only * to edges of color transitions. NORMAL: Apply blur to entire image. Pass to * ArtLayer.applySmartBlur(). */ declare enum SmartBlurMode { EDGEONLY, NORMAL, OVERLAYEDGE } /** * The blur quality to use. Pass to ArtLayer.applySmartBlur(). */ declare enum SmartBlurQuality { HIGH, LOW, MEDIUM } /** * The color space for source when printing with Document.print(). */ declare enum SourceSpaceType { DOCUMENT, PROOF } /** * The curve (or stretch shape) to use for the distortion. Pass to * ArtLayer.applySpherize(). */ declare enum SpherizeMode { HORIZONTAL, NORMAL, VERTICAL } /** * The style of strikethrough to use in text. Used in TextItem.strikeThru. */ declare enum StrikeThruType { STRIKEBOX, STRIKEHEIGHT, STRIKEOFF } /** * The placement of path or selection boundary strokes. Pass to * Selection.stroke(). */ declare enum StrokeLocation { CENTER, INSIDE, OUTSIDE } /** * The resolution to use when saving an image in Targa format. Used in * TargaSaveOptions. Constant type Values What it means Adobe Photoshop CC * JavaScript Scripting Reference Scripting Constants 213 */ declare enum TargaBitsPerPixels { SIXTEEN, THIRTYTWO, TWENTYFOUR } /** * The capitalization style to use in text. Used in TextItem.capitalization. */ declare enum TextCase { ALLCAPS, NORMAL, SMALLCAPS } /** * The composition method to use to optimize the specified hyphenation and * justification options. Used in TextItem.textComposer. */ declare enum TextComposer { ADOBEEVERYLINE, ADOBESINGLELINE } /** * The type of text, used in TextItem.kind. PARAGRAPHTEXT: Text that wraps * within a bounding box. POINTTEXT: Text that does not wrap. */ declare enum TextType { PARAGRAPHTEXT, POINTTEXT } /** * The type of texture or glass surface image to load for a texturizer or glass * filter. Pass to ArtLayer.applyGlassEffect(). */ declare enum TextureType { BLOCKS, CANVAS, FILE, FROSTED, TINYLENS } /** * The type of compression to use for TIFF files. Used in TiffSaveOptions. */ declare enum TIFFEncoding { JPEG, NONE, TIFFLZW, TIFFZIP } /** * The tool to use with PathItem.strokePath(). */ declare enum ToolType { ARTHISTORYBRUSH, BACKGROUNDERASER, BLUR, BRUSH, BURN, CLONESTAMP, COLORREPLACEMENTTOOL, DODGE, ERASER, HEALINGBRUSH, HISTORYBRUSH, PATTERNSTAMP, PENCIL, SHARPEN, SMUDGE, SPONGE } /** * The method to use for transition from one image to the next in a PDF * presentation. Used in PresentationOptions. Constant type Values What it means * Adobe Photoshop CC JavaScript Scripting Reference Scripting Constants 214 */ declare enum TransitionType { BLINDSHORIZONTAL, BLINDSVERTICAL, BOXIN, BOXOUT, DISSOLVE, GLITTERDOWN, GLITTERRIGHT, GLITTERRIGHTDOWN, NONE, RANDOM, SPLITHORIZONTALIN, SPLITHORIZONTALOUT, SPLITVERTICALIN, SPLITVERTICALOUT, WIPEDOWN, WIPELEFT, WIPERIGHT, WIPEUP } /** * Type of pixels to trim around an image, passed to Document.trim().: * BOTTOMRIGHT = bottom right pixel color. TOPLEFT = top left pixel color. */ declare enum TrimType { BOTTOMRIGHT, TOPLEFT, TRANSPARENT } /** * The preferred unit for text character measurements, set in Preferences. */ declare enum TypeUnits { MM, PIXELS, POINTS } /** * The method to use to treat undistorted areas or areas left blank in an image * to which the a filter in the Distort category has been applied. Pass to * ArtLayer.applyDisplace(), applyShear(), applyWave(). */ declare enum UndefinedAreas { REPEATEDGEPIXELS, WRAPAROUND } /** * The placement of text underlining. Used in TextItem.underline. Note: * UNDERLINELEFT and UNDELINERIGHT are valid only when direction = * Direction.VERTICAL. */ declare enum UnderlineType { UNDERLINELEFT, UNDERLINEOFF, UNDERLINERIGHT } /** * The preferred measurement unit for type and ruler increments, set in * Preferences.rulerUnits. */ declare enum Units { CM, INCHES, MM, PERCENT, PICAS, PIXELS, POINTS } /** * The editorial urgency status of a document, set in * DocumentPrintSettings.urgency. */ declare enum Urgency { FOUR, HIGH, LOW, NONE, NORMAL, SEVEN, SIX, THREE, TWO } /** * The warp style to use for text. Used in TextItem.warpStyle. Constant type * Values What it means Adobe Photoshop CC JavaScript Scripting Reference * Scripting Constants 215 */ declare enum WarpStyle { ARC, ARCH, ARCLOWER, ARCUPPER, BULGE, FISH, FISHEYE, FLAG, INFLATE, NONE, RISE, SHELLLOWER, SHELLUPPER, SQUEEZE, TWIST, WAVE } /** * The type of wave to use. Pass to ArtLayer.applyWave(). */ declare enum WaveType { SINE, SQUARE, TRIANGULAR } /** * Lighting conditions that affect color balance. Set in CameraRAWOpenOptions. */ declare enum WhiteBalanceType { ASSHOT, AUTO, CLOUDY, CUSTOM, DAYLIGHT, FLASH, FLUORESCENT, SHADE, TUNGSTEN } /** * The method of zigzagging to use. Pass to ArtLayer.applyZigZag(). */ declare enum ZigZagType { AROUNDCENTER, OUTFROMCENTER, PONDRIPPLES }
the_stack
(function script_init() { "use strict"; const sparser:sparser = global.sparser, script = function lexer_script(source:string):data { let a:number = 0, ltoke:string = "", ltype:string = "", lword:Array<[string, number]> = [], pword:any[] = [], lengthb:number = 0, wordTest:number = -1, paren:number = -1, funreferences:string[] = [], tempstore:record, pstack:[string, number], comment:[string, number]; const parse:parse = sparser.parse, data:data = parse.data, options:any = sparser.options, sourcemap:[number, string] = [ 0, "" ], references:string[][] = parse.references, b:number = source.length, c:string[] = source.split(""), brace:string[] = [], classy:number[] = [], datatype:boolean[] = [false], // identify variable declarations vart = { count: [], index: [], len : -1, word : [] }, // automatic semicolon insertion asi = function lexer_script_asi(isEnd:boolean):void { let aa:number = 0; const next:string = nextchar(1, false), record:record = { begin: data.begin[parse.count], ender: data.begin[parse.count], lexer: data.lexer[parse.count], lines: data.lines[parse.count], stack: data.stack[parse.count], token: data.token[parse.count], types: data.types[parse.count] }, clist:string = (parse.structure.length === 0) ? "" : parse.structure[parse.structure.length - 1][0]; if ((/^(\/(\/|\*)\s*parse-ignore\u002dstart)/).test(ltoke) === true) { return; } if (ltype === "start" || ltype === "type_start") { return; } if (options.language === "json" || options.language === "java" || options.language === "csharp") { return; } if (options.language === "json" || record.token === ";" || record.token === "," || next === "{" || record.stack === "class" || record.stack === "map" || record.stack === "attribute" || clist === "initializer" || data.types[record.begin - 1] === "generic") { return; } if (record.token === "}" && data.stack[record.begin - 1] === "global" && data.types[record.begin - 1] !== "operator" && record.stack === data.stack[parse.count - 1]) { return; } if (record.stack === "array" && record.token !== "]") { return; } if (data.token[data.begin[parse.count]] === "{" && record.stack === "data_type") { return; } if (record.types !== undefined && record.types.indexOf("template") > -1 && record.types.indexOf("template_string") < 0) { return; } if (next === ";" && isEnd === false) { return; } if (data.lexer[parse.count - 1] !== "script" && ((a < b && b === options.source.length - 1) || b < options.source.length - 1)) { return; } if (options.language === "qml") { if (record.types === "start") { return; } ltoke = (options.correct === true) ? ";" : "x;"; ltype = "separator"; recordPush(""); if (next !== "}") { blockinsert(); } return; } if (record.token === "}" && (record.stack === "function" || record.stack === "if" || record.stack === "else" || record.stack === "for" || record.stack === "do" || record.stack === "while" || record.stack === "switch" || record.stack === "class" || record.stack === "try" || record.stack === "catch" || record.stack === "finally" || record.stack === "block")) { if (record.stack === "function" && (data.stack[record.begin - 1] === "data_type" || data.types[record.begin - 1] === "type")) { aa = record.begin; do { aa = aa - 1; } while (aa > 0 && data.token[aa] !== ")" && data.stack[aa] !== "arguments"); aa = data.begin[aa]; } else { aa = data.begin[record.begin - 1]; } if (data.token[aa] === "(") { aa = aa - 1; if (data.token[aa - 1] === "function") { aa = aa - 1; } if (data.stack[aa - 1] === "object" || data.stack[aa - 1] === "switch") { return; } if (data.token[aa - 1] !== "=" && data.token[aa - 1] !== "return" && data.token[aa - 1] !== ":") { return; } } else { return; } } if ( record.types === "comment" || clist === "method" || clist === "paren" || clist === "expression" || clist === "array" || clist === "object" || (clist === "switch" && record.stack !== "method" && data.token[data.begin[parse.count]] === "(" && data.token[data.begin[parse.count] - 1] !== "return" && data.types[data.begin[parse.count] - 1] !== "operator")) { return; } if (data.stack[parse.count] === "expression" && (data.token[data.begin[parse.count] - 1] !== "while" || (data.token[data.begin[parse.count] - 1] === "while" && data.stack[data.begin[parse.count] - 2] !== "do"))) { return; } if (next !== "" && "=<>+*?|^:&%~,.()]".indexOf(next) > -1 && isEnd === false) { return; } if (record.types === "comment") { aa = parse.count; do { aa = aa - 1; } while ( aa > 0 && data.types[aa] === "comment" ); if (aa < 1) { return; } record.token = data.token[aa]; record.types = data.types[aa]; record.stack = data.stack[aa]; } if (record.token === undefined || record.types === "start" || record.types === "separator" || (record.types === "operator" && record.token !== "++" && record.token !== "--") || record.token === "x}" || record.token === "var" || record.token === "let" || record.token === "const" || record.token === "else" || record.token.indexOf("#!/") === 0 || record.token === "instanceof") { return; } if (record.stack === "method" && (data.token[record.begin - 1] === "function" || data.token[record.begin - 2] === "function")) { return; } if (options.lexer_options.script.variable_list === "list") { vart.index[vart.len] = parse.count; } ltoke = (options.correct === true) ? ";" : "x;"; ltype = "separator"; aa = parse.linesSpace; parse.linesSpace = 0; recordPush(""); parse.linesSpace = aa; blockinsert(); }, // fixes asi location if inserted after an inserted brace asibrace = function lexer_script_asibrace():void { let aa:number = parse.count; do { aa = aa - 1; } while (aa > -1 && data.token[aa] === "x}"); if (data.stack[aa] === "else") { return recordPush(""); } aa = aa + 1; parse.splice({ data : data, howmany: 0, index : aa, record : { begin: data.begin[aa], ender: -1, lexer: "script", lines: parse.linesSpace, stack: data.stack[aa], token: ltoke, types: ltype } }); recordPush(""); }, // cleans up improperly applied ASI asifix = function lexer_script_asifix():void { let len:number = parse.count; if (data.types[len] === "comment") { do { len = len - 1; } while ( len > 0 && data.types[len] === "comment" ); } if (data.token[len] === "from") { len = len - 2; } if (data.token[len] === "x;") { parse.splice( {data: data, howmany: 1, index: len} ); } }, // block comments blockComment = function lexer_script_blockComment() { asi(false); if (wordTest > -1) { word(); } comment = parse.wrapCommentBlock({ chars: c, end: b, lexer: "script", opening: "/*", start: a, terminator: "\u002a/" }); a = comment[1]; if (data.token[parse.count] === "var" || data.token[parse.count] === "let" || data.token[parse.count] === "const") { tempstore = parse.pop(data); recordPush(""); parse.push(data, tempstore, ""); if (data.lines[parse.count - 2] === 0) { data.lines[parse.count - 2] = data.lines[parse.count]; } data.lines[parse.count] = 0; } else if (comment[0] !== "") { ltoke = comment[0]; ltype = (/^\/\*\s*parse-ignore-start/).test(ltoke) ? "ignore" : "comment"; if (ltoke.indexOf("# sourceMappingURL=") === 2) { sourcemap[0] = parse.count + 1; sourcemap[1] = ltoke; } parse.push(data, { begin: parse.structure[parse.structure.length - 1][1], ender: -1, lexer: "script", lines: parse.linesSpace, stack: parse.structure[parse.structure.length - 1][0], token: ltoke, types: ltype }, ""); } if ((/\/\*\s*global\s+/).test(data.token[parse.count]) === true && data.types.indexOf("word") < 0) { references[0] = data.token[parse.count].replace(/\/\*\s*global\s+/, "").replace("\u002a/", "").replace(/,\s+/g, ",").split(","); } }, // inserts ending curly brace (where absent) blockinsert = function lexer_script_blockinsert():void { let next:string = nextchar(5, false), name:string = ""; const g:number = parse.count, lines:number = parse.linesSpace; if (options.language === "json" || brace.length < 1 || brace[brace.length - 1].charAt(0) !== "x" || (/^x?(;|\}|\))$/).test(ltoke) === false) { return; } if (data.stack[parse.count] === "do" && next === "while" && data.token[parse.count] === "}") { return; } if (ltoke === ";" && data.token[g - 1] === "x{") { name = data.token[data.begin[g - 2] - 1]; if (data.token[g - 2] === "do" || (data.token[g - 2] === ")" && "ifforwhilecatch".indexOf(name) > -1)) { tempstore = parse.pop(data); ltoke = (options.correct === true) ? "}" : "x}"; ltype = "end"; pstack = parse.structure[parse.structure.length - 1]; recordPush(""); brace.pop(); parse.linesSpace = lines; return; } // to prevent the semicolon from inserting between the braces --> while (x) {}; tempstore = parse.pop(data); ltoke = (options.correct === true) ? "}" : "x}"; ltype = "end"; pstack = parse.structure[parse.structure.length - 1]; recordPush(""); brace.pop(); ltoke = ";"; ltype = "end"; parse.push(data, tempstore, ""); parse.linesSpace = lines; return; } ltoke = (options.correct === true) ? "}" : "x}"; ltype = "end"; if (data.token[parse.count] === "x}") { return; } if (data.stack[parse.count] === "if" && (data.token[parse.count] === ";" || data.token[parse.count] === "x;") && next === "else") { pstack = parse.structure[parse.structure.length - 1]; recordPush(""); brace.pop(); parse.linesSpace = lines; return; } do { pstack = parse.structure[parse.structure.length - 1]; recordPush(""); brace.pop(); if (data.stack[parse.count] === "do") { break; } } while (brace[brace.length - 1] === "x{"); parse.linesSpace = lines; }, // commaComment ensures that commas immediately precede comments instead of // immediately follow commaComment = function lexer_script_commacomment():void { let x:number = parse.count; if (data.stack[x] === "object" && options.lexer_options.script.object_sort === true) { ltoke = ","; ltype = "separator"; asifix(); recordPush(""); } else { do { x = x - 1; } while ( x > 0 && data.types[x - 1] === "comment" ); parse.splice({ data : data, howmany: 0, index : x, record : { begin: data.begin[x], ender: -1, lexer: "script", lines: parse.linesSpace, stack: data.stack[x], token: ",", types: "separator" } }); recordPush(""); } }, // operations for end types: ), ], } end = function lexer_script_end(x:string):void { let insert:boolean = false, newarr:boolean = false; const next:string = nextchar(1, false), count:number = (data.token[parse.count] === "(") ? parse.count : data.begin[parse.count], newarray = function lexer_script_end_newarray():void { let arraylen:number = 0; const ar:boolean = (data.token[count - 1] === "Array"), startar:string = (ar === true) ? "[" : "{", endar:string = (ar === true) ? "]" : "}", namear:string = (ar === true) ? "array" : "object"; if (ar === true && data.types[parse.count] === "number") { arraylen = Number(data.token[parse.count]); tempstore = parse.pop(data); } tempstore = parse.pop(data); tempstore = parse.pop(data); tempstore = parse.pop(data); parse.structure.pop(); ltoke = startar; ltype = "start"; recordPush(namear); if (arraylen > 0) { ltoke = ","; ltype = "separator"; do { recordPush(""); arraylen = arraylen - 1; } while (arraylen > 0); } ltoke = endar; ltype = "end"; recordPush(""); }; if (wordTest > -1) { word(); } if (classy.length > 0) { if (classy[classy.length - 1] === 0) { classy.pop(); } else { classy[classy.length - 1] = classy[classy.length - 1] - 1; } } if (x === ")" || x === "x)" || x === "]") { if (options.correct === true) { plusplus(); } asifix(); } if (x === ")" || x === "x)") { asi(false); } if (vart.len > -1) { if (x === "}" && ((options.lexer_options.script.variable_list === "list" && vart.count[vart.len] === 0) || (data.token[parse.count] === "x;" && options.lexer_options.script.variable_list === "each"))) { vartpop(); } vart.count[vart.len] = vart.count[vart.len] - 1; if (vart.count[vart.len] < 0) { vartpop(); } } if (ltoke === "," && data.stack[parse.count] !== "initializer" && ((x === "]" && data.token[parse.count - 1] === "[") || x === "}")) { tempstore = parse.pop(data); } if (x === ")" || x === "x)") { ltoke = x; if (lword.length > 0) { pword = lword[lword.length - 1]; if (pword.length > 1 && next !== "{" && (pword[0] === "if" || pword[0] === "for" || (pword[0] === "while" && data.stack[pword[1] - 2] !== undefined && data.stack[pword[1] - 2] !== "do") || pword[0] === "with")) { insert = true; } } } else if (x === "]") { ltoke = "]"; } else if (x === "}") { if (ltoke !== "," && options.correct === true) { plusplus(); } if (parse.structure.length > 0 && parse.structure[parse.structure.length - 1][0] !== "object") { asi(true); } if (options.lexer_options.script.object_sort === true && parse.structure[parse.structure.length - 1][0] === "object") { parse.object_sort(data); } if (ltype === "comment") { ltoke = data.token[parse.count]; ltype = data.types[parse.count]; } ltoke = "}"; } if (parse.structure[parse.structure.length - 1][0] === "data_type") { ltype = "type_end"; } else { ltype = "end"; } lword.pop(); pstack = parse.structure[parse.structure.length - 1]; if (x === ")" && options.correct === true && count - parse.count < 2 && (data.token[parse.count] === "(" || data.types[parse.count] === "number") && (data.token[count - 1] === "Array" || data.token[count - 1] === "Object") && data.token[count - 2] === "new") { newarray(); newarr = true; } if (brace[brace.length - 1] === "x{" && x === "}") { blockinsert(); brace.pop(); if (data.stack[parse.count] !== "try") { if (next !== ":" && next !== ";" && data.token[data.begin[a] - 1] !== "?") { blockinsert(); } } ltoke = "}"; } else { brace.pop(); } // options.end_comma if (options.lexer_options.script.end_comma !== undefined && options.lexer_options.script.end_comma !== "none" && parse.structure[parse.structure.length - 1][0] === "array" || parse.structure[parse.structure.length - 1][0] === "object" || parse.structure[parse.structure.length - 1][0] === "data_type") { if (options.lexer_options.script.end_comma === "always" && data.token[parse.count] !== ",") { const begin:number = parse.structure[parse.structure.length - 1][1]; let y:number = parse.count; do { if (data.begin[y] === begin) { if (data.token[y] === ",") { break; } } else { y = data.begin[y]; } y = y - 1; } while (y > begin); if (y > begin) { const type:string = ltype, toke:string = ltoke; ltoke = ","; ltype = "separator"; recordPush(""); ltoke = toke; ltype = type; } } else if (options.lexer_options.script.end_comma === "never" && data.token[parse.count] === ",") { parse.pop(data); } } if (newarr === false) { recordPush(""); if (ltoke === "}" && data.stack[parse.count] !== "object" && data.stack[parse.count] !== "class" && data.stack[parse.count] !== "data_type") { references.pop(); blockinsert(); } } if (insert === true) { ltoke = (options.correct === true) ? "{" : "x{"; ltype = "start"; recordPush(pword[0]); brace.push("x{"); pword[1] = parse.count; } datatype.pop(); if (parse.structure[parse.structure.length - 1][0] !== "data_type") { datatype[datatype.length - 1] = false; } }, // the general function is a generic tokenizer start argument contains the // token's starting syntax offset argument is length of start minus control // chars end is how is to identify where the token ends general = function lexer_script_general(starting:string, ending:string, type:string):void { let ee:number = 0, escape:boolean = false, ext:boolean = false, build:string[] = [starting], ender:string[] = ending.split(""), temp:[string, string]; const endlen:number = ender.length, start:number = a, qc:"none"|"double"|"single" = (options.lexer_options.script.quote_convert === undefined) ? "none" : options.lexer_options.script.quote_convert, base:number = a + starting.length, cleanUp = function lexer_script_general_cleanUp():void { let linesSpace:number = 0; build = []; ltype = type; ee = a; if (type === "string" && (/\s/).test(c[ee + 1]) === true) { linesSpace = 1; do { ee = ee + 1; if (c[ee] === "\n") { linesSpace = linesSpace + 1; } } while (ee < b && (/\s/).test(c[ee + 1]) === true); parse.linesSpace = linesSpace; } }, finish = function lexer_script_general_finish():void { let str:string = ""; //pads certain template tag delimiters with a space const bracketSpace = function lexer_script_general_finish_bracketSpace(input:string):string { if (options.language !== "javascript" && options.language !== "typescript" && options.language !== "jsx" && options.language !== "tsx") { const spaceStart = function lexer_script_general_finish_bracketSpace_spaceStart(start:string):string { return start.replace(/\s*$/, " "); }, spaceEnd = function lexer_script_general_finish_bracketSpace_spaceStart(end:string):string { return end.replace(/^\s*/, " "); }; if ((/\{(#|\/|(%>)|(%\]))/).test(input) === true || (/\}%(>|\])/).test(input) === true) { return input; } input = input.replace(/\{((\{+)|%-?)\s*/g, spaceStart); input = input.replace(/\s*((\}\}+)|(-?%\}))/g, spaceEnd); return input; } return input; }; if (starting === "\"" && qc === "single") { build[0] = "'"; build[build.length - 1] = "'"; } else if (starting === "'" && qc === "double") { build[0] = "\""; build[build.length - 1] = "\""; } else if (escape === true) { str = build[build.length - 1]; build.pop(); build.pop(); build.push(str); } a = ee; if (ending === "\n") { a = a - 1; build.pop(); } ltoke = build.join(""); if (starting === "\"" || starting === "'" || starting === "{{" || starting === "{%" || starting === "{{{") { ltoke = bracketSpace(ltoke); } if (starting === "{%" || starting === "{{") { temp = tname(ltoke); ltype = temp[0]; recordPush(temp[1]); return; } if (type === "string") { ltype = "string"; if (options.language === "json") { ltoke = ltoke .replace(/\u0000/g, "\\u0000") .replace(/\u0001/g, "\\u0001") .replace(/\u0002/g, "\\u0002") .replace(/\u0003/g, "\\u0003") .replace(/\u0004/g, "\\u0004") .replace(/\u0005/g, "\\u0005") .replace(/\u0006/g, "\\u0006") .replace(/\u0007/g, "\\u0007") .replace(/\u0008/g, "\\u0008") .replace(/\u0009/g, "\\u0009") .replace(/\u000a/g, "\\u000a") .replace(/\u000b/g, "\\u000b") .replace(/\u000c/g, "\\u000c") .replace(/\u000d/g, "\\u000d") .replace(/\u000e/g, "\\u000e") .replace(/\u000f/g, "\\u000f") .replace(/\u0010/g, "\\u0010") .replace(/\u0011/g, "\\u0011") .replace(/\u0012/g, "\\u0012") .replace(/\u0013/g, "\\u0013") .replace(/\u0014/g, "\\u0014") .replace(/\u0015/g, "\\u0015") .replace(/\u0016/g, "\\u0016") .replace(/\u0017/g, "\\u0017") .replace(/\u0018/g, "\\u0018") .replace(/\u0019/g, "\\u0019") .replace(/\u001a/g, "\\u001a") .replace(/\u001b/g, "\\u001b") .replace(/\u001c/g, "\\u001c") .replace(/\u001d/g, "\\u001d") .replace(/\u001e/g, "\\u001e") .replace(/\u001f/g, "\\u001f"); } else if (starting.indexOf("#!") === 0) { ltoke = ltoke.slice(0, ltoke.length - 1); parse.linesSpace = 2; } else if (parse.structure[parse.structure.length - 1][0] !== "object" || (parse.structure[parse.structure.length - 1][0] === "object" && nextchar(1, false) !== ":" && data.token[parse.count] !== "," && data.token[parse.count] !== "{")) { if ((ltoke.length > options.wrap && options.wrap > 0) || (options.wrap !== 0 && data.token[parse.count] === "+" && (data.token[parse.count - 1].charAt(0) === "\"" || data.token[parse.count - 1].charAt(0) === "'"))) { let item:string = ltoke, q:string = (qc === "double") ? "\"" : (qc === "single") ? "'" : item.charAt(0), segment:string = ""; const limit:number = options.wrap, uchar:RegExp = (/u[0-9a-fA-F]{4}/), xchar:RegExp = (/x[0-9a-fA-F]{2}/); item = item.slice(1, item.length - 1); if (data.token[parse.count] === "+" && (data.token[parse.count - 1].charAt(0) === "\"" || data.token[parse.count - 1].charAt(0) === "'")) { parse.pop(data); q = data.token[parse.count].charAt(0); item = data.token[parse.count].slice(1, data.token[parse.count].length - 1) + item; parse.pop(data); } if (item.length > limit && limit > 0) { do { segment = item.slice(0, limit); if (segment.charAt(limit - 5) === "\\" && uchar.test(item.slice(limit - 4, limit + 1)) === true) { segment = segment.slice(0, limit - 5); } else if (segment.charAt(limit - 4) === "\\" && uchar.test(item.slice(limit - 3, limit + 2)) === true) { segment = segment.slice(0, limit - 4); } else if (segment.charAt(limit - 3) === "\\" && (uchar.test(item.slice(limit - 2, limit + 3)) === true || xchar.test(item.slice(limit - 2, limit + 1)) === true)) { segment = segment.slice(0, limit - 3); } else if (segment.charAt(limit - 2) === "\\" && (uchar.test(item.slice(limit - 1, limit + 4)) === true || xchar.test(item.slice(limit - 1, limit + 2)) === true)) { segment = segment.slice(0, limit - 2); } else if (segment.charAt(limit - 1) === "\\") { segment = segment.slice(0, limit - 1); } segment = q + segment + q; item = item.slice(segment.length - 2); ltoke = segment; ltype = "string"; recordPush(""); parse.linesSpace = 0; ltoke = "+"; ltype = "operator"; recordPush(""); } while (item.length > limit); } if (item === "") { ltoke = q + q; } else { ltoke = q + item + q; } ltype = "string"; } } } else if ((/\{\s*\?>$/).test(ltoke) === true) { if ((/^<\?(=|(php))\s*\}\s*else/).test(ltoke) === true) { ltype = "template_else"; } else { ltype = "template_start"; } } else if ((/^<\?(=|(php))\s*\}/).test(ltoke) === true) { if ((/^<\?(=|(php))\s*\}\s*else/).test(ltoke) === true) { ltype = "template_else"; } else { ltype = "template_end"; } } else { ltype = type; } if (ltoke.length > 0) { recordPush(""); } }; if (wordTest > -1) { word(); } // this insanity is for JSON where all the required quote characters are // escaped. if (c[a - 1] === "\\" && slashes(a - 1) === true && (c[a] === "\"" || c[a] === "'")) { parse.pop(data); if (data.token[0] === "{") { if (c[a] === "\"") { starting = "\""; ending = "\\\""; build = ["\""]; } else { starting = "'"; ending = "\\'"; build = ["'"]; } escape = true; } else { if (c[a] === "\"") { build = ["\\\""]; finish(); return; } build = ["\\'"]; finish(); return; } } ee = base; if (ee < b) { do { if (data.token[0] !== "{" && data.token[0] !== "[" && qc !== "none" && (c[ee] === "\"" || c[ee] === "'")) { if (c[ee - 1] === "\\") { if (slashes(ee - 1) === true) { if (qc === "double" && c[ee] === "'") { build.pop(); } else if (qc === "single" && c[ee] === "\"") { build.pop(); } } } else if (qc === "double" && c[ee] === "\"" && c[a] === "'") { c[ee] = "\\\""; } else if (qc === "single" && c[ee] === "'" && c[a] === "\"") { c[ee] = "\\'"; } build.push(c[ee]); } else if (ee > start) { ext = true; if (c[ee] === "<" && c[ee + 1] === "?" && c[ee + 2] === "p" && c[ee + 3] === "h" && c[ee + 4] === "p" && c[ee + 5] !== starting) { finish(); // php lexer_script_general("<?php", "?>", "template"); cleanUp(); } else if (c[ee] === "<" && c[ee + 1] === "?" && c[ee + 2] === "=" && c[ee + 3] !== starting) { finish(); // php lexer_script_general("<?=", "?>", "template"); cleanUp(); } else if (c[ee] === "<" && c[ee + 1] === "%" && c[ee + 2] !== starting) { finish(); // asp lexer_script_general("<%", "%>", "template"); cleanUp(); } else if (c[ee] === "{" && c[ee + 1] === "%" && c[ee + 2] !== starting) { finish(); // twig lexer_script_general("{%", "%}", "template"); cleanUp(); } else if (c[ee] === "{" && c[ee + 1] === "{" && c[ee + 2] === "{" && c[ee + 3] !== starting) { finish(); // mustache lexer_script_general("{{{", "}}}", "template"); cleanUp(); } else if (c[ee] === "{" && c[ee + 1] === "{" && c[ee + 2] !== starting) { finish(); // handlebars lexer_script_general("{{", "}}", "template"); cleanUp(); } else if (c[ee] === "<" && c[ee + 1] === "!" && c[ee + 2] === "-" && c[ee + 3] === "-" && c[ee + 4] === "#" && c[ee + 5] !== starting) { finish(); // ssi lexer_script_general("<!--#", "-->", "template"); cleanUp(); } else { ext = false; build.push(c[ee]); } } else { build.push(c[ee]); } if ((starting === "\"" || starting === "'") && (ext === true || ee > start) && options.language !== "json" && c[ee - 1] !== "\\" && c[ee] !== "\"" && c[ee] !== "'" && (c[ee] === "\n" || ee === b - 1)) { sparser.parseerror = "Unterminated string in script on line number " + parse.lineNumber; break; } if (c[ee] === ender[endlen - 1] && (c[ee - 1] !== "\\" || slashes(ee - 1) === false)) { if (endlen === 1) { break; } // `ee - base` is a cheap means of computing length of build array the `ee - // base` and `endlen` are both length based values, so adding two (1 for each) // provides an index based number if (build[ee - base] === ender[0] && build.slice(ee - base - endlen + 2).join("") === ending) { break; } } ee = ee + 1; } while (ee < b); } finish(); }, // line comments lineComment = function lexer_script_lineComment() { asi(false); blockinsert(); if (wordTest > -1) { word(); } comment = parse.wrapCommentLine({ chars: c, end: b, lexer: "script", opening: "//", start: a, terminator: "\n" }); a = comment[1]; if (comment[0] !== "") { ltoke = comment[0]; ltype = (/^(\/\/\s*parse-ignore-start)/).test(ltoke) ? "ignore" : "comment"; if (ltoke.indexOf("# sourceMappingURL=") === 2) { sourcemap[0] = parse.count + 1; sourcemap[1] = ltoke; } parse.push(data, { begin: parse.structure[parse.structure.length - 1][1], ender: -1, lexer: "script", lines: parse.linesSpace, stack: parse.structure[parse.structure.length - 1][0], token: ltoke, types: ltype }, ""); } }, // Identifies blocks of markup embedded within JavaScript for language super sets // like React JSX. markup = function lexer_script_markup():void { let curlytest:boolean = false, endtag:boolean = false, anglecount:number = 0, curlycount:number = 0, tagcount:number = 0, d:number = 0, next:string = "", priorToken:string = "", priorType:string = "", output:string[] = []; const dt:boolean = datatype[datatype.length - 1], syntaxnum:string = "0123456789=<>+-*?|^:&.,;%(){}[]~", applyMarkup = function lexer_script_markup_applyMarkup():void { if (ltoke === "(") { parse.structure[parse.structure.length - 1] = ["paren", parse.count]; } sparser.lexers.markup(output.join("")); }; if (wordTest > -1) { word(); } // type generics tokenizer priorToken = (parse.count > 0) ? data.token[parse.count - 1] : ""; priorType = (parse.count > 0) ? data.types[parse.count - 1] : ""; next = nextchar(1, false); if (options.language !== "jsx" && options.language !== "tsx" && (/\d/).test(next) === false && ( ltoke === "function" || priorToken === "=>" || priorToken === "void" || priorToken === "." || data.stack[parse.count] === "arguments" || ((options.language === "csharp" || options.language === "java") && priorToken === "public" || priorToken === "private" || priorToken === "final" || priorToken === "static") || (ltype === "type" && priorToken === "type") || (ltype === "reference" && (priorType === "operator" || priorToken === "function" || priorToken === "class" || priorToken === "new")) || (ltype === "type" && priorType === "operator") || ltoke === "return" || ltype === "operator" )) { let inc:number = 0, e:number = 0; const build:string[] = []; d = a; do { build.push(c[d]); if (c[d] === "<") { inc = inc + 1; } else if (c[d] === ">") { inc = inc - 1; if (inc < 1) { break; } } d = d + 1; } while (d < b); e = a; a = d; next = nextchar(1, false); if (c[d] === ">" && (dt === true || priorToken === "=>" || priorToken === "." || priorType !== "operator" || (priorType === "operator" && (next === "(" || next === "=")))) { ltype = "generic"; ltoke = build.join("").replace(/^<\s+/, "<").replace(/\s+>$/, ">").replace(/,\s*/g, ", "); recordPush(""); return; } a = e; } d = parse.count; if (data.types[d] === "comment") { do { d = d - 1; } while ( d > 0 && data.types[d] === "comment" ); } if ( dt === false && nextchar(1, false) !== ">" && ( (c[a] !== "<" && syntaxnum.indexOf(c[a + 1]) > -1) || data.token[d] === "++" || data.token[d] === "--" || (/\s/).test(c[a + 1]) === true || ( (/\d/).test(c[a + 1]) === true && ( ltype === "operator" || ltype === "string" || ltype === "number" || ltype === "reference" || (ltype === "word" && ltoke !== "return") ) )) ) { ltype = "operator"; ltoke = operator(); return recordPush(""); } if (options.language !== "typescript" && options.language !== "flow" && (data.token[d] === "return" || data.types[d] === "operator" || data.types[d] === "start" || data.types[d] === "separator" || data.types[d] === "jsx_attribute_start" || (data.token[d] === "}" && parse.structure[parse.structure.length - 1][0] === "global"))) { ltype = "markup"; options.language = "jsx"; do { output.push(c[a]); if (c[a] === "{") { curlycount = curlycount + 1; curlytest = true; } else if (c[a] === "}") { curlycount = curlycount - 1; if (curlycount === 0) { curlytest = false; } } else if (c[a] === "<" && curlytest === false) { if (c[a + 1] === "<") { do { output.push(c[a]); a = a + 1; } while (a < b && c[a + 1] === "<"); } anglecount = anglecount + 1; if (nextchar(1, false) === "/") { endtag = true; } } else if (c[a] === ">" && curlytest === false) { if (c[a + 1] === ">") { do { output.push(c[a]); a = a + 1; } while (c[a + 1] === ">"); } anglecount = anglecount - 1; if (endtag === true) { tagcount = tagcount - 1; } else if (c[a - 1] !== "/") { tagcount = tagcount + 1; } if (anglecount === 0 && curlycount === 0 && tagcount < 1) { next = nextchar(2, false); if (next.charAt(0) !== "<") { // if followed by nonmarkup return applyMarkup(); } // catch additional trailing tag sets if (next.charAt(0) === "<" && syntaxnum.indexOf(next.charAt(1)) < 0 && (/\s/).test(next.charAt(1)) === false) { // perform a minor safety test to verify if "<" is a tag start or a less than // operator d = a + 1; do { d = d + 1; if (c[d] === ">" || ((/\s/).test(c[d - 1]) === true && syntaxnum.indexOf(c[d]) < 0)) { break; } if (syntaxnum.indexOf(c[d]) > -1) { // if followed by additional markup tags return applyMarkup(); } } while (d < b); } else { // if a nonmarkup "<" follows markup return applyMarkup(); } } endtag = false; } a = a + 1; } while (a < b); return applyMarkup(); } ltype = "operator"; ltoke = operator(); recordPush(""); return; }, // peek at whats up next nextchar = function lexer_script_nextchar(len:number, current:boolean):string { let cc:number = (current === true) ? a : a + 1, dd:string = ""; if (typeof len !== "number" || len < 1) { len = 1; } if (c[a] === "/") { if (c[a + 1] === "/") { dd = "\n"; } else if (c[a + 1] === "*") { dd = "/"; } } if (cc < b) { do { if ((/\s/).test(c[cc]) === false) { if (c[cc] === "/") { if (dd === "") { if (c[cc + 1] === "/") { dd = "\n"; } else if (c[cc + 1] === "*") { dd = "/"; } } else if (dd === "/" && c[cc - 1] === "*") { dd = ""; } } if (dd === "" && c[cc - 1] + c[cc] !== "\u002a/") { return c .slice(cc, cc + len) .join(""); } } else if (dd === "\n" && c[cc] === "\n") { dd = ""; } cc = cc + 1; } while (cc < b); } return ""; }, // a tokenizer for numbers numb = function lexer_script_number():string { const f:number = b, build:string[] = [c[a]]; let ee:number = 0, test:RegExp = /zz/, dot:boolean = (build[0] === "."); if (a < b - 2 && c[a] === "0") { if (c[a + 1] === "x") { test = /[0-9a-fA-F]/; } else if (c[a + 1] === "o") { test = /[0-9]/; } else if (c[a + 1] === "b") { test = /0|1/; } if (test.test(c[a + 2]) === true) { build.push(c[a + 1]); ee = a + 1; do { ee = ee + 1; build.push(c[ee]); } while (test.test(c[ee + 1]) === true); a = ee; return build.join(""); } } ee = a + 1; if (ee < f) { do { if ((/[0-9]/).test(c[ee]) || (c[ee] === "." && dot === false)) { build.push(c[ee]); if (c[ee] === ".") { dot = true; } } else { break; } ee = ee + 1; } while (ee < f); } if (ee < f - 1 && ((/\d/).test(c[ee - 1]) === true || ((/\d/).test(c[ee - 2]) === true && (c[ee - 1] === "-" || c[ee - 1] === "+"))) && (c[ee] === "e" || c[ee] === "E")) { build.push(c[ee]); if (c[ee + 1] === "-" || c[ee + 1] === "+") { build.push(c[ee + 1]); ee = ee + 1; } dot = false; ee = ee + 1; if (ee < f) { do { if ((/[0-9]/).test(c[ee]) || (c[ee] === "." && dot === false)) { build.push(c[ee]); if (c[ee] === ".") { dot = true; } } else { break; } ee = ee + 1; } while (ee < f); } } a = ee - 1; return build.join(""); }, // a unique tokenizer for operator characters operator = function lexer_script_operator():string { let g:number = 0, h:number = 0, jj:number = b, output:string = ""; const syntax:string[] = [ "=", "<", ">", "+", "*", "?", "|", "^", ":", "&", "%", "~" ], synlen = syntax.length; if (wordTest > -1) { word(); } if (c[a] === "/" && (parse.count > -1 && ((ltype !== "word" && ltype !== "reference") || ltoke === "typeof" || ltoke === "return" || ltoke === "else") && ltype !== "number" && ltype !== "string" && ltype !== "end")) { if (ltoke === "return" || ltoke === "typeof" || ltoke === "else" || ltype !== "word") { ltoke = regex(); ltype = "regex"; } else { ltoke = "/"; ltype = "operator"; } recordPush(""); return "regex"; } if (c[a] === "?" && ("+-\u002a/.?".indexOf(c[a + 1]) > -1 || (c[a + 1] === ":" && syntax.join("").indexOf(c[a + 2]) < 0))) { if (c[a + 1] === "." && (/\d/).test(c[a + 2]) === false) { output = "?."; } else if (c[a + 1] === "?") { output = "??"; } if (output === "") { return "?"; } } if (c[a] === ":" && "+-\u002a/".indexOf(c[a + 1]) > -1) { return ":"; } if (a < b - 1) { if (c[a] !== "<" && c[a + 1] === "<") { return c[a]; } if (c[a] === "!" && c[a + 1] === "/") { return "!"; } if (c[a] === "-") { datatype[datatype.length - 1] = false; if (c[a + 1] === "-") { output = "--"; } else if (c[a + 1] === "=") { output = "-="; } else if (c[a + 1] === ">") { output = "->"; } if (output === "") { return "-"; } } if (c[a] === "+") { datatype[datatype.length - 1] = false; if (c[a + 1] === "+") { output = "++"; } else if (c[a + 1] === "=") { output = "+="; } if (output === "") { return "+"; } } if (c[a] === "=" && c[a + 1] !== "=" && c[a + 1] !== "!" && c[a + 1] !== ">") { datatype[datatype.length - 1] = false; return "="; } } if (c[a] === ":") { if (options.language === "typescript" || options.language === "flow") { if (data.stack[parse.count] === "arguments") { if (data.token[parse.count] === "?") { parse.pop(data); output = "?:"; a = a - 1; } datatype[datatype.length - 1] = true; } else if (ltoke === ")" && (data.token[data.begin[parse.count] - 1] === "function" || data.token[data.begin[parse.count] - 2] === "function")) { datatype[datatype.length - 1] = true; } else if (ltype === "reference") { g = parse.count; let colon:boolean = false; do { if (data.begin[g] === data.begin[parse.count]) { if (g < parse.count && data.token[g] === ":" && data.types[g + 1] !== "type") { colon = true; } if (data.token[g] === "?" && colon === false) { break; } if (data.token[g] === ";" || data.token[g] === "x;") { break; } if (data.token[g] === "var" || data.token[g] === "let" || data.token[g] === "const" || data.types[g] === "type") { datatype[datatype.length - 1] = true; break; } } else { if (data.types[g] === "type_end") { datatype[datatype.length - 1] = true; break; } g = data.begin[g]; } g = g - 1; } while (g > data.begin[parse.count]); } } else if ((data.types[parse.count] === "word" || data.types[parse.count] === "reference") && data.token[parse.count - 1] === "[") { parse.structure[parse.structure.length - 1][0] = "attribute"; data.stack[parse.count] = "attribute"; } } if (output === "") { if ((c[a + 1] === "+" && c[a + 2] === "+") || (c[a + 1] === "-" && c[a + 2] === "-")) { output = c[a]; } else { const buildout = [c[a]]; g = a + 1; if (g < jj) { do { if ((c[g] === "+" && c[g + 1] === "+") || (c[g] === "-" && c[g + 1] === "-")) { break; } h = 0; if (h < synlen) { do { if (c[g] === syntax[h]) { buildout.push(syntax[h]); break; } h = h + 1; } while (h < synlen); } if (h === synlen) { break; } g = g + 1; } while (g < jj); } output = buildout.join(""); } } a = a + (output.length - 1); if (output === "=>" && ltoke === ")") { g = parse.count; jj = data.begin[g]; do { if (data.begin[g] === jj) { data.stack[g] = "method"; } g = g - 1; } while (g > jj - 1); } return output; }, // convert ++ and -- into "= x +" and "= x -" in most cases plusplus = function lexer_script_plusplus():void { let pre:boolean = true, toke:string = "+", tokea:string = "", tokeb:string = "", tokec:string = "", inc:number = 0, ind:number = 0, walk:number = 0, next:string = ""; const store = [], end = function lexer_script_plusplus_end():void { walk = data.begin[walk] - 1; if (data.types[walk] === "end") { lexer_script_plusplus_end(); } else if (data.token[walk - 1] === ".") { period(); } }, period = function lexer_script_plusplus_period():void { walk = walk - 2; if (data.types[walk] === "end") { end(); } else if (data.token[walk - 1] === ".") { lexer_script_plusplus_period(); } }, applyStore = function lexer_script_plusplus_applyStore():void { let x:number = 0; const y:number = store.length; if (x < y) { do { parse.push(data, store[x], ""); x = x + 1; } while (x < y); } }, recordStore = function lexer_script_plusplus_recordStore(index:number):record { return { begin: data.begin[index], ender: data.ender[index], lexer: data.lexer[index], lines: data.lines[index], stack: data.stack[index], token: data.token[index], types: data.types[index] }; }; tokea = data.token[parse.count]; tokeb = data.token[parse.count - 1]; tokec = data.token[parse.count - 2]; if (tokea !== "++" && tokea !== "--" && tokeb !== "++" && tokeb !== "--") { walk = parse.count; if (data.types[walk] === "end") { end(); } else if (data.token[walk - 1] === ".") { period(); } } if (data.token[walk - 1] === "++" || data.token[walk - 1] === "--") { if ("startendoperator".indexOf(data.types[walk - 2]) > -1) { return; } inc = walk; if (inc < parse.count + 1) { do { store.push(recordStore(inc)); inc = inc + 1; } while (inc < parse.count + 1); parse.splice({ data : data, howmany: parse.count - walk, index : walk }); } } else { if (options.correct === false || (tokea !== "++" && tokea !== "--" && tokeb !== "++" && tokeb !== "--")) { return; } next = nextchar(1, false); if ((tokea === "++" || tokea === "--") && (c[a] === ";" || next === ";" || c[a] === "}" || next === "}" || c[a] === ")" || next === ")")) { toke = data.stack[parse.count]; if (toke === "array" || toke === "method" || toke === "object" || toke === "paren" || toke === "notation" || (data.token[data.begin[parse.count] - 1] === "while" && toke !== "while")) { return; } inc = parse.count; do { inc = inc - 1; if (data.token[inc] === "return") { return; } if (data.types[inc] === "end") { do { inc = data.begin[inc] - 1; } while (data.types[inc] === "end" && inc > 0); } } while ( inc > 0 && (data.token[inc] === "." || data.types[inc] === "word" || data.types[inc] === "reference" || data.types[inc] === "end") ); if (data.token[inc] === "," && c[a] !== ";" && next !== ";" && c[a] !== "}" && next !== "}" && c[a] !== ")" && next !== ")") { return; } if (data.types[inc] === "operator") { if (data.stack[inc] === "switch" && data.token[inc] === ":") { do { inc = inc - 1; if (data.types[inc] === "start") { ind = ind - 1; if (ind < 0) { break; } } else if (data.types[inc] === "end") { ind = ind + 1; } if (data.token[inc] === "?" && ind === 0) { return; } } while (inc > 0); } else { return; } } pre = false; if (tokea === "--") { toke = "-"; } else { toke = "+"; } } else if (tokec === "[" || tokec === ";" || tokec === "x;" || tokec === "}" || tokec === "{" || tokec === "(" || tokec === ")" || tokec === "," || tokec === "return") { if (tokea === "++" || tokea === "--") { if (tokec === "[" || tokec === "(" || tokec === "," || tokec === "return") { return; } if (tokea === "--") { toke = "-"; } pre = false; } else if (tokeb === "--" || tokea === "--") { toke = "-"; } } else { return; } if (pre === false) { tempstore = parse.pop(data); } walk = parse.count; if (data.types[walk] === "end") { end(); } else if (data.token[walk - 1] === ".") { period(); } inc = walk; if (inc < parse.count + 1) { do { store.push(recordStore(inc)); inc = inc + 1; } while (inc < parse.count + 1); } } if (pre === true) { parse.splice({ data : data, howmany: 1, index : walk - 1 }); ltoke = "="; ltype = "operator"; recordPush(""); applyStore(); ltoke = toke; ltype = "operator"; recordPush(""); ltoke = "1"; ltype = "number"; recordPush(""); } else { ltoke = "="; ltype = "operator"; recordPush(""); applyStore(); ltoke = toke; ltype = "operator"; recordPush(""); ltoke = "1"; ltype = "number"; recordPush(""); } ltoke = data.token[parse.count]; ltype = data.types[parse.count]; if (next === "}" && c[a] !== ";") { asi(false); } }, // determine the definition of containment by stack recordPush = function lexer_script_recordPush(structure: string):void { const record:record = { begin: parse.structure[parse.structure.length - 1][1], ender: -1, lexer: "script", lines: parse.linesSpace, stack: parse.structure[parse.structure.length - 1][0], token: ltoke, types: ltype }; parse.push(data, record, structure); }, // a tokenizer for regular expressions regex = function lexer_script_regex():string { let ee:number = a + 1, h:number = 0, i:number = 0, output:string = "", square:boolean = false; const f:number = b, build:string[] = ["/"]; if (ee < f) { do { build.push(c[ee]); if (c[ee - 1] !== "\\" || c[ee - 2] === "\\") { if (c[ee] === "[") { square = true; } if (c[ee] === "]") { square = false; } } if (c[ee] === "/" && square === false) { if (c[ee - 1] === "\\") { i = 0; h = ee - 1; if (h > 0) { do { if (c[h] === "\\") { i = i + 1; } else { break; } h = h - 1; } while (h > 0); } if (i % 2 === 0) { break; } } else { break; } } ee = ee + 1; } while (ee < f); } if (c[ee + 1] === "g" || c[ee + 1] === "i" || c[ee + 1] === "m" || c[ee + 1] === "y" || c[ee + 1] === "u") { build.push(c[ee + 1]); if (c[ee + 2] !== c[ee + 1] && (c[ee + 2] === "g" || c[ee + 2] === "i" || c[ee + 2] === "m" || c[ee + 2] === "y" || c[ee + 2] === "u")) { build.push(c[ee + 2]); if (c[ee + 3] !== c[ee + 1] && c[ee + 3] !== c[ee + 2] && (c[ee + 3] === "g" || c[ee + 3] === "i" || c[ee + 3] === "m" || c[ee + 3] === "y" || c[ee + 3] === "u")) { build.push(c[ee + 3]); if (c[ee + 4] !== c[ee + 1] && c[ee + 4] !== c[ee + 2] && c[ee + 4] !== c[ee + 3] && (c[ee + 4] === "g" || c[ee + 4] === "i" || c[ee + 4] === "m" || c[ee + 4] === "y" || c[ee + 4] === "u")) { build.push(c[ee + 4]); if (c[ee + 5] !== c[ee + 1] && c[ee + 5] !== c[ee + 2] && c[ee + 5] !== c[ee + 3] && c[ee + 5] !== c[ee + 4] && (c[ee + 5] === "g" || c[ee + 5] === "i" || c[ee + 5] === "m" || c[ee + 5] === "y" || c[ee + 5] === "u")) { build.push(c[ee + 4]); a = ee + 5; } else { a = ee + 4; } } else { a = ee + 3; } } else { a = ee + 2; } } else { a = ee + 1; } } else { a = ee; } output = build.join(""); return output; }, // determines if a slash comprises a valid escape or if it is escaped itself slashes = function lexer_script_slashes(index:number):boolean { const slashy:number = index; do { index = index - 1; } while (c[index] === "\\" && index > 0); if ((slashy - index) % 2 === 1) { return true; } return false; }, // operations for start types: (, [, { start = function lexer_script_start(x:string):void { let aa:number = parse.count, wordx:string = "", wordy:string = "", stack:string = "", func:boolean = false; brace.push(x); if (x === "{" && (data.types[parse.count] === "type" || data.types[parse.count] === "type_end" || data.types[parse.count] === "generic")) { // this block determines if a function body follows a type annotation let begin:number = 0; if (data.types[parse.count] === "type_end") { aa = data.begin[parse.count]; } begin = aa; do { aa = aa - 1; if (data.begin[aa] !== begin && data.begin[aa] !== -1) { break; } if (data.token[aa] === ":") { break; } } while (aa > data.begin[aa]); if (data.token[aa] === ":" && data.stack[aa - 1] === "arguments") { datatype.push(false); func = true; } else { datatype.push(datatype[datatype.length - 1]); } aa = parse.count; } else if (x === "[" && data.types[parse.count] === "type_end") { datatype.push(true); } else { datatype.push(datatype[datatype.length - 1]); } if (wordTest > -1) { word(); aa = parse.count; } if (vart.len > -1) { vart.count[vart.len] = vart.count[vart.len] + 1; } if (data.token[aa - 1] === "function") { lword.push([ "function", aa + 1 ]); } else { lword.push([ ltoke, aa + 1 ]); } ltoke = x; if (datatype[datatype.length - 1] === true) { ltype = "type_start"; } else { ltype = "start"; } if (x === "(" || x === "x(") { asifix(); } else if (x === "{") { if (paren > -1) { if (data.begin[paren - 1] === data.begin[data.begin[aa] - 1] || data.token[data.begin[aa]] === "x(") { paren = -1; if (options.correct === true) { end(")"); } else { end("x)"); } asifix(); ltoke = "{"; ltype = "start"; } } else if (ltoke === ")") { asifix(); } if (ltype === "comment" && data.token[aa - 1] === ")") { ltoke = data.token[aa]; data.token[aa] = "{"; ltype = data.types[aa]; data.types[aa] = "start"; } } wordx = (function lexer_script_start_wordx():string { let bb:number = parse.count; if (data.types[bb] === "comment") { do { bb = bb - 1; } while (bb > 0 && data.types[bb] === "comment"); } return data.token[bb]; }()); wordy = (data.stack[aa] === undefined) ? "" : (function lexer_script_start_wordy():string { let bb:number = parse.count; if (data.types[bb] === "comment") { do { bb = bb - 1; } while (bb > 0 && data.types[bb] === "comment"); } return data.token[data.begin[bb] - 1]; }()); if (ltoke === "{" && (data.types[aa] === "word" || data.token[aa] === "]")) { let bb:number = aa; if (data.token[bb] === "]") { do { bb = data.begin[bb] - 1; } while (data.token[bb] === "]"); } do { if (data.types[bb] === "start" || data.types[bb] === "end" || data.types[bb] === "operator") { break; } bb = bb - 1; } while (bb > 0); if (data.token[bb] === ":" && data.stack[bb - 1] === "arguments") { stack = "function"; references.push(funreferences); funreferences = []; } } if (ltype === "type_start") { stack = "data_type"; } else if (stack === "" && (ltoke === "{" || ltoke === "x{")) { if (wordx === "else" || wordx === "do" || wordx === "try" || wordx === "finally" || wordx === "switch") { stack = wordx; } else if (classy[classy.length - 1] === 0 && wordx !== "return") { classy.pop(); stack = "class"; } else if (data.token[aa - 1] === "class") { stack = "class"; } else if (data.token[aa] === "]" && data.token[aa - 1] === "[") { stack = "array"; } else if ( (data.types[aa] === "word" || data.types[aa] === "reference") && ( data.types[aa - 1] === "word" || data.types[aa - 1] === "reference" || (data.token[aa - 1] === "?" && (data.types[aa - 2] === "word" || data.types[aa - 2] === "reference")) ) && data.token[aa] !== "in" && data.token[aa - 1] !== "export" && data.token[aa - 1] !== "import" ) { stack = "map"; } else if ( data.stack[aa] === "method" && data.types[aa] === "end" && (data.types[data.begin[aa] - 1] === "word" || data.types[data.begin[aa] - 1] === "reference") && data.token[data.begin[aa] - 2] === "new" ) { stack = "initializer"; } else if ( ltoke === "{" && (wordx === ")" || wordx === "x)") && (data.types[data.begin[aa] - 1] === "word" || data.types[data.begin[aa] - 1] === "reference" || data.token[data.begin[aa] - 1] === "]") ) { if (wordy === "if") { stack = "if"; } else if (wordy === "for") { stack = "for"; } else if (wordy === "while") { stack = "while"; } else if (wordy === "class") { stack = "class"; } else if (wordy === "switch" || data.token[data.begin[aa] - 1] === "switch") { stack = "switch"; } else if (wordy === "catch") { stack = "catch"; } else { stack = "function"; } } else if (ltoke === "{" && (wordx === ";" || wordx === "x;")) { // ES6 block stack = "block"; } else if (ltoke === "{" && data.token[aa] === ":" && data.stack[aa] === "switch") { // ES6 block stack = "block"; } else if (data.token[aa - 1] === "import" || data.token[aa - 2] === "import" || data.token[aa - 1] === "export" || data.token[aa - 2] === "export") { stack = "object"; } else if (wordx === ")" && (pword[0] === "function" || pword[0] === "if" || pword[0] === "for" || pword[0] === "class" || pword[0] === "while" || pword[0] === "switch" || pword[0] === "catch")) { // if preceeded by a paren the prior containment is preceeded by a keyword if // (...) { stack = pword[0]; } else if (data.stack[aa] === "notation") { // if following a TSX array type declaration stack = "function"; } else if ( ( data.types[aa] === "number" || data.types[aa] === "string" || data.types[aa] === "word" || data.types[aa] === "reference" ) && (data.types[aa - 1] === "word" || data.types[aa - 1] === "reference") && data.token[data.begin[aa] - 1] !== "for" ) { // if preceed by a word and either string or word public class { stack = "function"; } else if (parse.structure.length > 0 && data.token[aa] !== ":" && parse.structure[parse.structure.length - 1][0] === "object" && ( data.token[data.begin[aa] - 2] === "{" || data.token[data.begin[aa] - 2] === "," )) { // if an object wrapped in some containment which is itself preceeded by a curly // brace or comma var a={({b:{cat:"meow"}})}; stack = "function"; } else if (data.types[pword[1] - 1] === "markup" && data.token[pword[1] - 3] === "function") { // checking for TSX function using an angle brace name stack = "function"; } else if (wordx === "=>") { // checking for fat arrow assignment stack = "function"; } else if (func === true || (data.types[parse.count] === "type_end" && data.stack[data.begin[parse.count] - 2] === "arguments")) { // working around typescript inline interface stack = "function"; } else if ( wordx === ")" && data.stack[aa] === "method" && (data.types[data.begin[aa] - 1] === "word" || data.types[data.begin[aa] - 1] === "property" || data.types[data.begin[aa] - 1] === "reference") ) { stack = "function"; } else if (data.types[aa] === "word" && ltoke === "{" && data.token[aa] !== "return" && data.token[aa] !== "in" && data.token[aa] !== "import" && data.token[aa] !== "const" && data.token[aa] !== "let" && data.token[aa] !== "") { // ES6 block stack = "block"; } else if (ltoke === "{" && (data.token[aa] === "x}" || data.token[aa] === "}") && "if|else|for|while|function|class|switch|catch|finally".indexOf(data.stack[aa]) > -1) { // ES6 block stack = "block"; } else if (data.stack[aa] === "arguments") { stack = "function"; } else if (data.types[aa] === "generic") { do { aa = aa - 1; if (data.token[aa] === "function" || data.stack[aa] === "arguments") { stack = "function"; break; } if (data.token[aa] === "interface") { stack = "map"; break; } if (data.token[aa] === ";") { stack = "object"; break; } } while (aa > data.begin[parse.count]); } else if ((options.language === "java" || options.language === "csharp") && data.types[parse.count - 1] === "reference" && data.token[parse.count - 2] === "]") { stack = "array"; } else { stack = "object"; } if (stack !== "object" && stack !== "class") { if (stack === "function") { references.push(funreferences); funreferences = []; } else { references.push([]); } } } else if (ltoke === "[") { if ((/\s/).test(c[a - 1]) === true && (data.types[aa] === "word" || data.types[aa] === "reference") && wordx !== "return" && options.language !== "twig") { stack = "notation"; } else { stack = "array"; } } else if (ltoke === "(" || ltoke === "x(") { if (wordx === "function" || data.token[aa - 1] === "function" || data.token[aa - 1] === "function*" || data.token[aa - 2] === "function") { stack = "arguments"; } else if (data.token[aa - 1] === "." || data.token[data.begin[aa] - 2] === ".") { stack = "method"; } else if (data.types[aa] === "generic") { stack = "method"; } else if (data.token[aa] === "}" && data.stack[aa] === "function") { stack = "method"; } else if (wordx === "if" || wordx === "for" || wordx === "class" || wordx === "while" || wordx === "catch" || wordx === "finally" || wordx === "switch" || wordx === "with") { stack = "expression"; } else if (data.types[aa] === "word" || data.types[aa] === "property" || data.types[aa] === "reference") { stack = "method"; } else { stack = "paren"; } } recordPush(stack); if (classy.length > 0) { classy[classy.length - 1] = classy[classy.length - 1] + 1; } }, // ES6 template string support tempstring = function lexer_script_tempstring():string { const output:string[] = [c[a]]; a = a + 1; if (a < b) { do { output.push(c[a]); if (c[a] === "`" && (c[a - 1] !== "\\" || slashes(a - 1) === false)) { break; } if (c[a - 1] === "$" && c[a] === "{" && (c[a - 2] !== "\\" || slashes(a - 2) === false)) { break; } a = a + 1; } while (a < b); } return output.join(""); }, // determines tag names for {% %} based template tags and returns a type tname = function lexer_script_tname(x:string):[string, string] { let sn:number = 2, en:number = 0, name:string = ""; const st:string = x.slice(0, 2), len:number = x.length, namelist:string[] = [ "autoescape", "block", "capture", "case", "comment", "embed", "filter", "for", "form", "if", "macro", "paginate", "raw", "sandbox", "spaceless", "tablerow", "unless", "verbatim" ]; if (x.charAt(2) === "-") { sn = sn + 1; } if ((/\s/).test(x.charAt(sn)) === true) { do { sn = sn + 1; } while ((/\s/).test(x.charAt(sn)) === true && sn < len); } en = sn; do { en = en + 1; } while ( (/\s/).test(x.charAt(en)) === false && x.charAt(en) !== "(" && en < len ); if (en === len) { en = x.length - 2; } name = x.slice(sn, en); if (name === "else" || (st === "{%" && (name === "elseif" || name === "when" || name === "elif"))) { return ["template_else", `template_${name}`]; } if (st === "{{") { if (name === "end") { return ["template_end", ""]; } if ((name === "block" && (/\{%\s*\w/).test(source) === false) || name === "define" || name === "form" || name === "if" || name === "range" || name === "with") { return ["template_start", `template_${name}`]; } return ["template", ""]; } en = namelist.length - 1; if (en > -1) { do { if (name === namelist[en] && (name !== "block" || (/\{%\s*\w/).test(source) === false)) { return ["template_start", `template_${name}`]; } if (name === "end" + namelist[en]) { return ["template_end", ""]; } en = en - 1; } while (en > -1); } return ["template", ""]; }, // remove "vart" object data vartpop = function lexer_script_vartpop():void { vart .count .pop(); vart .index .pop(); vart .word .pop(); vart.len = vart.len - 1; }, // A lexer for keywords, reserved words, and variables word = function lexer_script_word() { let f:number = wordTest, g:number = 1, output:string = "", nextitem:string = "", tokel:string = ltoke, typel:string = ltype; const lex = [], elsefix = function lexer_script_word_elsefix():void { brace.push("x{"); parse.splice({ data : data, howmany: 1, index : parse.count - 3 }); }, hoisting = function lexer_script_word_hoisting(index:number, ref:string, samescope:boolean):void { const begin:number = data.begin[index]; let parent:number = 0; do { if (data.token[index] === ref && data.types[index] === "word") { if (samescope === true) { // the simple state is for hoisted references, var and function declarations data.types[index] = "reference"; } else if (data.begin[index] > begin && data.token[data.begin[index]] === "{" && data.stack[index] !== "object" && data.stack[index] !== "class" && data.stack[index] !== "data_type") { // the complex state is for non-hoisted references living in prior functions of the same parent scope if (data.stack[index] === "function") { data.types[index] = "reference"; } else { // this looping is necessary to determine if there is a function between the reference and the declared scope parent = data.begin[index]; do { if (data.stack[parent] === "function") { data.types[index] = "reference"; break; } parent = data.begin[parent]; } while (parent > begin); } } } index = index - 1; } while (index > begin); }; do { lex.push(c[f]); if (c[f] === "\\") { sparser.parseerror = `Illegal escape in JavaScript on line number ${parse.lineNumber}`; } f = f + 1; } while (f < a); if (ltoke.charAt(0) === "\u201c") { sparser.parseerror = `Quote looking character (\u201c, \\u201c) used instead of actual quotes on line number ${parse.lineNumber}`; } else if (ltoke.charAt(0) === "\u201d") { sparser.parseerror = `Quote looking character (\u201d, \\u201d) used instead of actual quotes on line number ${parse.lineNumber}`; } output = lex.join(""); wordTest = -1; if (parse.count > 0 && output === "function" && data.token[parse.count] === "(" && (data.token[parse.count - 1] === "{" || data.token[parse.count - 1] === "x{")) { data.types[parse.count] = "start"; } if (parse.count > 1 && output === "function" && ltoke === "(" && (data.token[parse.count - 1] === "}" || data.token[parse.count - 1] === "x}")) { if (data.token[parse.count - 1] === "}") { f = parse.count - 2; if (f > -1) { do { if (data.types[f] === "end") { g = g + 1; } else if (data.types[f] === "start" || data.types[f] === "end") { g = g - 1; } if (g === 0) { break; } f = f - 1; } while (f > -1); } if (data.token[f] === "{" && data.token[f - 1] === ")") { g = 1; f = f - 2; if (f > -1) { do { if (data.types[f] === "end") { g = g + 1; } else if (data.types[f] === "start" || data.types[f] === "end") { g = g - 1; } if (g === 0) { break; } f = f - 1; } while (f > -1); } if (data.token[f - 1] !== "function" && data.token[f - 2] !== "function") { data.types[parse.count] = "start"; } } } else { data.types[parse.count] = "start"; } } if (options.correct === true && (output === "Object" || output === "Array") && c[a + 1] === "(" && c[a + 2] === ")" && data.token[parse.count - 1] === "=" && data.token[parse.count] === "new") { if (output === "Object") { data.token[parse.count] = "{"; ltoke = "}"; data.stack[parse.count] = "object"; parse.structure[parse.structure.length - 1][0] = "object"; } else { data.token[parse.count] = "["; ltoke = "]"; data.stack[parse.count] = "array"; parse.structure[parse.structure.length - 1][0] = "array"; } data.types[parse.count] = "start"; ltype = "end"; c[a + 1] = ""; c[a + 2] = ""; a = a + 2; } else { g = parse.count; f = g; if (options.lexer_options.script.variable_list !== "none" && (output === "var" || output === "let" || output === "const")) { if (data.types[g] === "comment") { do { g = g - 1; } while ( g > 0 && (data.types[g] === "comment") ); } if (options.lexer_options.script.variable_list === "list" && vart.len > -1 && vart.index[vart.len] === g && output === vart.word[vart.len]) { ltoke = ","; ltype = "separator"; data.token[g] = ltoke; data.types[g] = ltype; vart.count[vart.len] = 0; vart.index[vart.len] = g; vart.word[vart.len] = output; return; } vart.len = vart.len + 1; vart .count .push(0); vart .index .push(g); vart .word .push(output); g = f; } else if (vart.len > -1 && output !== vart.word[vart.len] && parse.count === vart.index[vart.len] && data.token[vart.index[vart.len]] === ";" && ltoke !== vart.word[vart.len] && options.lexer_options.script.variable_list === "list") { vartpop(); } if (output === "from" && data.token[parse.count] === "x;" && data.token[parse.count - 1] === "}") { asifix(); } if (output === "while" && data.token[parse.count] === "x;" && data.token[parse.count - 1] === "}") { let d:number = 0, e:number = parse.count - 2; if (e > -1) { do { if (data.types[e] === "end") { d = d + 1; } else if (data.types[e] === "start") { d = d - 1; } if (d < 0) { if (data.token[e] === "{" && data.token[e - 1] === "do") { asifix(); } return; } e = e - 1; } while (e > -1); } } if (typel === "comment") { let d:number = parse.count; do { d = d - 1; } while (d > 0 && data.types[d] === "comment"); typel = data.types[d]; tokel = data.token[d]; } nextitem = nextchar(2, false); if (output === "void") { if (tokel === ":" && data.stack[parse.count - 1] === "arguments") { ltype = "type"; } else { ltype = "word"; } } else if ((options.language === "java" || options.language === "csharp") && output === "static") { ltype = "word"; } else if ( ( parse.structure[parse.structure.length - 1][0] === "object" || parse.structure[parse.structure.length - 1][0] === "class" || parse.structure[parse.structure.length - 1][0] === "data_type" ) && ( data.token[parse.count] === "{" || (data.token[data.begin[parse.count]] === "{" && data.token[parse.count] === ",") || (data.types[parse.count] === "template_end" && (data.token[data.begin[parse.count] - 1] === "{" || data.token[data.begin[parse.count] - 1] === ",")) ) ) { if (output === "return" || output === "break") { ltype = "word"; } else { ltype = "property"; } } else if (datatype[datatype.length - 1] === true || ((options.language === "typescript" || options.language === "flow") && tokel === "type")) { ltype = "type"; } else if ((options.language === "java" || options.language === "csharp") && (tokel === "public" || tokel === "private" || tokel === "static" || tokel === "final")) { ltype = "reference"; } else if ((options.language === "java" || options.language === "csharp") && ltoke !== "var" && (ltype === "end" || ltype === "word") && nextitem.charAt(0) === "=" && nextitem.charAt(1) !== "=") { ltype = "reference"; } else if (references.length > 0 && (tokel === "function" || tokel === "class" || tokel === "const" || tokel === "let" || tokel === "var" || tokel === "new" || tokel === "void")) { ltype = "reference"; references[references.length - 1].push(output); if (options.language === "javascript" || options.language === "jsx" || options.language === "typescript" || options.language === "flow") { if (tokel === "var" || (tokel === "function" && data.types[parse.count - 1] !== "operator" && data.types[parse.count - 1] !== "start" && data.types[parse.count - 1] !== "end")) { hoisting(parse.count, output, true); } else { hoisting(parse.count, output, false); } } else { hoisting(parse.count, output, false); } } else if (parse.structure[parse.structure.length - 1][0] === "arguments" && ltype !== "operator") { ltype = "reference"; funreferences.push(output); } else if (tokel === "," && data.stack[parse.count] !== "method" && (data.stack[parse.count] !== "expression" || data.token[data.begin[parse.count] - 1] === "for")) { let d:number = parse.count; const e:number = parse.structure[parse.structure.length - 1][1]; do { if (data.begin[d] === e) { if (data.token[d] === ";") { break; } if (data.token[d] === "var" || data.token[d] === "let" || data.token[d] === "const" || data.token[d] === "type") { break; } } else if (data.types[d] === "end") { d = data.begin[d]; } d = d - 1; } while (d > e); if (references.length > 0 && data.token[d] === "var") { ltype = "reference"; references[references.length - 1].push(output); if (options.language === "javascript" || options.language === "jsx" || options.language === "typescript" || options.language === "flow") { hoisting(d, output, true); } else { hoisting(d, output, false); } } else if (references.length > 0 && (data.token[d] === "let" || data.token[d] === "const" || (data.token[d] === "type" && (options.language === "typescript" || options.language === "flow")))) { ltype = "reference"; references[references.length - 1].push(output); hoisting(d, output, false); } else { ltype = "word"; } } else if (parse.structure[parse.structure.length - 1][0] !== "object" || (parse.structure[parse.structure.length - 1][0] === "object" && ltoke !== "," && ltoke !== "{")) { let d:number = references.length, e:number = 0; if (d > 0) { do { d = d - 1; e = references[d].length; if (e > 0) { do { e = e - 1; if (output === references[d][e]) { break; } } while (e > 0); if (output === references[d][e]) { break; } } } while (d > 0); if (references[d][e] === output && tokel !== ".") { ltype = "reference"; } else { ltype = "word"; } } else { ltype = "word"; } } else { ltype = "word"; } ltoke = output; if (output === "from" && data.token[parse.count] === "}") { asifix(); } } recordPush(""); if (output === "class") { classy.push(0); } if (output === "do") { nextitem = nextchar(1, true); if (nextitem !== "{") { ltoke = (options.correct === true) ? "{" : "x{"; ltype = "start"; brace.push("x{"); recordPush("do"); } } if (output === "else") { nextitem = nextchar(2, true); let x:number = parse.count - 1; if (data.types[x] === "comment") { do { x = x - 1; } while (x > 0 && data.types[x] === "comment"); } if (data.token[x] === "x}") { if (data.token[parse.count] === "else") { if (data.stack[parse.count - 1] !== "if" && data.types[parse.count - 1] !== "comment" && data.stack[parse.count - 1] !== "else") { brace.pop(); parse.splice({ data : data, howmany: 0, index : parse.count - 1, record : { begin: data.begin[data.begin[data.begin[parse.count - 1] - 1] - 1], ender: -1, lexer: "script", lines: 0, stack: "if", token: (options.correct === true) ? "}" : "x}", types: "end" } }); if (parse.structure.length > 1) { parse.structure.splice(parse.structure.length - 2, 1); parse.structure[parse.structure.length - 1][1] = parse.count; } } else if (data.token[parse.count - 2] === "x}" && pstack[0] !== "if" && data.stack[parse.count] === "else") { elsefix(); } else if (data.token[parse.count - 2] === "}" && data.stack[parse.count - 2] === "if" && pstack[0] === "if" && data.token[pstack[1] - 1] !== "if" && data.token[data.begin[parse.count - 1]] === "x{") { // fixes when "else" is following a block that isn't "if" elsefix(); } } else if (data.token[parse.count] === "x}" && data.stack[parse.count] === "if") { elsefix(); } } if (nextitem !== "if" && nextitem.charAt(0) !== "{") { ltoke = (options.correct === true) ? "{" : "x{"; ltype = "start"; brace.push("x{"); recordPush("else"); } } if ((output === "for" || output === "if" || output === "switch" || output === "catch") && options.language !== "twig" && data.token[parse.count - 1] !== ".") { nextitem = nextchar(1, true); if (nextitem !== "(") { paren = parse.count; if (options.correct === true) { start("("); } else { start("x("); } } } }; do { if ((/\s/).test(c[a]) === true) { if (wordTest > -1) { word(); } a = parse.spacer({array: c, end: b, index: a}); if (parse.linesSpace > 1 && ltoke !== ";" && lengthb < parse.count && c[a + 1] !== "}") { asi(false); lengthb = parse.count; } } else if (c[a] === "<" && c[a + 1] === "?" && c[a + 2] === "p" && c[a + 3] === "h" && c[a + 4] === "p") { // php general("<?php", "?>", "template"); } else if (c[a] === "<" && c[a + 1] === "?" && c[a + 2] === "=") { // php general("<?=", "?>", "template"); } else if (c[a] === "<" && c[a + 1] === "%") { // asp general("<%", "%>", "template"); } else if (c[a] === "{" && c[a + 1] === "%") { // twig general("{%", "%}", "template"); } else if (c[a] === "{" && c[a + 1] === "{" && c[a + 2] === "{") { // mustache general("{{{", "}}}", "template"); } else if (c[a] === "{" && c[a + 1] === "{") { // handlebars general("{{", "}}", "template"); } else if (c[a] === "<" && c[a + 1] === "!" && c[a + 2] === "-" && c[a + 3] === "-" && c[a + 4] === "#") { // ssi general("<!--#", "-->", "template"); } else if (c[a] === "<" && c[a + 1] === "!" && c[a + 2] === "-" && c[a + 3] === "-") { // markup comment general("<!--", "-->", "comment"); } else if (c[a] === "<") { // markup markup(); } else if (c[a] === "/" && (a === b - 1 || c[a + 1] === "*")) { // comment block blockComment(); } else if ((parse.count < 0 || data.lines[parse.count] > 0) && c[a] === "#" && c[a + 1] === "!" && (c[a + 2] === "/" || c[a + 2] === "[")) { // shebang general("#!" + c[a + 2], "\n", "string"); } else if (c[a] === "/" && (a === b - 1 || c[a + 1] === "/")) { // comment line lineComment(); } else if (c[a] === "#" && c[a + 1] === "r" && c[a + 2] === "e" && c[a + 3] === "g" && c[a + 4] === "i" && c[a + 5] === "o" && c[a + 6] === "n" && (/\s/).test(c[a + 7]) === true) { // comment line asi(false); general("#region", "\n", "comment"); } else if (c[a] === "#" && c[a + 1] === "e" && c[a + 2] === "n" && c[a + 3] === "d" && c[a + 4] === "r" && c[a + 5] === "e" && c[a + 6] === "g" && c[a + 7] === "i" && c[a + 8] === "o" && c[a + 9] === "n") { // comment line asi(false); general("#endregion", "\n", "comment"); } else if (c[a] === "`" || (c[a] === "}" && parse.structure[parse.structure.length - 1][0] === "template_string")) { // template string if (wordTest > -1) { word(); } ltoke = tempstring(); if (ltoke.charAt(0) === "}" && ltoke.slice(ltoke.length - 2) === "${") { ltype = "template_string_else"; recordPush("template_string"); } else if (ltoke.slice(ltoke.length - 2) === "${") { ltype = "template_string_start"; recordPush("template_string"); } else if (ltoke.charAt(0) === "}") { ltype = "template_string_end"; recordPush(""); } else { ltype = "string"; recordPush(""); } } else if (c[a] === "\"" || c[a] === "'") { // string general(c[a], c[a], "string"); } else if ( c[a] === "-" && (a < b - 1 && c[a + 1] !== "=" && c[a + 1] !== "-") && (ltype === "number" || ltype === "word" || ltype === "reference") && ltoke !== "return" && (ltoke === ")" || ltoke === "]" || ltype === "word" || ltype === "reference" || ltype === "number") ) { // subtraction if (wordTest > -1) { word(); } ltoke = "-"; ltype = "operator"; recordPush(""); } else if (wordTest === -1 && (c[a] !== "0" || (c[a] === "0" && c[a + 1] !== "b")) && ((/\d/).test(c[a]) || (a !== b - 2 && c[a] === "-" && c[a + 1] === "." && (/\d/).test(c[a + 2])) || (a !== b - 1 && (c[a] === "-" || c[a] === ".") && (/\d/).test(c[a + 1])))) { // number if (wordTest > -1) { word(); } if (ltype === "end" && c[a] === "-") { ltoke = "-"; ltype = "operator"; } else { ltoke = numb(); ltype = "number"; } recordPush(""); } else if (c[a] === ":" && c[a + 1] === ":") { if (wordTest > -1) { word(); } if (options.correct === true) { plusplus(); } asifix(); a = a + 1; ltoke = "::"; ltype = "separator"; recordPush(""); } else if (c[a] === ",") { // comma if (wordTest > -1) { word(); } if (options.correct === true) { plusplus(); } if (datatype[datatype.length - 1] === true && data.stack[parse.count].indexOf("type") < 0) { datatype[datatype.length - 1] = false; } if (ltype === "comment") { commaComment(); } else if (vart.len > -1 && vart.count[vart.len] === 0 && options.lexer_options.script.variable_list === "each") { asifix(); ltoke = ";"; ltype = "separator"; recordPush(""); ltoke = vart.word[vart.len]; ltype = "word"; recordPush(""); vart.index[vart.len] = parse.count; } else { ltoke = ","; ltype = "separator"; asifix(); recordPush(""); } } else if (c[a] === ".") { // period if (wordTest > -1) { word(); } datatype[datatype.length - 1] = false; if (c[a + 1] === "." && c[a + 2] === ".") { ltoke = "..."; ltype = "operator"; a = a + 2; } else { asifix(); ltoke = "."; ltype = "separator"; } if ((/\s/).test(c[a - 1]) === true) { parse.linesSpace = 1; } recordPush(""); } else if (c[a] === ";") { // semicolon if (wordTest > -1) { word(); } if (datatype[datatype.length - 1] === true && data.stack[parse.count].indexOf("type") < 0) { datatype[datatype.length - 1] = false; } if (options.language === "qml") { ltoke = (options.correct === true) ? ";" : "x;"; ltype = "separator"; recordPush(""); } else { if (classy[classy.length - 1] === 0) { classy.pop(); } if (vart.len > -1 && vart.count[vart.len] === 0) { if (options.lexer_options.script.variable_list === "each") { vartpop(); } else { vart.index[vart.len] = parse.count + 1; } } if (options.correct === true) { plusplus(); } ltoke = ";"; ltype = "separator"; if (data.token[parse.count] === "x}") { asibrace(); } else { recordPush(""); } } blockinsert(); } else if (c[a] === "(" || c[a] === "[" || c[a] === "{") { start(c[a]); } else if (c[a] === ")" || c[a] === "]" || c[a] === "}") { end(c[a]); } else if (c[a] === "*" && data.stack[parse.count] === "object" && wordTest < 0 && (/\s/).test(c[a + 1]) === false && c[a + 1] !== "=" && (/\d/).test(c[a + 1]) === false) { wordTest = a; } else if (c[a] === "=" || c[a] === "&" || c[a] === "<" || c[a] === ">" || c[a] === "+" || c[a] === "-" || c[a] === "*" || c[a] === "/" || c[a] === "!" || c[a] === "?" || c[a] === "|" || c[a] === "^" || c[a] === ":" || c[a] === "%" || c[a] === "~") { // operator ltoke = operator(); if (ltoke === "regex") { ltoke = data.token[parse.count]; } else if (ltoke === "*" && data.token[parse.count] === "function") { data.token[parse.count] = "function*"; } else { ltype = "operator"; if (ltoke !== "!" && ltoke !== "++" && ltoke !== "--") { asifix(); } recordPush(""); } } else if (wordTest < 0 && c[a] !== "") { wordTest = a; } if (vart.len > -1 && parse.count === vart.index[vart.len] + 1 && data.token[vart.index[vart.len]] === ";" && ltoke !== vart.word[vart.len] && ltype !== "comment" && options.lexer_options.script.variable_list === "list") { vartpop(); } a = a + 1; } while (a < b); if (wordTest > -1) { word(); } if (((data.token[parse.count] !== "}" && data.token[0] === "{") || data.token[0] !== "{") && ((data.token[parse.count] !== "]" && data.token[0] === "[") || data.token[0] !== "[")) { asi(false); } if (sourcemap[0] === parse.count) { ltoke = "\n" + sourcemap[1]; ltype = "string"; recordPush(""); } if (data.token[parse.count] === "x;" && (data.token[parse.count - 1] === "}" || data.token[parse.count - 1] === "]") && data.begin[parse.count - 1] === 0) { parse.pop(data); } return data; }; sparser.lexers.script = script; }());
the_stack
'use strict'; import { IntegrationsSettings, InitOptions, SegmentAnalytics, SegmentOpts, SegmentIntegration } from './types'; var _analytics = global.analytics; /* * Module dependencies. */ var Alias = require('segmentio-facade').Alias; var Emitter = require('component-emitter'); var Facade = require('segmentio-facade'); var Group = require('segmentio-facade').Group; var Identify = require('segmentio-facade').Identify; var SourceMiddlewareChain = require('./middleware').SourceMiddlewareChain; var IntegrationMiddlewareChain = require('./middleware') .IntegrationMiddlewareChain; var DestinationMiddlewareChain = require('./middleware') .DestinationMiddlewareChain; var Page = require('segmentio-facade').Page; var Track = require('segmentio-facade').Track; var bindAll = require('bind-all'); var clone = require('./utils/clone'); var extend = require('extend'); var cookie = require('./cookie'); var metrics = require('./metrics'); var debug = require('debug'); var defaults = require('@ndhoule/defaults'); var each = require('./utils/each'); var group = require('./group'); var is = require('is'); var isMeta = require('@segment/is-meta'); var keys = require('@ndhoule/keys'); var memory = require('./memory'); var nextTick = require('next-tick'); var normalize = require('./normalize'); var on = require('component-event').bind; var pageDefaults = require('./pageDefaults'); var pick = require('@ndhoule/pick'); var prevent = require('@segment/prevent-default'); var url = require('component-url'); var store = require('./store'); var user = require('./user'); var type = require('component-type'); /** * Initialize a new `Analytics` instance. */ function Analytics() { this._options({}); this.Integrations = {}; this._sourceMiddlewares = new SourceMiddlewareChain(); this._integrationMiddlewares = new IntegrationMiddlewareChain(); this._destinationMiddlewares = {}; this._integrations = {}; this._readied = false; this._timeout = 300; // XXX: BACKWARDS COMPATIBILITY this._user = user; this.log = debug('analytics.js'); bindAll(this); var self = this; this.on('initialize', function(settings, options) { if (options.initialPageview) self.page(); self._parseQuery(window.location.search); }); } /** * Mix in event emitter. */ Emitter(Analytics.prototype); /** * Use a `plugin`. */ Analytics.prototype.use = function( plugin: (analytics: SegmentAnalytics) => void ): SegmentAnalytics { plugin(this); return this; }; /** * Define a new `Integration`. */ Analytics.prototype.addIntegration = function( Integration: (options: SegmentOpts) => void ): SegmentAnalytics { var name = Integration.prototype.name; if (!name) throw new TypeError('attempted to add an invalid integration'); this.Integrations[name] = Integration; return this; }; /** * Define a new `SourceMiddleware` */ Analytics.prototype.addSourceMiddleware = function( middleware: Function ): SegmentAnalytics { this._sourceMiddlewares.add(middleware); return this; }; /** * Define a new `IntegrationMiddleware` * @deprecated */ Analytics.prototype.addIntegrationMiddleware = function( middleware: Function ): SegmentAnalytics { this._integrationMiddlewares.add(middleware); return this; }; /** * Define a new `DestinationMiddleware` * Destination Middleware is chained after integration middleware */ Analytics.prototype.addDestinationMiddleware = function( integrationName: string, middlewares: Array<unknown> ): SegmentAnalytics { var self = this; middlewares.forEach(function(middleware) { if (!self._destinationMiddlewares[integrationName]) { self._destinationMiddlewares[ integrationName ] = new DestinationMiddlewareChain(); } self._destinationMiddlewares[integrationName].add(middleware); }); return self; }; /** * Initialize with the given integration `settings` and `options`. * * Aliased to `init` for convenience. */ Analytics.prototype.init = Analytics.prototype.initialize = function( settings?: IntegrationsSettings, options?: InitOptions ): SegmentAnalytics { settings = settings || {}; options = options || {}; this._options(options); this._readied = false; // clean unknown integrations from settings var self = this; each(function(_opts: unknown, name: string | number) { var Integration = self.Integrations[name]; if (!Integration) delete settings[name]; }, settings); // add integrations each(function(opts: unknown, name: string | number) { // Don't load disabled integrations if (options.integrations) { if ( options.integrations[name] === false || (options.integrations.All === false && !options.integrations[name]) ) { return; } } var Integration = self.Integrations[name]; var clonedOpts = {}; extend(true, clonedOpts, opts); // deep clone opts var integration = new Integration(clonedOpts); self.log('initialize %o - %o', name, opts); self.add(integration); }, settings); var integrations = this._integrations; // load user now that options are set user.load(); group.load(); // make ready callback var readyCallCount = 0; var integrationCount = keys(integrations).length; var ready = function() { readyCallCount++; if (readyCallCount >= integrationCount) { self._readied = true; self.emit('ready'); } }; // init if no integrations if (integrationCount <= 0) { ready(); } // initialize integrations, passing ready // create a list of any integrations that did not initialize - this will be passed with all events for replay support: this.failedInitializations = []; var initialPageSkipped = false; each(function(integration) { if ( options.initialPageview && integration.options.initialPageview === false ) { // We've assumed one initial pageview, so make sure we don't count the first page call. var page = integration.page; integration.page = function() { if (initialPageSkipped) { return page.apply(this, arguments); } initialPageSkipped = true; return; }; } integration.analytics = self; integration.once('ready', ready); try { metrics.increment('analytics_js.integration.invoke', { method: 'initialize', integration_name: integration.name }); integration.initialize(); } catch (e) { var integrationName = integration.name; metrics.increment('analytics_js.integration.invoke.error', { method: 'initialize', integration_name: integration.name }); self.failedInitializations.push(integrationName); self.log('Error initializing %s integration: %o', integrationName, e); // Mark integration as ready to prevent blocking of anyone listening to analytics.ready() integration.ready(); } }, integrations); // backwards compat with angular plugin and used for init logic checks this.initialized = true; this.emit('initialize', settings, options); return this; }; /** * Set the user's `id`. */ Analytics.prototype.setAnonymousId = function(id: string): SegmentAnalytics { this.user().anonymousId(id); return this; }; /** * Add an integration. */ Analytics.prototype.add = function(integration: { name: string | number; }): SegmentAnalytics { this._integrations[integration.name] = integration; return this; }; /** * Identify a user by optional `id` and `traits`. * * @param {string} [id=user.id()] User ID. * @param {Object} [traits=null] User traits. * @param {Object} [options=null] * @param {Function} [fn] * @return {Analytics} */ Analytics.prototype.identify = function( id?: string, traits?: unknown, options?: SegmentOpts, fn?: Function | SegmentOpts ): SegmentAnalytics { // Argument reshuffling. /* eslint-disable no-unused-expressions, no-sequences */ if (is.fn(options)) (fn = options), (options = null); if (is.fn(traits)) (fn = traits), (options = null), (traits = null); if (is.object(id)) (options = traits), (traits = id), (id = user.id()); /* eslint-enable no-unused-expressions, no-sequences */ // clone traits before we manipulate so we don't do anything uncouth, and take // from `user` so that we carryover anonymous traits user.identify(id, traits); var msg = this.normalize({ options: options, traits: user.traits(), userId: user.id() }); // Add the initialize integrations so the server-side ones can be disabled too if (this.options.integrations) { defaults(msg.integrations, this.options.integrations); } this._invoke('identify', new Identify(msg)); // emit this.emit('identify', id, traits, options); this._callback(fn); return this; }; /** * Return the current user. * * @return {Object} */ Analytics.prototype.user = function(): object { return user; }; /** * Identify a group by optional `id` and `traits`. Or, if no arguments are * supplied, return the current group. * * @param {string} [id=group.id()] Group ID. * @param {Object} [traits=null] Group traits. * @param {Object} [options=null] * @param {Function} [fn] * @return {Analytics|Object} */ Analytics.prototype.group = function( id: string, traits?: unknown, options?: unknown, fn?: unknown ): SegmentAnalytics { /* eslint-disable no-unused-expressions, no-sequences */ if (!arguments.length) return group; if (is.fn(options)) (fn = options), (options = null); if (is.fn(traits)) (fn = traits), (options = null), (traits = null); if (is.object(id)) (options = traits), (traits = id), (id = group.id()); /* eslint-enable no-unused-expressions, no-sequences */ // grab from group again to make sure we're taking from the source group.identify(id, traits); var msg = this.normalize({ options: options, traits: group.traits(), groupId: group.id() }); // Add the initialize integrations so the server-side ones can be disabled too if (this.options.integrations) { defaults(msg.integrations, this.options.integrations); } this._invoke('group', new Group(msg)); this.emit('group', id, traits, options); this._callback(fn); return this; }; /** * Track an `event` that a user has triggered with optional `properties`. * * @param {string} event * @param {Object} [properties=null] * @param {Object} [options=null] * @param {Function} [fn] * @return {Analytics} */ Analytics.prototype.track = function( event: string, properties?: unknown, options?: unknown, fn?: unknown ): SegmentAnalytics { // Argument reshuffling. /* eslint-disable no-unused-expressions, no-sequences */ if (is.fn(options)) (fn = options), (options = null); if (is.fn(properties)) (fn = properties), (options = null), (properties = null); /* eslint-enable no-unused-expressions, no-sequences */ // figure out if the event is archived. var plan = this.options.plan || {}; var events = plan.track || {}; var planIntegrationOptions = {}; // normalize var msg = this.normalize({ properties: properties, options: options, event: event }); // plan. plan = events[event]; if (plan) { this.log('plan %o - %o', event, plan); if (plan.enabled === false) { // Disabled events should always be sent to Segment. planIntegrationOptions = { All: false, 'Segment.io': true }; } else { planIntegrationOptions = plan.integrations || {}; } } else { var defaultPlan = events.__default || { enabled: true }; if (!defaultPlan.enabled) { // Disabled events should always be sent to Segment. planIntegrationOptions = { All: false, 'Segment.io': true }; } } // Add the initialize integrations so the server-side ones can be disabled too defaults( msg.integrations, this._mergeInitializeAndPlanIntegrations(planIntegrationOptions) ); this._invoke('track', new Track(msg)); this.emit('track', event, properties, options); this._callback(fn); return this; }; /** * Helper method to track an outbound link that would normally navigate away * from the page before the analytics calls were sent. * * BACKWARDS COMPATIBILITY: aliased to `trackClick`. * * @param {Element|Array} links * @param {string|Function} event * @param {Object|Function} properties (optional) * @return {Analytics} */ Analytics.prototype.trackClick = Analytics.prototype.trackLink = function( links: Element | Array<unknown>, event: any, properties?: any ): SegmentAnalytics { if (!links) return this; // always arrays, handles jquery if (type(links) === 'element') links = [links]; var self = this; each(function(el) { if (type(el) !== 'element') { throw new TypeError('Must pass HTMLElement to `analytics.trackLink`.'); } on(el, 'click', function(e) { var ev = is.fn(event) ? event(el) : event; var props = is.fn(properties) ? properties(el) : properties; var href = el.getAttribute('href') || el.getAttributeNS('http://www.w3.org/1999/xlink', 'href') || el.getAttribute('xlink:href'); self.track(ev, props); if (href && el.target !== '_blank' && !isMeta(e)) { prevent(e); self._callback(function() { window.location.href = href; }); } }); }, links); return this; }; /** * Helper method to track an outbound form that would normally navigate away * from the page before the analytics calls were sent. * * BACKWARDS COMPATIBILITY: aliased to `trackSubmit`. * * @param {Element|Array} forms * @param {string|Function} event * @param {Object|Function} properties (optional) * @return {Analytics} */ Analytics.prototype.trackSubmit = Analytics.prototype.trackForm = function( forms: Element | Array<unknown>, event: any, properties?: any ): SegmentAnalytics { if (!forms) return this; // always arrays, handles jquery if (type(forms) === 'element') forms = [forms]; var self = this; each(function(el: { submit: () => void }) { if (type(el) !== 'element') throw new TypeError('Must pass HTMLElement to `analytics.trackForm`.'); function handler(e) { prevent(e); var ev = is.fn(event) ? event(el) : event; var props = is.fn(properties) ? properties(el) : properties; self.track(ev, props); self._callback(function() { el.submit(); }); } // Support the events happening through jQuery or Zepto instead of through // the normal DOM API, because `el.submit` doesn't bubble up events... var $ = window.jQuery || window.Zepto; if ($) { $(el).submit(handler); } else { on(el, 'submit', handler); } }, forms); return this; }; /** * Trigger a pageview, labeling the current page with an optional `category`, * `name` and `properties`. * * @param {string} [category] * @param {string} [name] * @param {Object|string} [properties] (or path) * @param {Object} [options] * @param {Function} [fn] * @return {Analytics} */ Analytics.prototype.page = function( category?: string, name?: string, properties?: any, options?: any, fn?: unknown ): SegmentAnalytics { // Argument reshuffling. /* eslint-disable no-unused-expressions, no-sequences */ if (is.fn(options)) (fn = options), (options = null); if (is.fn(properties)) (fn = properties), (options = properties = null); if (is.fn(name)) (fn = name), (options = properties = name = null); if (type(category) === 'object') (options = name), (properties = category), (name = category = null); if (type(name) === 'object') (options = properties), (properties = name), (name = null); if (type(category) === 'string' && type(name) !== 'string') (name = category), (category = null); /* eslint-enable no-unused-expressions, no-sequences */ properties = clone(properties) || {}; if (name) properties.name = name; if (category) properties.category = category; // Ensure properties has baseline spec properties. // TODO: Eventually move these entirely to `options.context.page` var defs = pageDefaults(); defaults(properties, defs); // Mirror user overrides to `options.context.page` (but exclude custom properties) // (Any page defaults get applied in `this.normalize` for consistency.) // Weird, yeah--moving special props to `context.page` will fix this in the long term. var overrides = pick(keys(defs), properties); if (!is.empty(overrides)) { options = options || {}; options.context = options.context || {}; options.context.page = overrides; } var msg = this.normalize({ properties: properties, category: category, options: options, name: name }); // Add the initialize integrations so the server-side ones can be disabled too if (this.options.integrations) { defaults(msg.integrations, this.options.integrations); } this._invoke('page', new Page(msg)); this.emit('page', category, name, properties, options); this._callback(fn); return this; }; /** * FIXME: BACKWARDS COMPATIBILITY: convert an old `pageview` to a `page` call. * @api private */ Analytics.prototype.pageview = function(url: string): SegmentAnalytics { const properties: { path?: string } = {}; if (url) properties.path = url; this.page(properties); return this; }; /** * Merge two previously unassociated user identities. * * @param {string} to * @param {string} from (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ Analytics.prototype.alias = function( to: string, from?: string, options?: unknown, fn?: unknown ): SegmentAnalytics { // Argument reshuffling. /* eslint-disable no-unused-expressions, no-sequences */ if (is.fn(options)) (fn = options), (options = null); if (is.fn(from)) (fn = from), (options = null), (from = null); if (is.object(from)) (options = from), (from = null); /* eslint-enable no-unused-expressions, no-sequences */ var msg = this.normalize({ options: options, previousId: from, userId: to }); // Add the initialize integrations so the server-side ones can be disabled too if (this.options.integrations) { defaults(msg.integrations, this.options.integrations); } this._invoke('alias', new Alias(msg)); this.emit('alias', to, from, options); this._callback(fn); return this; }; /** * Register a `fn` to be fired when all the analytics services are ready. */ Analytics.prototype.ready = function(fn: Function): SegmentAnalytics { if (is.fn(fn)) { if (this._readied) { nextTick(fn); } else { this.once('ready', fn); } } return this; }; /** * Set the `timeout` (in milliseconds) used for callbacks. */ Analytics.prototype.timeout = function(timeout: number) { this._timeout = timeout; }; /** * Enable or disable debug. */ Analytics.prototype.debug = function(str: string | boolean) { if (!arguments.length || str) { debug.enable('analytics:' + (str || '*')); } else { debug.disable(); } }; /** * Apply options. * @api private */ Analytics.prototype._options = function( options: InitOptions ): SegmentAnalytics { options = options || {}; this.options = options; cookie.options(options.cookie); metrics.options(options.metrics); store.options(options.localStorage); user.options(options.user); group.options(options.group); return this; }; /** * Callback a `fn` after our defined timeout period. * @api private */ Analytics.prototype._callback = function(fn: Function): SegmentAnalytics { if (is.fn(fn)) { this._timeout ? setTimeout(fn, this._timeout) : nextTick(fn); } return this; }; /** * Call `method` with `facade` on all enabled integrations. * * @param {string} method * @param {Facade} facade * @return {Analytics} * @api private */ Analytics.prototype._invoke = function( method: string, facade: unknown ): SegmentAnalytics { var self = this; try { this._sourceMiddlewares.applyMiddlewares( extend(true, new Facade({}), facade), this._integrations, function(result) { // A nullified payload should not be sent. if (result === null) { self.log( 'Payload with method "%s" was null and dropped by source a middleware.', method ); return; } // Check if the payload is still a Facade. If not, convert it to one. if (!(result instanceof Facade)) { result = new Facade(result); } self.emit('invoke', result); metrics.increment('analytics_js.invoke', { method: method }); applyIntegrationMiddlewares(result); } ); } catch (e) { metrics.increment('analytics_js.invoke.error', { method: method }); self.log( 'Error invoking .%s method of %s integration: %o', method, name, e ); } return this; function applyIntegrationMiddlewares(facade) { var failedInitializations = self.failedInitializations || []; each(function(integration, name) { var facadeCopy = extend(true, new Facade({}), facade); if (!facadeCopy.enabled(name)) return; // Check if an integration failed to initialize. // If so, do not process the message as the integration is in an unstable state. if (failedInitializations.indexOf(name) >= 0) { self.log( 'Skipping invocation of .%s method of %s integration. Integration failed to initialize properly.', method, name ); } else { try { // Apply any integration middlewares that exist, then invoke the integration with the result. self._integrationMiddlewares.applyMiddlewares( facadeCopy, integration.name, function(result) { // A nullified payload should not be sent to an integration. if (result === null) { self.log( 'Payload to integration "%s" was null and dropped by a middleware.', name ); return; } // Check if the payload is still a Facade. If not, convert it to one. if (!(result instanceof Facade)) { result = new Facade(result); } // apply destination middlewares // Apply any integration middlewares that exist, then invoke the integration with the result. if (self._destinationMiddlewares[integration.name]) { self._destinationMiddlewares[integration.name].applyMiddlewares( facadeCopy, integration.name, function(result) { // A nullified payload should not be sent to an integration. if (result === null) { self.log( 'Payload to destination "%s" was null and dropped by a middleware.', name ); return; } // Check if the payload is still a Facade. If not, convert it to one. if (!(result instanceof Facade)) { result = new Facade(result); } metrics.increment('analytics_js.integration.invoke', { method: method, integration_name: integration.name }); integration.invoke.call(integration, method, result); } ); } else { metrics.increment('analytics_js.integration.invoke', { method: method, integration_name: integration.name }); integration.invoke.call(integration, method, result); } } ); } catch (e) { metrics.increment('analytics_js.integration.invoke.error', { method: method, integration_name: integration.name }); self.log( 'Error invoking .%s method of %s integration: %o', method, name, e ); } } }, self._integrations); } }; /** * Push `args`. * * @param {Array} args * @api private */ Analytics.prototype.push = function(args: any[]) { var method = args.shift(); if (!this[method]) return; this[method].apply(this, args); }; /** * Reset group and user traits and id's. * * @api public */ Analytics.prototype.reset = function() { this.user().logout(); this.group().logout(); }; /** * Parse the query string for callable methods. * * @api private */ Analytics.prototype._parseQuery = function(query: string): SegmentAnalytics { // Parse querystring to an object const parsed = url.parse(query); const q = parsed.query.split('&').reduce((acc, str) => { const [k, v] = str.split('='); acc[k] = decodeURI(v).replace('+', ' '); return acc; }, {}); // Create traits and properties objects, populate from querysting params var traits = pickPrefix('ajs_trait_', q); var props = pickPrefix('ajs_prop_', q); // Trigger based on callable parameters in the URL if (q.ajs_uid) this.identify(q.ajs_uid, traits); if (q.ajs_event) this.track(q.ajs_event, props); if (q.ajs_aid) user.anonymousId(q.ajs_aid); return this; /** * Create a shallow copy of an input object containing only the properties * whose keys are specified by a prefix, stripped of that prefix * * @return {Object} * @api private */ function pickPrefix(prefix: string, object: object) { var length = prefix.length; var sub; return Object.keys(object).reduce(function(acc, key) { if (key.substr(0, length) === prefix) { sub = key.substr(length); acc[sub] = object[key]; } return acc; }, {}); } }; /** * Normalize the given `msg`. */ Analytics.prototype.normalize = function(msg: { context: { page }; anonymousId: string; }): object { msg = normalize(msg, keys(this._integrations)); if (msg.anonymousId) user.anonymousId(msg.anonymousId); msg.anonymousId = user.anonymousId(); // Ensure all outgoing requests include page data in their contexts. msg.context.page = defaults(msg.context.page || {}, pageDefaults()); return msg; }; /** * Merges the tracking plan and initialization integration options. * * @param {Object} planIntegrations Tracking plan integrations. * @return {Object} The merged integrations. */ Analytics.prototype._mergeInitializeAndPlanIntegrations = function( planIntegrations: SegmentIntegration ): object { // Do nothing if there are no initialization integrations if (!this.options.integrations) { return planIntegrations; } // Clone the initialization integrations var integrations = extend({}, this.options.integrations); var integrationName: string; // Allow the tracking plan to disable integrations that were explicitly // enabled on initialization if (planIntegrations.All === false) { integrations = { All: false }; } for (integrationName in planIntegrations) { if (planIntegrations.hasOwnProperty(integrationName)) { // Don't allow the tracking plan to re-enable disabled integrations if (this.options.integrations[integrationName] !== false) { integrations[integrationName] = planIntegrations[integrationName]; } } } return integrations; }; /** * No conflict support. */ Analytics.prototype.noConflict = function(): SegmentAnalytics { window.analytics = _analytics; return this; }; /* * Exports. */ module.exports = Analytics; module.exports.cookie = cookie; module.exports.memory = memory; module.exports.store = store; module.exports.metrics = metrics;
the_stack
import { Disposable } from '../dispose' import { Hub } from '../hub/index' import { Forward } from '../hub/index' /** Creates a timeout that throws with the given error message. */ function timeout<T=any>(ms: number, message: string = 'timeout'): Promise<T> { return new Promise<T>((_, reject) => { setTimeout(() => reject(new Error(message)), ms) }) } /** Receives exactly one message from this data channel. */ function receive<T=any>(channel: RTCDataChannel, eventName: string): Promise<T> { return new Promise<T>(resolve => { channel.addEventListener(eventName, function handler(event) { channel.removeEventListener(eventName, handler) resolve(event as any) }) }) } enum Loopback { None = 0, Sender = 1, Receiver = 2 } const loopbackSwitch = (loopback: Loopback) => loopback === Loopback.Receiver ? Loopback.Sender : loopback === Loopback.Sender ? Loopback.Receiver : loopback export class NegotiateError extends Error { constructor( public readonly local: string, public readonly remote: string, public readonly error: Error, public readonly sdp?: RTCSessionDescriptionInit | RTCIceCandidate ) { super(`local: ${local} remote: ${remote} error: ${error.message}`) } } export class SignallingError extends Error { constructor(public readonly remote: string, public readonly error: Error) { super(`remote: ${remote} error: ${error.message}`) } } export class PortInUseError extends Error { constructor(public readonly port: string) { super(`The port '${port}' is already in use.`) } } interface Candidate { type: 'candidate', loopback: Loopback, candidate: RTCIceCandidate } interface Offer { type: 'offer', loopback: Loopback, sdp: RTCSessionDescriptionInit } interface Answer { type: 'answer', loopback: Loopback , sdp: RTCSessionDescriptionInit } type Protocol = Candidate | Offer | Answer /** A function to receive channels on. */ export type PortListenFunction = (event: [Peer, RTCDataChannel]) => void /** A container type for a peer connection. */ export interface Peer { connection: RTCPeerConnection loopback: Loopback local: string remote: string } /** * A webrtc peer connection and negotiation layer. This type is intended * to handle the details of peers, peer signalling, port binding and * client loopback. This type is used by RTC consumers to interact with * peer connections without dealing with the details of ICE. */ export class Network implements Disposable { private ports: Map<string, PortListenFunction> private peers: Map<string, Peer> constructor(private hub: Hub) { this.hub.on('forward', forward => this.onForward(forward)) this.ports = new Map<string, PortListenFunction>() this.peers = new Map<string, Peer>() this.createLoopback() } /** Gets the address of this peer on the network. */ public address(): Promise<string> { return this.hub.address() } /** Gets all peers managed by this driver. */ public getPeers(): Map<string, Peer> { return this.peers } /** * Connects to a remote endpoint and returns a Peer and RTCDataChannel. This * function handles connection negotiate with the remote peer as well as * handling network timeouts and remote port reject. The data channel * returned from this function is given in an 'open' state ready for use. */ public async connect(remote: string, port: string): Promise<[Peer, RTCDataChannel]> { remote = (remote === await this.hub.address() || remote === 'localhost') ? 'localhost:1' : remote const peer = await this.getPeer(remote) const channel = peer.connection.createDataChannel(port) channel.binaryType = 'arraybuffer' // wait for connection await Promise.race([ timeout(4000, `Connection to host '${peer.remote}' timed out.`), receive(channel, 'open') ]) // wait for accept | reject const response = await Promise.race([ timeout<MessageEvent>(4000, `${peer.remote}' is not responding.`), receive<MessageEvent>(channel, 'message') ]).then(response => new Uint8Array(response.data)) // resolve or reject if(response[0] === 1) { channel.close() throw Error(`'${peer.remote}' forcefully closed this connection.`) } else { return [peer, channel] } } /** * Binds the given port to accept remote peer connections on. Data channels * passed on this callback passed in an 'open' state ready for immediate use. */ public bindPort(port: string, callback: PortListenFunction) { if (this.ports.has(port)) { throw new PortInUseError(port) } this.ports.set(port, callback) } /** * Unbinds the given port preventing further connections to be received on * this port. This function does not close existing connections on the port, * so callers will need to explicitly terminate all active connections * manually. */ public unbindPort(port: string) { this.ports.delete(port) } /** Disposes of this object. */ public dispose(): void { for (const key of this.peers.keys()) { const peer = this.peers.get(key)! peer.connection.close() this.peers.delete(key) } } // #region Peer resolver /** Gets or creates a peer to the remote endpoint. */ public async getPeer(remote: string): Promise<Peer> { const configuration = await this.hub.configuration() const local = await this.hub.address() if (!this.peers.has(remote)) { const connection = new RTCPeerConnection(configuration) const loopback = Loopback.None const peer = { connection, local, remote, loopback } connection.addEventListener('negotiationneeded', event => this.onNegotiationNeeded(peer, event)) connection.addEventListener('icecandidate', event => this.onIceCandidate(peer, event)) connection.addEventListener('datachannel', event => this.onDataChannel(peer, event)) this.peers.set(remote, peer) } return this.peers.get(remote)! } // #region Signalling /** * Forwards a signalling message over to a remote host. This function tries * to optimize here by detecting forwards on localhost. These are intercepted * before making to the signalling hub. */ private async forward<T extends Protocol>(remote: string, data: T) { if (remote === 'localhost') { const type = 'forward' const from = 'localhost' const to = 'localhost' return this.onForward({ type, to, from, data }) } this.hub.forward<T>(remote, data) } /** * Dispatches incoming forwarded messages out to their respective handlers. */ private onForward(request: Forward<Protocol>) { switch (request.data.type) { case 'candidate': this.onCandidate(request as Forward<Candidate>); break case 'answer': this.onAnswer(request as Forward<Answer>); break case 'offer': this.onOffer(request as Forward<Offer>); break } } /** * Handles incoming offers from remote peers */ private async onOffer(request: Forward<Offer>): Promise<void> { try { const peer = await this.getPeer(this.resolveLoopbackTarget(request)) await peer.connection.setRemoteDescription(request.data.sdp) const sdp = await peer.connection.createAnswer() const loopback = loopbackSwitch(request.data.loopback) await peer.connection.setLocalDescription(sdp) await this.forward<Answer>(request.from, { type: 'answer', sdp, loopback }) } catch (error) { const local = request.to const remote = request.from console.warn(new NegotiateError(local, remote, error, request.data.sdp)) } } /** * Handles incoming answers from remote peers */ private async onAnswer(request: Forward<Answer>): Promise<void> { try { const peer = await this.getPeer(this.resolveLoopbackTarget(request)) await peer.connection.setRemoteDescription(request.data.sdp) } catch (error) { console.warn(new NegotiateError(request.to, request.from, error, request.data.sdp)) } } /** * Handles incoming candidates from remote peers */ private async onCandidate(request: Forward<Candidate>): Promise<void> { try { const peer = await this.getPeer(this.resolveLoopbackTarget(request)) await peer.connection.addIceCandidate(request.data.candidate) } catch (error) { console.warn( new NegotiateError(request.to, request.from, error, request.data.candidate) ) } } // #region RTCPeerConnection events private async onNegotiationNeeded(peer: Peer, event: Event) { try { const sdp = await peer.connection.createOffer() const loopback = peer.loopback await peer.connection.setLocalDescription(sdp) await this.forward<Offer>(peer.remote, { type: 'offer', sdp, loopback }) } catch (error) { const local = peer.local const remote = peer.remote console.warn(new NegotiateError(local, remote, error)) } } private onIceCandidate(peer: Peer, event: RTCPeerConnectionIceEvent) { if (event.candidate === null) { return } try { const candidate = event.candidate const loopback = peer.loopback this.forward<Candidate>(peer.remote, { type: 'candidate', candidate, loopback }) } catch (error) { console.error(new NegotiateError( peer.local, peer.remote, error)) } } /** * Receives an incoming data channel from a remote peer. This function will * tests that this peer is listening on the given port, and if so, emits * to that ports listener, otherwise, the socket is sent a rejection signal * and closed. */ private async onDataChannel(peer: Peer, event: RTCDataChannelEvent) { const port = event.channel.label const channel = event.channel channel.binaryType = 'arraybuffer' try { await Promise.race([ timeout(2000, `Received connection from ${peer.remote} failed to open.`), receive(channel, 'open') ]) if (!this.ports.has(port)) { channel.send(new Uint8Array([1])) channel.close() } else { channel.send(new Uint8Array([0])) const callback = this.ports.get(port)! callback([ peer, channel ]) } } catch { /** ignore */ } } // #region Loopback and Routing /** * Sets up the peer connections for localhost. localhost:0 is for outbound * connections, localhost:1 is for inbound. Therefore when connections are * created on localhost, they are always connecting to the localhost:1 * connection. */ private createLoopback() { { const connection = new RTCPeerConnection() const loopback = Loopback.Sender const local = 'localhost' const remote = 'localhost' const peer = { connection, local, remote, loopback } connection.addEventListener('negotiationneeded', event => this.onNegotiationNeeded(peer, event)) connection.addEventListener('icecandidate', event => this.onIceCandidate(peer, event)) connection.addEventListener('datachannel', event => this.onDataChannel(peer, event)) this.peers.set('localhost:0', peer) } { const connection = new RTCPeerConnection() const loopback = Loopback.Receiver const local = 'localhost' const remote = 'localhost' const peer = { connection, local, remote, loopback } connection.addEventListener('negotiationneeded', event => this.onNegotiationNeeded(peer, event)) connection.addEventListener('icecandidate', event => this.onIceCandidate(peer, event)) connection.addEventListener('datachannel', event => this.onDataChannel(peer, event)) this.peers.set('localhost:1', peer) } } /** * Resolves the loopback target. This function acts as a switch which flips * between localhost:0 and localhost:1 if the loopback happens to be on * localhost. Used during connection negotiate. */ private resolveLoopbackTarget(request: Forward<Protocol>) { return request.data.loopback === Loopback.Sender ? 'localhost:1' : request.data.loopback === Loopback.Receiver ? 'localhost:0' : request.from } }
the_stack
import { Where, WhereParamsByIdentifierI, WhereParamsI } from '../Where'; import { Neo4jSupportedProperties, NeogmaModel } from '../..'; /** returns the given type, while making the given properties required */ type RequiredProperties<T, P extends keyof T> = T & { [key in P]-?: Required<NonNullable<T[key]>>; }; export type ParameterI = | RawI | MatchI | CreateI | MergeI | SetI | DeleteI | RemoveI | ReturnI | OrderByI | UnwindI | ForEachI | LimitI | SkipI | WithI | WhereI | null | undefined; /** raw string to be used as is in the query */ export type RawI = { /** will used as is in the query */ raw: string; }; export const isRawParameter = (param: ParameterI): param is RawI => { return !!(param as RawI).raw; }; /** MATCH parameter */ export type MatchI = { /** MATCH parameter */ match: string | MatchNodeI | MatchRelatedI | MatchMultipleI | MatchLiteralI; }; export const isMatchParameter = (param: ParameterI): param is MatchI => { return !!(param as MatchI).match; }; /** matching a single node */ export type MatchNodeI = NodeForMatchI & { /** optional match */ optional?: boolean; }; /** matching a combination of related nodes and relationships */ export type MatchRelatedI = { /** combination of related nodes and relationships */ related: Array<NodeForMatchI | RelationshipForMatchI>; /** optional match */ optional?: boolean; }; export const isMatchRelated = ( param: MatchI['match'], ): param is MatchRelatedI => { return !!(param as MatchRelatedI).related; }; /** matching multiple nodes */ export type MatchMultipleI = { /** multiple nodes */ multiple: NodeForMatchI[]; /** optional match */ optional?: boolean; }; export const isMatchMultiple = ( param: MatchI['match'], ): param is MatchMultipleI => { return !!(param as MatchMultipleI).multiple; }; /** a literal string for matching */ export type MatchLiteralI = { /** literal string */ literal: string; /** optional match */ optional?: string; }; export const isMatchLiteral = ( param: MatchI['match'], ): param is MatchLiteralI => { return !!(param as MatchLiteralI).literal; }; /** CREATE parameter */ export type CreateI = { /** CREATE parameter */ create: string | CreateNodeI | CreateRelatedI | CreateMultipleI; }; export const isCreateParameter = (param: ParameterI): param is CreateI => { return !!(param as CreateI).create; }; /** creating a node */ export type CreateNodeI = NodeForCreateI; /** creating a combination of related nodes and relationships */ export type CreateRelatedI = { /** combination of related nodes and relationships */ related: Array<Partial<NodeForCreateI> | RelationshipForCreateI>; }; export const isCreateRelated = ( param: CreateI['create'], ): param is CreateRelatedI => { return !!(param as CreateRelatedI).related; }; /** creating multiple nodes */ export type CreateMultipleI = { /** multiple nodes */ multiple: NodeForCreateI[]; }; export const isCreateMultiple = ( param: CreateI['create'], ): param is CreateMultipleI => { return !!(param as CreateMultipleI).multiple; }; /** MERGE parameter. Using the same types as CREATE */ export type MergeI = { /** MERGE parameter. Using the same types as CREATE */ merge: string | CreateNodeI | CreateRelatedI | CreateMultipleI; }; export const isMergeParameter = (param: ParameterI): param is MergeI => { return !!(param as MergeI).merge; }; /** DELETE parameter */ export type DeleteI = { /** DELETE parameter */ delete: string | DeleteByIdentifierI | DeleteLiteralI; }; export const isDeleteParameter = (param: ParameterI): param is DeleteI => { return !!(param as DeleteI).delete; }; /** deletes the given identifiers */ export type DeleteByIdentifierI = { /** identifiers to be deleted */ identifiers: string | string[]; /** detach delete */ detach?: boolean; }; export const isDeleteWithIdentifier = ( _param: DeleteI['delete'], ): _param is DeleteByIdentifierI => { const param = _param as DeleteByIdentifierI; return !!param.identifiers; }; /** deletes by using the given literal */ export type DeleteLiteralI = { /** delete literal */ literal: string; /** detach delete */ detach?: boolean; }; export const isDeleteWithLiteral = ( _param: DeleteI['delete'], ): _param is DeleteLiteralI => { const param = _param as DeleteLiteralI; return !!param.literal; }; /** SET parameter */ export type SetI = { /** SET parameter */ set: string | SetObjectI; }; export const isSetParameter = (param: ParameterI): param is SetI => { return !!(param as SetI).set; }; export type SetObjectI = { /** identifier whose properties will be set */ identifier: string; /** properties to set */ properties: Neo4jSupportedProperties; }; // REMOVE parameter export type RemoveI = { // REMOVE parameter remove: string | RemovePropertiesI | RemoveLabelsI; // TODO also array of Properties|Labels }; export const isRemoveParameter = (param: ParameterI): param is RemoveI => { return !!(param as RemoveI).remove; }; /** removes properties of an identifier */ export type RemovePropertiesI = { /** identifier whose properties will be removed */ identifier: string; /** properties to remove */ properties: string | string[]; }; export const isRemoveProperties = ( _param: RemoveI['remove'], ): _param is RemovePropertiesI => { const param = _param as RemovePropertiesI; return !!(param.properties && param.identifier); }; /** removes labels of an identifier */ export type RemoveLabelsI = { /** identifier whose labels will be removed */ identifier: string; /** labels to remove */ labels: string | string[]; }; export const isRemoveLabels = ( _param: RemoveI['remove'], ): _param is RemoveLabelsI => { const param = _param as RemoveLabelsI; return !!(param.labels && param.identifier); }; /** RETURN parameter */ export type ReturnI = { /** RETURN parameter */ return: string | string[] | ReturnObjectI; }; export const isReturnParameter = (param: ParameterI): param is ReturnI => { return !!(param as ReturnI).return; }; export type ReturnObjectI = Array<{ /** identifier to return */ identifier: string; /** returns only this property of the identifier */ property?: string; }>; export const isReturnObject = ( param: ReturnI['return'], ): param is ReturnObjectI => { return ( Array.isArray(param) && param.findIndex( (v) => typeof v !== 'object' || !(v as ReturnObjectI[0]).identifier, ) < 0 ); }; /** LIMIT parameter */ export type LimitI = { limit: string | number }; export const isLimitParameter = (limit: ParameterI): limit is LimitI => { return !!(limit as LimitI).limit; }; /** SKIP parameter */ export type SkipI = { skip: string | number }; export const isSkipParameter = (skip: ParameterI): skip is SkipI => { return !!(skip as SkipI).skip; }; /** WITH parameter */ export type WithI = { with: string | string[] }; export const isWithParameter = (wth: ParameterI): wth is WithI => { return !!(wth as WithI).with; }; /** ORDER BY parameter */ export type OrderByI = { orderBy: | string | Array<string | [string, 'ASC' | 'DESC'] | OrderByObjectI> | OrderByObjectI; }; export type OrderByObjectI = { /** identifier to order */ identifier: string; /** only order this property of the identifier */ property?: string; /** direction of this order */ direction?: 'ASC' | 'DESC'; }; export const isOrderByParameter = ( orderBy: ParameterI, ): orderBy is OrderByI => { return !!(orderBy as OrderByI).orderBy; }; /** UNWIND parameter */ export type UnwindI = { /** UNWIND parameter */ unwind: string | UnwindObjectI; }; export type UnwindObjectI = { /** value to unwind */ value: string; /** unwind value as this */ as: string; }; export const isUnwindParameter = (unwind: ParameterI): unwind is UnwindI => { return !!(unwind as UnwindI).unwind; }; /** WHERE parameter */ export type WhereI = { /** WHERE parameter */ where: string | Where | WhereParamsByIdentifierI; }; export const isWhereParameter = (where: ParameterI): where is WhereI => { return !!(where as WhereI).where; }; /** FOR EACH parameter */ export type ForEachI = { /** FOR EACH parameter */ forEach: string; }; export const isForEachParameter = ( forEach: ParameterI, ): forEach is ForEachI => { return !!(forEach as ForEachI).forEach; }; /** node type which will be used for matching */ export type NodeForMatchI = string | NodeForMatchObjectI; export type NodeForMatchObjectI = { /** a label to use for this node */ label?: string; /** the model of this node. Automatically sets the "label" field */ model?: NeogmaModel<any, any, any, any>; /** identifier for the node */ identifier?: string; /** where parameters for matching this node */ where?: WhereParamsI; }; /** node type which will be used for creating/merging */ export type NodeForCreateI = | string | NodeForCreateWithLabelI | NodeForCreateWithModelI; export type NodeForCreateObjectI = | NodeForCreateWithLabelI | NodeForCreateWithModelI; /** node type used for creating/merging, using a label */ export type NodeForCreateWithLabelI = { /** identifier for the node */ identifier?: string; /** a label to use for this node */ label: string; /** properties of the node */ properties?: Neo4jSupportedProperties; }; /** node type used for creating/merging, using a model to extract the label */ export type NodeForCreateWithModelI = { /** identifier for the node */ identifier?: string; /** the model of this node. Automatically sets the "label" field */ model: NeogmaModel<any, any, any, any>; /** properties of the node */ properties?: Neo4jSupportedProperties; }; export const isNodeWithWhere = ( node: NodeForMatchObjectI | NodeForCreateObjectI, ): node is RequiredProperties<NodeForMatchObjectI, 'where'> => { return !!(node as NodeForMatchObjectI).where; }; export const isNodeWithLabel = ( node: NodeForMatchObjectI | NodeForCreateObjectI, ): node is NodeForCreateWithLabelI => { return !!(node as NodeForMatchObjectI | NodeForCreateWithLabelI).label; }; export const isNodeWithModel = ( node: NodeForMatchObjectI | NodeForCreateObjectI, ): node is NodeForCreateWithModelI => { return !!(node as NodeForMatchObjectI | NodeForCreateWithModelI).model; }; export const isNodeWithProperties = ( node: NodeForMatchObjectI | NodeForCreateObjectI, ): node is RequiredProperties<NodeForCreateObjectI, 'properties'> => { return !!(node as NodeForCreateObjectI).properties; }; /** relationship type used for matching */ export type RelationshipForMatchI = string | RelationshipForMatchObjectI; export type RelationshipForMatchObjectI = { /** direction of this relationship, from top to bottom */ direction: 'in' | 'out' | 'none'; /** name of this relationship */ name?: string; /** identifier for this relationship */ identifier?: string; /** where parameters for matching this relationship */ where?: WhereParamsI; }; /** relationship type used for creating/merging */ export type RelationshipForCreateI = string | RelationshipForCreateObjectI; export type RelationshipForCreateObjectI = { /** direction of this relationship, from top to bottom */ direction: 'in' | 'out' | 'none'; /** name of this relationship */ name: string; /** identifier for this relationship */ identifier?: string; /** properties of the relationship */ properties?: Neo4jSupportedProperties; }; export const isRelationshipWithWhere = ( relationship: RelationshipForMatchObjectI | RelationshipForCreateObjectI, ): relationship is RequiredProperties<RelationshipForMatchObjectI, 'where'> => { return !!(relationship as RelationshipForMatchObjectI).where; }; export const isRelationshipWithProperties = ( relationship: RelationshipForMatchObjectI | RelationshipForCreateObjectI, ): relationship is RequiredProperties< RelationshipForCreateObjectI, 'properties' > => { return !!(relationship as RelationshipForCreateObjectI).properties; }; export const isRelationship = ( _relationship: RelationshipForMatchI | NodeForMatchI, ): _relationship is RelationshipForMatchI => { const relationship = _relationship as RelationshipForMatchI; return typeof relationship === 'string' || !!relationship.direction; };
the_stack
import { View, Text } from 'react-native'; import React from 'react'; import Animated from 'react-native-reanimated'; import LinearGradient from 'react-native-linear-gradient'; import { create } from 'react-test-renderer'; import SkeletonContent from '../SkeletonContent'; import { ISkeletonContentProps, DEFAULT_BONE_COLOR, DEFAULT_HIGHLIGHT_COLOR, DEFAULT_BORDER_RADIUS } from '../Constants'; const staticStyles = { borderRadius: DEFAULT_BORDER_RADIUS, overflow: 'hidden', backgroundColor: DEFAULT_BONE_COLOR }; describe('SkeletonComponent test suite', () => { it('should render empty alone', () => { const tree = create(<SkeletonContent isLoading={false} />).toJSON(); expect(tree).toMatchSnapshot(); }); it('should have the correct layout when loading', () => { const layout = [ { width: 240, height: 100, marginBottom: 10 }, { width: 180, height: 40, borderRadius: 20, backgroundColor: 'grey' } ]; const props: ISkeletonContentProps = { layout, isLoading: true, animationType: 'none' }; const instance = create(<SkeletonContent {...props} />); const component = instance.root; const bones = component.findAllByType(Animated.View); // two bones and parent component expect(bones.length).toEqual(layout.length + 1); expect(bones[0].props.style).toEqual({ alignItems: 'center', flex: 1, justifyContent: 'center' }); // default props that are not set expect(bones[1].props.style).toEqual([{ ...layout[0], ...staticStyles }]); expect(bones[2].props.style).toEqual([ { overflow: 'hidden', ...layout[1] } ]); expect(instance.toJSON()).toMatchSnapshot(); }); it('should render the correct bones for children', () => { const props: ISkeletonContentProps = { isLoading: true, animationType: 'shiver' }; const w1 = { height: 100, width: 200 }; const w2 = { height: 120, width: 20 }; const w3 = { height: 80, width: 240 }; const children = [w1, w2, w3]; const TestComponent = ({ isLoading, animationType }: ISkeletonContentProps) => ( <SkeletonContent isLoading={isLoading} animationType={animationType}> {children.map(c => ( <View key={c.height} style={c} /> ))} </SkeletonContent> ); const instance = create(<TestComponent {...props} />); let component = instance.root; // finding children count let bones = component.findAllByType(LinearGradient); expect(bones.length).toEqual(children.length); // finding styles of wrapper views bones = component.findAllByType(Animated.View); expect(bones[1].props.style).toEqual({ ...staticStyles, ...w1 }); expect(bones[3].props.style).toEqual({ ...staticStyles, ...w2 }); expect(bones[5].props.style).toEqual({ ...staticStyles, ...w3 }); // re-update with pulse animation instance.update(<TestComponent isLoading animationType="pulse" />); component = instance.root; bones = component.findAllByType(Animated.View); // cannot test interpolated background color expect(bones[1].props.style).toEqual([ { ...w1, borderRadius: DEFAULT_BORDER_RADIUS }, { backgroundColor: { ' __value': 4278190080 } } ]); expect(bones[2].props.style).toEqual([ { ...w2, borderRadius: DEFAULT_BORDER_RADIUS }, { backgroundColor: { ' __value': 4278190080 } } ]); expect(bones[3].props.style).toEqual([ { ...w3, borderRadius: DEFAULT_BORDER_RADIUS }, { backgroundColor: { ' __value': 4278190080 } } ]); expect(instance.toJSON()).toMatchSnapshot(); }); it('should have correct props and layout between loading states', () => { const w1 = { width: 240, height: 100, marginBottom: 10 }; const w2 = { width: 180, height: 40 }; const layout = [w1, w2]; const props: ISkeletonContentProps = { layout, isLoading: true, animationType: 'shiver' }; const childStyle = { fontSize: 24 }; const instance = create( <SkeletonContent {...props}> <Text style={childStyle} /> </SkeletonContent> ); const component = instance.root; let bones = component.findAllByType(LinearGradient); // one animated view child for each bone + parent expect(bones.length).toEqual(layout.length); bones = component.findAllByType(Animated.View); expect(bones[1].props.style).toEqual({ ...staticStyles, ...w1 }); expect(bones[3].props.style).toEqual({ ...staticStyles, ...w2 }); let children = component.findAllByType(Text); // no child since it's loading expect(children.length).toEqual(0); // update props instance.update( <SkeletonContent {...props} isLoading={false}> <Text style={childStyle} /> </SkeletonContent> ); bones = instance.root.findAllByType(LinearGradient); expect(bones.length).toEqual(0); children = instance.root.findAllByType(Text); expect(children.length).toEqual(1); expect(children[0].props.style).toEqual(childStyle); // re-update to loading state instance.update( <SkeletonContent {...props}> <Text style={childStyle} /> </SkeletonContent> ); bones = instance.root.findAllByType(LinearGradient); expect(bones.length).toEqual(layout.length); bones = component.findAllByType(Animated.View); expect(bones[1].props.style).toEqual({ ...staticStyles, ...w1 }); expect(bones[3].props.style).toEqual({ ...staticStyles, ...w2 }); children = instance.root.findAllByType(Text); // no child since it's loading expect(children.length).toEqual(0); // snapshot expect(instance.toJSON()).toMatchSnapshot(); }); it('should support nested layouts', () => { const layout: any = [ { flexDirection: 'row', width: 320, height: 300, children: [ { width: 200, height: 120 }, { width: 180, height: 100 } ] }, { width: 180, height: 40, borderRadius: 20, backgroundColor: 'grey' } ]; const props: ISkeletonContentProps = { layout, isLoading: true, animationType: 'shiver' }; const instance = create(<SkeletonContent {...props} />); const component = instance.root; let bones = component.findAllByType(LinearGradient); // three overall bones expect(bones.length).toEqual(3); bones = component.findAllByType(Animated.View); expect(bones[1].props.style).toEqual({ flexDirection: 'row', width: 320, height: 300 }); // testing that styles for nested layout and last child persist expect(bones[2].props.style).toEqual({ ...staticStyles, ...layout[0].children[0] }); expect(bones[4].props.style).toEqual({ ...staticStyles, ...layout[0].children[1] }); expect(bones[6].props.style).toEqual({ ...staticStyles, ...layout[1] }); expect(instance.toJSON()).toMatchSnapshot(); }); it('should support percentage for child size', () => { const parentHeight = 300; const parentWidth = 320; const containerStyle = { width: parentWidth, height: parentHeight }; const layout = [ { width: '20%', height: '50%', borderRadius: 20, backgroundColor: 'grey' }, { width: '50%', height: '10%', borderRadius: 10 } ]; const props: ISkeletonContentProps = { layout, isLoading: true, animationType: 'shiver', containerStyle }; const instance = create(<SkeletonContent {...props} />); const component = instance.root; let bones = component.findAllByType(LinearGradient); expect(bones.length).toEqual(layout.length); // get parent bones = component.findAllByType(Animated.View); // testing that styles of childs corresponds to percentages expect(bones[1].props.style).toEqual({ ...staticStyles, ...layout[0] }); expect(bones[3].props.style).toEqual({ ...staticStyles, ...layout[1] }); expect(instance.toJSON()).toMatchSnapshot(); }); it('should have the correct gradient properties', () => { let customProps: ISkeletonContentProps = { layout: [ { width: 240, height: 100, marginBottom: 10 } ], isLoading: true, animationDirection: 'diagonalDownLeft' }; const TestComponent = (props: ISkeletonContentProps) => ( <SkeletonContent {...props}> <Animated.View style={{ height: 100, width: 200 }} /> </SkeletonContent> ); const component = create(<TestComponent {...customProps} />); let gradient = component.root.findByType(LinearGradient); expect(gradient).toBeDefined(); expect(gradient.props.start).toEqual({ x: 0, y: 0 }); expect(gradient.props.end).toEqual({ x: 0, y: 1 }); // change layout on diagonal component customProps = { ...customProps, layout: [ { width: 240, height: 300 } ] }; component.update( <SkeletonContent {...customProps} animationDirection="diagonalDownLeft"> <Animated.View style={{ height: 300, width: 200 }} /> </SkeletonContent> ); gradient = component.root.findByType(LinearGradient); expect(gradient).toBeDefined(); expect(gradient.props.start).toEqual({ x: 0, y: 0 }); expect(gradient.props.end).toEqual({ x: 1, y: 0 }); component.update( <SkeletonContent {...customProps} animationDirection="verticalTop"> <Text style={{ fontSize: 24 }} /> </SkeletonContent> ); gradient = component.root.findByType(LinearGradient); expect(gradient).toBeDefined(); expect(gradient.props.start).toEqual({ x: 0, y: 0 }); expect(gradient.props.end).toEqual({ x: 0, y: 1 }); component.update( <SkeletonContent {...customProps} animationDirection="verticalDown"> <Text style={{ fontSize: 24 }} /> </SkeletonContent> ); gradient = component.root.findByType(LinearGradient); expect(gradient).toBeDefined(); expect(gradient.props.start).toEqual({ x: 0, y: 0 }); expect(gradient.props.end).toEqual({ x: 0, y: 1 }); component.update( <SkeletonContent {...customProps} animationDirection="horizontalLeft"> <Text style={{ fontSize: 24 }} /> </SkeletonContent> ); gradient = component.root.findByType(LinearGradient); expect(gradient).toBeDefined(); expect(gradient.props.start).toEqual({ x: 0, y: 0 }); expect(gradient.props.end).toEqual({ x: 1, y: 0 }); component.update( <SkeletonContent {...customProps} animationDirection="horizontalRight"> <Text style={{ fontSize: 24 }} /> </SkeletonContent> ); gradient = component.root.findByType(LinearGradient); expect(gradient).toBeDefined(); expect(gradient.props.start).toEqual({ x: 0, y: 0 }); expect(gradient.props.end).toEqual({ x: 1, y: 0 }); expect(gradient.props.colors).toEqual([ DEFAULT_BONE_COLOR, DEFAULT_HIGHLIGHT_COLOR, DEFAULT_BONE_COLOR ]); }); });
the_stack
// IMPORTANT // This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually. // In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator // Generated from: https://partners.googleapis.com/$discovery/rest?version=v2 /// <reference types="gapi.client" /> declare namespace gapi.client { /** Load Google Partners API v2 */ function load(name: "partners", version: "v2"): PromiseLike<void>; function load(name: "partners", version: "v2", callback: () => any): void; const analytics: partners.AnalyticsResource; const clientMessages: partners.ClientMessagesResource; const companies: partners.CompaniesResource; const exams: partners.ExamsResource; const leads: partners.LeadsResource; const offers: partners.OffersResource; const userEvents: partners.UserEventsResource; const userStates: partners.UserStatesResource; const users: partners.UsersResource; const v2: partners.V2Resource; namespace partners { interface AdWordsManagerAccountInfo { /** Name of the customer this account represents. */ customerName?: string; /** The AdWords Manager Account id. */ id?: string; } interface Analytics { /** * Instances of users contacting the `Company` * on the specified date. */ contacts?: AnalyticsDataPoint; /** Date on which these events occurred. */ eventDate?: Date; /** * Instances of users viewing the `Company` profile * on the specified date. */ profileViews?: AnalyticsDataPoint; /** * Instances of users seeing the `Company` in Google Partners Search results * on the specified date. */ searchViews?: AnalyticsDataPoint; } interface AnalyticsDataPoint { /** * Number of times the type of event occurred. * Meaning depends on context (e.g. profile views, contacts, etc.). */ eventCount?: number; /** Location information of where these events occurred. */ eventLocations?: LatLng[]; } interface AnalyticsSummary { /** * Aggregated number of times users contacted the `Company` * for given date range. */ contactsCount?: number; /** Aggregated number of profile views for the `Company` for given date range. */ profileViewsCount?: number; /** * Aggregated number of times users saw the `Company` * in Google Partners Search results for given date range. */ searchViewsCount?: number; } interface AvailableOffer { /** The number of codes for this offer that are available for distribution. */ available?: number; /** Offer info by country. */ countryOfferInfos?: CountryOfferInfo[]; /** Description of the offer. */ description?: string; /** ID of this offer. */ id?: string; /** The maximum age of an account [in days] to be eligible. */ maxAccountAge?: number; /** Name of the offer. */ name?: string; /** Level of this offer. */ offerLevel?: string; /** Type of offer. */ offerType?: string; /** Customers who qualify for this offer. */ qualifiedCustomer?: OfferCustomer[]; /** Whether or not the list of qualified customers is definitely complete. */ qualifiedCustomersComplete?: boolean; /** Should special text be shown on the offers page. */ showSpecialOfferCopy?: boolean; /** Terms of the offer. */ terms?: string; } interface Certification { /** Whether this certification has been achieved. */ achieved?: boolean; /** The type of certification, the area of expertise. */ certificationType?: string; /** Date this certification is due to expire. */ expiration?: string; /** The date the user last achieved certification. */ lastAchieved?: string; /** Whether this certification is in the state of warning. */ warning?: boolean; } interface CertificationExamStatus { /** The number of people who have passed the certification exam. */ numberUsersPass?: number; /** The type of certification exam. */ type?: string; } interface CertificationStatus { /** List of certification exam statuses. */ examStatuses?: CertificationExamStatus[]; /** Whether certification is passing. */ isCertified?: boolean; /** The type of the certification. */ type?: string; /** Number of people who are certified, */ userCount?: number; } interface Company { /** * URL of the company's additional websites used to verify the dynamic badges. * These are stored as full URLs as entered by the user, but only the TLD will * be used for the actual verification. */ additionalWebsites?: string[]; /** * Email domains that allow users with a matching email address to get * auto-approved for associating with this company. */ autoApprovalEmailDomains?: string[]; /** Partner badge tier */ badgeTier?: string; /** The list of Google Partners certification statuses for the company. */ certificationStatuses?: CertificationStatus[]; /** Company type labels listed on the company's profile. */ companyTypes?: string[]; /** * The minimum monthly budget that the company accepts for partner business, * converted to the requested currency code. */ convertedMinMonthlyBudget?: Money; /** The ID of the company. */ id?: string; /** Industries the company can help with. */ industries?: string[]; /** The list of localized info for the company. */ localizedInfos?: LocalizedCompanyInfo[]; /** * The list of all company locations. * If set, must include the * primary_location * in the list. */ locations?: Location[]; /** The name of the company. */ name?: string; /** * The unconverted minimum monthly budget that the company accepts for partner * business. */ originalMinMonthlyBudget?: Money; /** The Primary AdWords Manager Account id. */ primaryAdwordsManagerAccountId?: string; /** * The primary language code of the company, as defined by * <a href="https://tools.ietf.org/html/bcp47">BCP 47</a> * (IETF BCP 47, "Tags for Identifying Languages"). */ primaryLanguageCode?: string; /** The primary location of the company. */ primaryLocation?: Location; /** The public viewability status of the company's profile. */ profileStatus?: string; /** Basic information from the company's public profile. */ publicProfile?: PublicProfile; /** * Information related to the ranking of the company within the list of * companies. */ ranks?: Rank[]; /** Services the company can help with. */ services?: string[]; /** The list of Google Partners specialization statuses for the company. */ specializationStatus?: SpecializationStatus[]; /** URL of the company's website. */ websiteUrl?: string; } interface CompanyRelation { /** The primary address for this company. */ address?: string; /** Whether the company is a Partner. */ badgeTier?: string; /** Indicates if the user is an admin for this company. */ companyAdmin?: boolean; /** * The ID of the company. There may be no id if this is a * pending company.5 */ companyId?: string; /** * The timestamp of when affiliation was requested. * @OutputOnly */ creationTime?: string; /** * The internal company ID. * Only available for a whitelisted set of api clients. */ internalCompanyId?: string; /** The flag that indicates if the company is pending verification. */ isPending?: boolean; /** A URL to a profile photo, e.g. a G+ profile photo. */ logoUrl?: string; /** The AdWords manager account # associated this company. */ managerAccount?: string; /** The name (in the company's primary language) for the company. */ name?: string; /** The phone number for the company's primary address. */ phoneNumber?: string; /** The primary location of the company. */ primaryAddress?: Location; /** The primary country code of the company. */ primaryCountryCode?: string; /** The primary language code of the company. */ primaryLanguageCode?: string; /** * The timestamp when the user was approved. * @OutputOnly */ resolvedTimestamp?: string; /** The segment the company is classified as. */ segment?: string[]; /** The list of Google Partners specialization statuses for the company. */ specializationStatus?: SpecializationStatus[]; /** The state of relationship, in terms of approvals. */ state?: string; /** The website URL for this company. */ website?: string; } interface CountryOfferInfo { /** (localized) Get Y amount for that country's offer. */ getYAmount?: string; /** Country code for which offer codes may be requested. */ offerCountryCode?: string; /** Type of offer country is eligible for. */ offerType?: string; /** (localized) Spend X amount for that country's offer. */ spendXAmount?: string; } interface CreateLeadRequest { /** * The lead resource. The `LeadType` must not be `LEAD_TYPE_UNSPECIFIED` * and either `email` or `phone_number` must be provided. */ lead?: Lead; /** <a href="https://www.google.com/recaptcha/">reCaptcha</a> challenge info. */ recaptchaChallenge?: RecaptchaChallenge; /** Current request metadata. */ requestMetadata?: RequestMetadata; } interface CreateLeadResponse { /** * Lead that was created depending on the outcome of * <a href="https://www.google.com/recaptcha/">reCaptcha</a> validation. */ lead?: Lead; /** * The outcome of <a href="https://www.google.com/recaptcha/">reCaptcha</a> * validation. */ recaptchaStatus?: string; /** Current response metadata. */ responseMetadata?: ResponseMetadata; } interface Date { /** * Day of month. Must be from 1 to 31 and valid for the year and month, or 0 * if specifying a year/month where the day is not significant. */ day?: number; /** Month of year. Must be from 1 to 12. */ month?: number; /** * Year of date. Must be from 1 to 9999, or 0 if specifying a date without * a year. */ year?: number; } interface DebugInfo { /** Info about the server that serviced this request. */ serverInfo?: string; /** Server-side debug stack trace. */ serverTraceInfo?: string; /** URL of the service that handled this request. */ serviceUrl?: string; } interface EventData { /** Data type. */ key?: string; /** Data values. */ values?: string[]; } interface ExamStatus { /** The type of the exam. */ examType?: string; /** Date this exam is due to expire. */ expiration?: string; /** The date the user last passed this exam. */ lastPassed?: string; /** Whether this exam has been passed and not expired. */ passed?: boolean; /** The date the user last taken this exam. */ taken?: string; /** Whether this exam is in the state of warning. */ warning?: boolean; } interface ExamToken { /** The id of the exam the token is for. */ examId?: string; /** The type of the exam the token belongs to. */ examType?: string; /** The token, only present if the user has access to the exam. */ token?: string; } interface GetCompanyResponse { /** The company. */ company?: Company; /** Current response metadata. */ responseMetadata?: ResponseMetadata; } interface GetPartnersStatusResponse { /** Current response metadata. */ responseMetadata?: ResponseMetadata; } interface HistoricalOffer { /** Client's AdWords page URL. */ adwordsUrl?: string; /** Email address for client. */ clientEmail?: string; /** ID of client. */ clientId?: string; /** Name of the client. */ clientName?: string; /** Time offer was first created. */ creationTime?: string; /** Time this offer expires. */ expirationTime?: string; /** Time last action was taken. */ lastModifiedTime?: string; /** Offer code. */ offerCode?: string; /** Country Code for the offer country. */ offerCountryCode?: string; /** Type of offer. */ offerType?: string; /** Name (First + Last) of the partners user to whom the incentive is allocated. */ senderName?: string; /** Status of the offer. */ status?: string; } interface LatLng { /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */ latitude?: number; /** The longitude in degrees. It must be in the range [-180.0, +180.0]. */ longitude?: number; } interface Lead { /** The AdWords Customer ID of the lead. */ adwordsCustomerId?: string; /** Comments lead source gave. */ comments?: string; /** Timestamp of when this lead was created. */ createTime?: string; /** Email address of lead source. */ email?: string; /** Last name of lead source. */ familyName?: string; /** First name of lead source. */ givenName?: string; /** List of reasons for using Google Partner Search and creating a lead. */ gpsMotivations?: string[]; /** ID of the lead. */ id?: string; /** * Language code of the lead's language preference, as defined by * <a href="https://tools.ietf.org/html/bcp47">BCP 47</a> * (IETF BCP 47, "Tags for Identifying Languages"). */ languageCode?: string; /** Whether or not the lead signed up for marketing emails */ marketingOptIn?: boolean; /** The minimum monthly budget lead source is willing to spend. */ minMonthlyBudget?: Money; /** Phone number of lead source. */ phoneNumber?: string; /** The lead's state in relation to the company. */ state?: string; /** Type of lead. */ type?: string; /** Website URL of lead source. */ websiteUrl?: string; } interface ListAnalyticsResponse { /** * The list of analytics. * Sorted in ascending order of * Analytics.event_date. */ analytics?: Analytics[]; /** * Aggregated information across the response's * analytics. */ analyticsSummary?: AnalyticsSummary; /** * A token to retrieve next page of results. * Pass this value in the `ListAnalyticsRequest.page_token` field in the * subsequent call to * ListAnalytics to retrieve the * next page of results. */ nextPageToken?: string; /** Current response metadata. */ responseMetadata?: ResponseMetadata; } interface ListCompaniesResponse { /** The list of companies. */ companies?: Company[]; /** * A token to retrieve next page of results. * Pass this value in the `ListCompaniesRequest.page_token` field in the * subsequent call to * ListCompanies to retrieve the * next page of results. */ nextPageToken?: string; /** Current response metadata. */ responseMetadata?: ResponseMetadata; } interface ListLeadsResponse { /** The list of leads. */ leads?: Lead[]; /** * A token to retrieve next page of results. * Pass this value in the `ListLeadsRequest.page_token` field in the * subsequent call to * ListLeads to retrieve the * next page of results. */ nextPageToken?: string; /** Current response metadata. */ responseMetadata?: ResponseMetadata; /** The total count of leads for the given company. */ totalSize?: number; } interface ListOffersHistoryResponse { /** True if the user has the option to show entire company history. */ canShowEntireCompany?: boolean; /** Supply this token in a ListOffersHistoryRequest to retrieve the next page. */ nextPageToken?: string; /** Historical offers meeting request. */ offers?: HistoricalOffer[]; /** Current response metadata. */ responseMetadata?: ResponseMetadata; /** True if this response is showing entire company history. */ showingEntireCompany?: boolean; /** Number of results across all pages. */ totalResults?: number; } interface ListOffersResponse { /** Available Offers to be distributed. */ availableOffers?: AvailableOffer[]; /** Reason why no Offers are available. */ noOfferReason?: string; /** Current response metadata. */ responseMetadata?: ResponseMetadata; } interface ListUserStatesResponse { /** Current response metadata. */ responseMetadata?: ResponseMetadata; /** User's states. */ userStates?: string[]; } interface LocalizedCompanyInfo { /** List of country codes for the localized company info. */ countryCodes?: string[]; /** Localized display name. */ displayName?: string; /** * Language code of the localized company info, as defined by * <a href="https://tools.ietf.org/html/bcp47">BCP 47</a> * (IETF BCP 47, "Tags for Identifying Languages"). */ languageCode?: string; /** Localized brief description that the company uses to advertise themselves. */ overview?: string; } interface Location { /** The single string version of the address. */ address?: string; /** * The following address lines represent the most specific part of any * address. */ addressLine?: string[]; /** Top-level administrative subdivision of this country. */ administrativeArea?: string; /** * Dependent locality or sublocality. Used for UK dependent localities, or * neighborhoods or boroughs in other locations. */ dependentLocality?: string; /** Language code of the address. Should be in BCP 47 format. */ languageCode?: string; /** The latitude and longitude of the location, in degrees. */ latLng?: LatLng; /** Generally refers to the city/town portion of an address. */ locality?: string; /** Values are frequently alphanumeric. */ postalCode?: string; /** CLDR (Common Locale Data Repository) region code . */ regionCode?: string; /** * Use of this code is very country-specific, but will refer to a secondary * classification code for sorting mail. */ sortingCode?: string; } interface LogMessageRequest { /** Map of client info, such as URL, browser navigator, browser platform, etc. */ clientInfo?: Record<string, string>; /** Details about the client message. */ details?: string; /** Message level of client message. */ level?: string; /** Current request metadata. */ requestMetadata?: RequestMetadata; } interface LogMessageResponse { /** Current response metadata. */ responseMetadata?: ResponseMetadata; } interface LogUserEventRequest { /** The action that occurred. */ eventAction?: string; /** The category the action belongs to. */ eventCategory?: string; /** List of event data for the event. */ eventDatas?: EventData[]; /** The scope of the event. */ eventScope?: string; /** Advertiser lead information. */ lead?: Lead; /** Current request metadata. */ requestMetadata?: RequestMetadata; /** The URL where the event occurred. */ url?: string; } interface LogUserEventResponse { /** Current response metadata. */ responseMetadata?: ResponseMetadata; } interface Money { /** The 3-letter currency code defined in ISO 4217. */ currencyCode?: string; /** * Number of nano (10^-9) units of the amount. * The value must be between -999,999,999 and +999,999,999 inclusive. * If `units` is positive, `nanos` must be positive or zero. * If `units` is zero, `nanos` can be positive, zero, or negative. * If `units` is negative, `nanos` must be negative or zero. * For example $-1.75 is represented as `units`=-1 and `nanos`=-750,000,000. */ nanos?: number; /** * The whole units of the amount. * For example if `currencyCode` is `"USD"`, then 1 unit is one US dollar. */ units?: string; } interface OfferCustomer { /** URL to the customer's AdWords page. */ adwordsUrl?: string; /** Country code of the customer. */ countryCode?: string; /** Time the customer was created. */ creationTime?: string; /** Days the customer is still eligible. */ eligibilityDaysLeft?: number; /** External CID for the customer. */ externalCid?: string; /** Formatted Get Y amount with currency code. */ getYAmount?: string; /** Name of the customer. */ name?: string; /** Type of the offer */ offerType?: string; /** Formatted Spend X amount with currency code. */ spendXAmount?: string; } interface OptIns { /** * An opt-in about receiving email from Partners marketing teams. Includes * member-only events and special promotional offers for Google products. */ marketComm?: boolean; /** * An opt-in about receiving email with customized AdWords campaign management * tips. */ performanceSuggestions?: boolean; /** An opt-in to allow recieivng phone calls about their Partners account. */ phoneContact?: boolean; /** An opt-in to receive special promotional gifts and material in the mail. */ physicalMail?: boolean; /** An opt-in about receiving email regarding new features and products. */ specialOffers?: boolean; } interface PublicProfile { /** The URL to the main display image of the public profile. Being deprecated. */ displayImageUrl?: string; /** The display name of the public profile. */ displayName?: string; /** The ID which can be used to retrieve more details about the public profile. */ id?: string; /** The URL to the main profile image of the public profile. */ profileImage?: string; /** The URL of the public profile. */ url?: string; } interface Rank { /** The type of rank. */ type?: string; /** The numerical value of the rank. */ value?: number; } interface RecaptchaChallenge { /** The ID of the reCaptcha challenge. */ id?: string; /** The response to the reCaptcha challenge. */ response?: string; } interface RequestMetadata { /** Experiment IDs the current request belongs to. */ experimentIds?: string[]; /** Locale to use for the current request. */ locale?: string; /** Google Partners session ID. */ partnersSessionId?: string; /** Source of traffic for the current request. */ trafficSource?: TrafficSource; /** * Values to use instead of the user's respective defaults for the current * request. These are only honored by whitelisted products. */ userOverrides?: UserOverrides; } interface ResponseMetadata { /** Debug information about this request. */ debugInfo?: DebugInfo; } interface SpecializationStatus { /** The specialization this status is for. */ badgeSpecialization?: string; /** State of agency specialization. */ badgeSpecializationState?: string; } interface TrafficSource { /** * Identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ trafficSourceId?: string; /** * Second level identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ trafficSubId?: string; } interface User { /** * This is the list of AdWords Manager Accounts the user has edit access to. * If the user has edit access to multiple accounts, the user can choose the * preferred account and we use this when a personal account is needed. Can * be empty meaning the user has access to no accounts. * @OutputOnly */ availableAdwordsManagerAccounts?: AdWordsManagerAccountInfo[]; /** * The list of achieved certifications. These are calculated based on exam * results and other requirements. * @OutputOnly */ certificationStatus?: Certification[]; /** * The company that the user is associated with. * If not present, the user is not associated with any company. */ company?: CompanyRelation; /** * The email address used by the user used for company verification. * @OutputOnly */ companyVerificationEmail?: string; /** * The list of exams the user ever taken. For each type of exam, only one * entry is listed. */ examStatus?: ExamStatus[]; /** The ID of the user. */ id?: string; /** * The internal user ID. * Only available for a whitelisted set of api clients. */ internalId?: string; /** * The most recent time the user interacted with the Partners site. * @OutputOnly */ lastAccessTime?: string; /** * The list of emails the user has access to/can select as primary. * @OutputOnly */ primaryEmails?: string[]; /** * The profile information of a Partners user, contains all the directly * editable user information. */ profile?: UserProfile; /** Information about a user's external public profile outside Google Partners. */ publicProfile?: PublicProfile; } interface UserOverrides { /** IP address to use instead of the user's geo-located IP address. */ ipAddress?: string; /** Logged-in user ID to impersonate instead of the user's ID. */ userId?: string; } interface UserProfile { /** The user's mailing address, contains multiple fields. */ address?: Location; /** * If the user has edit access to multiple accounts, the user can choose the * preferred account and it is used when a personal account is needed. Can * be empty. */ adwordsManagerAccount?: string; /** A list of ids representing which channels the user selected they were in. */ channels?: string[]; /** The email address the user has selected on the Partners site as primary. */ emailAddress?: string; /** The list of opt-ins for the user, related to communication preferences. */ emailOptIns?: OptIns; /** The user's family name. */ familyName?: string; /** The user's given name. */ givenName?: string; /** A list of ids representing which industries the user selected. */ industries?: string[]; /** A list of ids represnting which job categories the user selected. */ jobFunctions?: string[]; /** The list of languages this user understands. */ languages?: string[]; /** A list of ids representing which markets the user was interested in. */ markets?: string[]; /** The user's phone number. */ phoneNumber?: string; /** The user's primary country, an ISO 2-character code. */ primaryCountryCode?: string; /** Whether the user's public profile is visible to anyone with the URL. */ profilePublic?: boolean; } interface AnalyticsResource { /** * Lists analytics data for a user's associated company. * Should only be called within the context of an authorized logged in user. */ list(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Requested page size. Server may return fewer analytics than requested. * If unspecified or set to 0, default value is 30. * Specifies the number of days in the date range when querying analytics. * The `page_token` represents the end date of the date range * and the start date is calculated using the `page_size` as the number * of days BEFORE the end date. * Must be a non-negative integer. */ pageSize?: number; /** * A token identifying a page of results that the server returns. * Typically, this is the value of `ListAnalyticsResponse.next_page_token` * returned from the previous call to * ListAnalytics. * Will be a date string in `YYYY-MM-DD` format representing the end date * of the date range of results to return. * If unspecified or set to "", default value is the current date. */ pageToken?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Experiment IDs the current request belongs to. */ "requestMetadata.experimentIds"?: string; /** Locale to use for the current request. */ "requestMetadata.locale"?: string; /** Google Partners session ID. */ "requestMetadata.partnersSessionId"?: string; /** * Identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSourceId"?: string; /** * Second level identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSubId"?: string; /** IP address to use instead of the user's geo-located IP address. */ "requestMetadata.userOverrides.ipAddress"?: string; /** Logged-in user ID to impersonate instead of the user's ID. */ "requestMetadata.userOverrides.userId"?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<ListAnalyticsResponse>; } interface ClientMessagesResource { /** * Logs a generic message from the client, such as * `Failed to render component`, `Profile page is running slow`, * `More than 500 users have accessed this result.`, etc. */ log(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<LogMessageResponse>; } interface LeadsResource { /** Creates an advertiser lead for the given company ID. */ create(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** The ID of the company to contact. */ companyId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<CreateLeadResponse>; } interface CompaniesResource { /** Gets a company. */ get(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** * The address to use for sorting the company's addresses by proximity. * If not given, the geo-located address of the request is used. * Used when order_by is set. */ address?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** The ID of the company to retrieve. */ companyId: string; /** * If the company's budget is in a different currency code than this one, then * the converted budget is converted to this currency code. */ currencyCode?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * How to order addresses within the returned company. Currently, only * `address` and `address desc` is supported which will sorted by closest to * farthest in distance from given address and farthest to closest distance * from given address respectively. */ orderBy?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Experiment IDs the current request belongs to. */ "requestMetadata.experimentIds"?: string; /** Locale to use for the current request. */ "requestMetadata.locale"?: string; /** Google Partners session ID. */ "requestMetadata.partnersSessionId"?: string; /** * Identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSourceId"?: string; /** * Second level identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSubId"?: string; /** IP address to use instead of the user's geo-located IP address. */ "requestMetadata.userOverrides.ipAddress"?: string; /** Logged-in user ID to impersonate instead of the user's ID. */ "requestMetadata.userOverrides.userId"?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; /** * The view of `Company` resource to be returned. This must not be * `COMPANY_VIEW_UNSPECIFIED`. */ view?: string; }): Request<GetCompanyResponse>; /** Lists companies. */ list(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** * The address to use when searching for companies. * If not given, the geo-located address of the request is used. */ address?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Company name to search for. */ companyName?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** List of reasons for using Google Partner Search to get companies. */ gpsMotivations?: string; /** List of industries the company can help with. */ industries?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * List of language codes that company can support. Only primary language * subtags are accepted as defined by * <a href="https://tools.ietf.org/html/bcp47">BCP 47</a> * (IETF BCP 47, "Tags for Identifying Languages"). */ languageCodes?: string; /** The 3-letter currency code defined in ISO 4217. */ "maxMonthlyBudget.currencyCode"?: string; /** * Number of nano (10^-9) units of the amount. * The value must be between -999,999,999 and +999,999,999 inclusive. * If `units` is positive, `nanos` must be positive or zero. * If `units` is zero, `nanos` can be positive, zero, or negative. * If `units` is negative, `nanos` must be negative or zero. * For example $-1.75 is represented as `units`=-1 and `nanos`=-750,000,000. */ "maxMonthlyBudget.nanos"?: number; /** * The whole units of the amount. * For example if `currencyCode` is `"USD"`, then 1 unit is one US dollar. */ "maxMonthlyBudget.units"?: string; /** The 3-letter currency code defined in ISO 4217. */ "minMonthlyBudget.currencyCode"?: string; /** * Number of nano (10^-9) units of the amount. * The value must be between -999,999,999 and +999,999,999 inclusive. * If `units` is positive, `nanos` must be positive or zero. * If `units` is zero, `nanos` can be positive, zero, or negative. * If `units` is negative, `nanos` must be negative or zero. * For example $-1.75 is represented as `units`=-1 and `nanos`=-750,000,000. */ "minMonthlyBudget.nanos"?: number; /** * The whole units of the amount. * For example if `currencyCode` is `"USD"`, then 1 unit is one US dollar. */ "minMonthlyBudget.units"?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * How to order addresses within the returned companies. Currently, only * `address` and `address desc` is supported which will sorted by closest to * farthest in distance from given address and farthest to closest distance * from given address respectively. */ orderBy?: string; /** * Requested page size. Server may return fewer companies than requested. * If unspecified, server picks an appropriate default. */ pageSize?: number; /** * A token identifying a page of results that the server returns. * Typically, this is the value of `ListCompaniesResponse.next_page_token` * returned from the previous call to * ListCompanies. */ pageToken?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Experiment IDs the current request belongs to. */ "requestMetadata.experimentIds"?: string; /** Locale to use for the current request. */ "requestMetadata.locale"?: string; /** Google Partners session ID. */ "requestMetadata.partnersSessionId"?: string; /** * Identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSourceId"?: string; /** * Second level identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSubId"?: string; /** IP address to use instead of the user's geo-located IP address. */ "requestMetadata.userOverrides.ipAddress"?: string; /** Logged-in user ID to impersonate instead of the user's ID. */ "requestMetadata.userOverrides.userId"?: string; /** * List of services that the returned agencies should provide. If this is * not empty, any returned agency must have at least one of these services, * or one of the specializations in the "specializations" field. */ services?: string; /** * List of specializations that the returned agencies should provide. If this * is not empty, any returned agency must have at least one of these * specializations, or one of the services in the "services" field. */ specializations?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; /** * The view of the `Company` resource to be returned. This must not be * `COMPANY_VIEW_UNSPECIFIED`. */ view?: string; /** * Website URL that will help to find a better matched company. * . */ websiteUrl?: string; }): Request<ListCompaniesResponse>; leads: LeadsResource; } interface ExamsResource { /** Gets an Exam Token for a Partner's user to take an exam in the Exams System */ getToken(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** The exam type we are requesting a token for. */ examType: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Experiment IDs the current request belongs to. */ "requestMetadata.experimentIds"?: string; /** Locale to use for the current request. */ "requestMetadata.locale"?: string; /** Google Partners session ID. */ "requestMetadata.partnersSessionId"?: string; /** * Identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSourceId"?: string; /** * Second level identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSubId"?: string; /** IP address to use instead of the user's geo-located IP address. */ "requestMetadata.userOverrides.ipAddress"?: string; /** Logged-in user ID to impersonate instead of the user's ID. */ "requestMetadata.userOverrides.userId"?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<ExamToken>; } interface LeadsResource { /** * Lists advertiser leads for a user's associated company. * Should only be called within the context of an authorized logged in user. */ list(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * How to order Leads. Currently, only `create_time` * and `create_time desc` are supported */ orderBy?: string; /** * Requested page size. Server may return fewer leads than requested. * If unspecified, server picks an appropriate default. */ pageSize?: number; /** * A token identifying a page of results that the server returns. * Typically, this is the value of `ListLeadsResponse.next_page_token` * returned from the previous call to * ListLeads. */ pageToken?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Experiment IDs the current request belongs to. */ "requestMetadata.experimentIds"?: string; /** Locale to use for the current request. */ "requestMetadata.locale"?: string; /** Google Partners session ID. */ "requestMetadata.partnersSessionId"?: string; /** * Identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSourceId"?: string; /** * Second level identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSubId"?: string; /** IP address to use instead of the user's geo-located IP address. */ "requestMetadata.userOverrides.ipAddress"?: string; /** Logged-in user ID to impersonate instead of the user's ID. */ "requestMetadata.userOverrides.userId"?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<ListLeadsResponse>; } interface HistoryResource { /** Lists the Historical Offers for the current user (or user's entire company) */ list(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** if true, show history for the entire company. Requires user to be admin. */ entireCompany?: boolean; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Comma-separated list of fields to order by, e.g.: "foo,bar,baz". * Use "foo desc" to sort descending. * List of valid field names is: name, offer_code, expiration_time, status, * last_modified_time, sender_name, creation_time, country_code, * offer_type. */ orderBy?: string; /** Maximum number of rows to return per page. */ pageSize?: number; /** Token to retrieve a specific page. */ pageToken?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Experiment IDs the current request belongs to. */ "requestMetadata.experimentIds"?: string; /** Locale to use for the current request. */ "requestMetadata.locale"?: string; /** Google Partners session ID. */ "requestMetadata.partnersSessionId"?: string; /** * Identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSourceId"?: string; /** * Second level identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSubId"?: string; /** IP address to use instead of the user's geo-located IP address. */ "requestMetadata.userOverrides.ipAddress"?: string; /** Logged-in user ID to impersonate instead of the user's ID. */ "requestMetadata.userOverrides.userId"?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<ListOffersHistoryResponse>; } interface OffersResource { /** Lists the Offers available for the current user */ list(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Experiment IDs the current request belongs to. */ "requestMetadata.experimentIds"?: string; /** Locale to use for the current request. */ "requestMetadata.locale"?: string; /** Google Partners session ID. */ "requestMetadata.partnersSessionId"?: string; /** * Identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSourceId"?: string; /** * Second level identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSubId"?: string; /** IP address to use instead of the user's geo-located IP address. */ "requestMetadata.userOverrides.ipAddress"?: string; /** Logged-in user ID to impersonate instead of the user's ID. */ "requestMetadata.userOverrides.userId"?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<ListOffersResponse>; history: HistoryResource; } interface UserEventsResource { /** Logs a user event. */ log(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<LogUserEventResponse>; } interface UserStatesResource { /** Lists states for current user. */ list(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Experiment IDs the current request belongs to. */ "requestMetadata.experimentIds"?: string; /** Locale to use for the current request. */ "requestMetadata.locale"?: string; /** Google Partners session ID. */ "requestMetadata.partnersSessionId"?: string; /** * Identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSourceId"?: string; /** * Second level identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSubId"?: string; /** IP address to use instead of the user's geo-located IP address. */ "requestMetadata.userOverrides.ipAddress"?: string; /** Logged-in user ID to impersonate instead of the user's ID. */ "requestMetadata.userOverrides.userId"?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<ListUserStatesResponse>; } interface UsersResource { /** Creates a user's company relation. Affiliates the user to a company. */ createCompanyRelation(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Experiment IDs the current request belongs to. */ "requestMetadata.experimentIds"?: string; /** Locale to use for the current request. */ "requestMetadata.locale"?: string; /** Google Partners session ID. */ "requestMetadata.partnersSessionId"?: string; /** * Identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSourceId"?: string; /** * Second level identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSubId"?: string; /** IP address to use instead of the user's geo-located IP address. */ "requestMetadata.userOverrides.ipAddress"?: string; /** Logged-in user ID to impersonate instead of the user's ID. */ "requestMetadata.userOverrides.userId"?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; /** * The ID of the user. Can be set to <code>me</code> to mean * the currently authenticated user. */ userId: string; }): Request<CompanyRelation>; /** Deletes a user's company relation. Unaffiliaites the user from a company. */ deleteCompanyRelation(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Experiment IDs the current request belongs to. */ "requestMetadata.experimentIds"?: string; /** Locale to use for the current request. */ "requestMetadata.locale"?: string; /** Google Partners session ID. */ "requestMetadata.partnersSessionId"?: string; /** * Identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSourceId"?: string; /** * Second level identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSubId"?: string; /** IP address to use instead of the user's geo-located IP address. */ "requestMetadata.userOverrides.ipAddress"?: string; /** Logged-in user ID to impersonate instead of the user's ID. */ "requestMetadata.userOverrides.userId"?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; /** * The ID of the user. Can be set to <code>me</code> to mean * the currently authenticated user. */ userId: string; }): Request<{}>; /** Gets a user. */ get(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Experiment IDs the current request belongs to. */ "requestMetadata.experimentIds"?: string; /** Locale to use for the current request. */ "requestMetadata.locale"?: string; /** Google Partners session ID. */ "requestMetadata.partnersSessionId"?: string; /** * Identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSourceId"?: string; /** * Second level identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSubId"?: string; /** IP address to use instead of the user's geo-located IP address. */ "requestMetadata.userOverrides.ipAddress"?: string; /** Logged-in user ID to impersonate instead of the user's ID. */ "requestMetadata.userOverrides.userId"?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; /** * Identifier of the user. Can be set to <code>me</code> to mean the currently * authenticated user. */ userId: string; /** Specifies what parts of the user information to return. */ userView?: string; }): Request<User>; /** * Updates a user's profile. A user can only update their own profile and * should only be called within the context of a logged in user. */ updateProfile(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Experiment IDs the current request belongs to. */ "requestMetadata.experimentIds"?: string; /** Locale to use for the current request. */ "requestMetadata.locale"?: string; /** Google Partners session ID. */ "requestMetadata.partnersSessionId"?: string; /** * Identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSourceId"?: string; /** * Second level identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSubId"?: string; /** IP address to use instead of the user's geo-located IP address. */ "requestMetadata.userOverrides.ipAddress"?: string; /** Logged-in user ID to impersonate instead of the user's ID. */ "requestMetadata.userOverrides.userId"?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<UserProfile>; } interface V2Resource { /** * Gets Partners Status of the logged in user's agency. * Should only be called if the logged in user is the admin of the agency. */ getPartnersstatus(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Experiment IDs the current request belongs to. */ "requestMetadata.experimentIds"?: string; /** Locale to use for the current request. */ "requestMetadata.locale"?: string; /** Google Partners session ID. */ "requestMetadata.partnersSessionId"?: string; /** * Identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSourceId"?: string; /** * Second level identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSubId"?: string; /** IP address to use instead of the user's geo-located IP address. */ "requestMetadata.userOverrides.ipAddress"?: string; /** Logged-in user ID to impersonate instead of the user's ID. */ "requestMetadata.userOverrides.userId"?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GetPartnersStatusResponse>; /** * Update company. * Should only be called within the context of an authorized logged in user. */ updateCompanies(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Experiment IDs the current request belongs to. */ "requestMetadata.experimentIds"?: string; /** Locale to use for the current request. */ "requestMetadata.locale"?: string; /** Google Partners session ID. */ "requestMetadata.partnersSessionId"?: string; /** * Identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSourceId"?: string; /** * Second level identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSubId"?: string; /** IP address to use instead of the user's geo-located IP address. */ "requestMetadata.userOverrides.ipAddress"?: string; /** Logged-in user ID to impersonate instead of the user's ID. */ "requestMetadata.userOverrides.userId"?: string; /** * Standard field mask for the set of fields to be updated. * Required with at least 1 value in FieldMask's paths. */ updateMask?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<Company>; /** Updates the specified lead. */ updateLeads(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Experiment IDs the current request belongs to. */ "requestMetadata.experimentIds"?: string; /** Locale to use for the current request. */ "requestMetadata.locale"?: string; /** Google Partners session ID. */ "requestMetadata.partnersSessionId"?: string; /** * Identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSourceId"?: string; /** * Second level identifier to indicate where the traffic comes from. * An identifier has multiple letters created by a team which redirected the * traffic to us. */ "requestMetadata.trafficSource.trafficSubId"?: string; /** IP address to use instead of the user's geo-located IP address. */ "requestMetadata.userOverrides.ipAddress"?: string; /** Logged-in user ID to impersonate instead of the user's ID. */ "requestMetadata.userOverrides.userId"?: string; /** * Standard field mask for the set of fields to be updated. * Required with at least 1 value in FieldMask's paths. * Only `state` and `adwords_customer_id` are currently supported. */ updateMask?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<Lead>; } } }
the_stack
import { Carousel, DynamicEntities, DynamicEntitiesMode, DynamicEntity, DynamicEntityMap, mergeInstances, MessageMaxLength, MessageValue, NormalizedOutputTemplate, OutputTemplate, OutputTemplateConverterStrategyConfig, QuickReplyValue, removeSSML, SingleResponseOutputTemplateConverterStrategy, SpeechMessage, TextMessage, toSSML, } from '@jovotech/output'; import { GoogleAssistantResponse } from '../GoogleAssistantResponse'; import { COLLECTION_MAX_SIZE, COLLECTION_MIN_SIZE, SUGGESTION_TITLE_MAX_LENGTH, SUGGESTIONS_MAX_SIZE, TEXT_MAX_LENGTH, } from './constants'; import { Entry, Session, Suggestion, TypeOverride, TypeOverrideMode, TypeOverrideModeLike, } from './models'; import { convertMessageToGoogleAssistantSimple } from './utilities'; export class GoogleAssistantOutputTemplateConverterStrategy extends SingleResponseOutputTemplateConverterStrategy< GoogleAssistantResponse, OutputTemplateConverterStrategyConfig > { platformName = 'googleAssistant' as const; responseClass = GoogleAssistantResponse; // make sure the (content of) message and reprompt always is an object for Google Assistant normalizeOutput(output: OutputTemplate | OutputTemplate[]): NormalizedOutputTemplate { const makeMessageObj = (message: string): TextMessage | SpeechMessage => { return { text: removeSSML(message), speech: toSSML(message), }; }; const updateMessage = (outputTemplate: OutputTemplate, key: 'message' | 'reprompt') => { const value = outputTemplate[key]; if (value && typeof value === 'string') { outputTemplate[key] = makeMessageObj(value); } else if (Array.isArray(value)) { outputTemplate[key] = value.map((message) => typeof message === 'string' ? makeMessageObj(message) : message, ); } }; if (Array.isArray(output)) { output.forEach((outputTemplate) => { updateMessage(outputTemplate, 'message'); updateMessage(outputTemplate, 'reprompt'); }); } else { updateMessage(output, 'message'); updateMessage(output, 'reprompt'); } return super.normalizeOutput(output); } protected sanitizeOutput(output: NormalizedOutputTemplate): NormalizedOutputTemplate { if (output.message) { output.message = this.sanitizeMessage(output.message, 'message'); } if (output.reprompt) { output.reprompt = this.sanitizeMessage(output.reprompt, 'reprompt'); } if (output.quickReplies) { output.quickReplies = this.sanitizeQuickReplies(output.quickReplies, 'quickReplies'); } if (output.carousel) { output.carousel = this.sanitizeCarousel(output.carousel, 'carousel'); } return output; } protected sanitizeMessage( message: MessageValue, path: string, maxLength: MessageMaxLength = { text: TEXT_MAX_LENGTH, }, offset?: number, ): MessageValue { return super.sanitizeMessage(message, path, maxLength, offset); } protected sanitizeQuickReplies( quickReplies: QuickReplyValue[], path: string, maxSize = SUGGESTIONS_MAX_SIZE, maxLength = SUGGESTION_TITLE_MAX_LENGTH, ): QuickReplyValue[] { return super.sanitizeQuickReplies(quickReplies, path, maxSize, maxLength); } protected sanitizeCarousel( carousel: Carousel, path: string, minSize = COLLECTION_MIN_SIZE, maxSize = COLLECTION_MAX_SIZE, ): Carousel { return super.sanitizeCarousel(carousel, path, minSize, maxSize); } toResponse(output: NormalizedOutputTemplate): GoogleAssistantResponse { const response: GoogleAssistantResponse = this.normalizeResponse({}); function getEmptySession(): Session { return { id: '', params: {}, languageCode: '' }; } const listen = output.listen; if (listen === false) { response.scene = { name: '', slots: {}, next: { name: 'actions.scene.END_CONVERSATION', }, }; } else if (typeof listen === 'object' && listen.entities?.types) { const typeOverrideMode: TypeOverrideMode = listen.entities.mode === DynamicEntitiesMode.Merge ? TypeOverrideMode.Merge : TypeOverrideMode.Replace; if (!response.session) { response.session = getEmptySession(); } response.session.typeOverrides = Object.keys(listen.entities.types).map((entityName) => this.convertDynamicEntityToTypeOverride( entityName, ((listen.entities as DynamicEntities).types as DynamicEntityMap)[entityName], typeOverrideMode, ), ); } const message = output.message; if (message) { if (!response.prompt) { response.prompt = {}; } response.prompt.firstSimple = convertMessageToGoogleAssistantSimple(message); } const reprompt = output.reprompt; if (reprompt) { if (!response.session) { response.session = getEmptySession(); } const text = typeof reprompt === 'string' ? reprompt : reprompt.text || reprompt.speech; response.session.params._GOOGLE_ASSISTANT_REPROMPTS_ = { NO_INPUT_1: text, NO_INPUT_2: text, NO_INPUT_FINAL: text, }; } const quickReplies = output.quickReplies; if (quickReplies?.length) { if (!response.prompt) { response.prompt = {}; } response.prompt.suggestions = quickReplies .slice(0, 8) .map(this.convertQuickReplyToSuggestion); } const card = output.card; if (card) { if (!response.prompt) { response.prompt = {}; } if (!response.prompt.content) { response.prompt.content = {}; } response.prompt.content.card = card.toGoogleAssistantCard?.(); } const carousel = output.carousel; // Show a regular card if there is a single item in the carousel if ( carousel?.selection?.entityType && carousel?.selection?.intent && carousel.items.length === 1 ) { if (!response.prompt) { response.prompt = {}; } if (!response.prompt.content) { response.prompt.content = {}; } response.prompt.content.card = carousel.toGoogleAssistantCard?.(); } // if a carousel exists and selection.entityType is set for it (otherwise carousel can't be displayed) if ( carousel?.selection?.entityType && carousel?.selection?.intent && carousel.items.length > 1 ) { const collectionData = carousel.toGoogleAssistantCollectionData?.(); if (collectionData) { if (!response.session) { response.session = getEmptySession(); } if (!response.session.typeOverrides) { response.session.typeOverrides = []; } response.session.typeOverrides.push(collectionData.typeOverride); response.session.params._GOOGLE_ASSISTANT_SELECTION_INTENT_ = carousel.selection.intent; if (!response.prompt) { response.prompt = {}; } if (!response.prompt.content) { response.prompt.content = {}; } response.prompt.content.collection = collectionData.collection; } } if (output.platforms?.googleAssistant?.nativeResponse) { mergeInstances(response, output.platforms.googleAssistant.nativeResponse); } return response; } fromResponse(response: GoogleAssistantResponse): NormalizedOutputTemplate { const output: NormalizedOutputTemplate = {}; const simple = response.prompt?.firstSimple || response.prompt?.lastSimple; if (simple?.toMessage) { output.message = simple.toMessage(); } const reprompts = response.session?.params?._GOOGLE_ASSISTANT_REPROMPTS_ as | Record<'NO_INPUT_1' | 'NO_INPUT_2' | 'NO_INPUT_FINAL', string> | undefined; const reprompt = reprompts?.NO_INPUT_1 || reprompts?.NO_INPUT_2 || reprompts?.NO_INPUT_FINAL; if (reprompt) { output.reprompt = reprompt; } if (response.scene?.next?.name === 'actions.scene.END_CONVERSATION') { output.listen = false; } if (response.session?.typeOverrides?.length) { // only the first should be sufficient const mode = response.session.typeOverrides[0].typeOverrideMode === TypeOverrideMode.Merge ? DynamicEntitiesMode.Merge : DynamicEntitiesMode.Replace; output.listen = { entities: { mode, types: response.session.typeOverrides.reduce( (map: DynamicEntityMap, typeOverride: TypeOverride) => { map[typeOverride.name] = this.convertTypeOverrideToDynamicEntity(typeOverride); return map; }, {}, ), }, }; } const suggestions = response?.prompt?.suggestions; if (suggestions?.length) { output.quickReplies = suggestions.map((suggestion: Suggestion) => { return suggestion.toQuickReply!(); }); } const card = response.prompt?.content?.card; if (card?.toCard) { output.card = card.toCard(); } if (response?.session?.typeOverrides && response?.prompt?.content?.collection) { const carouselTypeOverride = response.session?.typeOverrides?.find((item: TypeOverride) => { return item.name === 'prompt_option'; }); if (carouselTypeOverride?.synonym) { output.carousel = { items: carouselTypeOverride.synonym.entries.map((entry: Entry) => { return { title: entry.display?.title || '', subtitle: entry.display?.description, imageUrl: entry.display?.image?.url, key: entry.name, }; }), }; } } return output; } convertQuickReplyToSuggestion(quickReply: QuickReplyValue): Suggestion { return typeof quickReply === 'string' ? { title: quickReply } : quickReply.toGoogleAssistantSuggestion?.() || { title: quickReply.text, }; } private convertDynamicEntityToTypeOverride( entityName: string, entity: DynamicEntity, mode: TypeOverrideModeLike = TypeOverrideMode.Replace, ): TypeOverride { return { name: entityName, typeOverrideMode: mode, synonym: { entries: (entity.values || []).map((entityValue) => ({ name: entityValue.id || entityValue.value, synonyms: entityValue.synonyms?.slice() || [], })), }, }; } private convertTypeOverrideToDynamicEntity(typeOverride: TypeOverride): DynamicEntity { return { values: (typeOverride.synonym?.entries || []).map((entry) => ({ id: entry.name, value: entry.name, synonyms: entry.synonyms?.slice(), })), }; } }
the_stack
import nj from 'numjs' import { FaceEmbedding, INPUT_FACE_SIZE, log, VERSION, } from './config' import { Face, } from './face' import { distance, imageToData, loadImage, resizeImage, } from './misc' import { PythonFacenet, } from './python3/python-facenet' // minimum width/height of the face image. // the standard shape of face for facenet is 160x160 // 40 is 1/16 of the low resolution // Update 2017/11/23: loose the limitation from 40 to 0 const MIN_FACE_SIZE = 0 const MIN_FACE_CONFIDENCE = 0.5 // Interface for Cache export interface Alignable { align(imageData: ImageData | string): Promise<Face[]>, } // Interface for Cache export interface Embeddingable { embedding(face: Face): Promise<FaceEmbedding>, } /** * * Facenet is designed for bring the state-of-art neural network with bleeding-edge technology to full stack developers * Neural Network && pre-trained model && easy to use APIs * @class Facenet */ export class Facenet implements Alignable, Embeddingable { private pythonFacenet: PythonFacenet constructor () { log.verbose('Facenet', `constructor() v${VERSION}`) this.pythonFacenet = new PythonFacenet() } public version (): string { return VERSION } /** * * Init facenet * @returns {Promise<void>} */ public async init (): Promise<void> { await this.initFacenet() await this.initMtcnn() } /** * @private */ public async initFacenet (): Promise<void> { log.verbose('Facenet', 'initFacenet()') const start = Date.now() await this.pythonFacenet.initFacenet() log.verbose('Facenet', 'initFacenet() cost %d milliseconds', Date.now() - start) } /** * @private */ public async initMtcnn (): Promise<void> { log.verbose('Facenet', 'initMtcnn()') const start = Date.now() await this.pythonFacenet.initMtcnn() log.verbose('Facenet', 'initMtcnn() cost %d milliseconds', Date.now() - start) } /** * * Quit facenet * @returns {Promise<void>} */ public async quit (): Promise<void> { log.verbose('Facenet', 'quit()') await this.pythonFacenet.quit() } /** * * Do face alignment for the image, return a list of faces. * @param {(ImageData | string)} imageData * @returns {Promise<Face[]>} - a list of faces * @example * const imageFile = `${__dirname}/../tests/fixtures/two-faces.jpg` * const faceList = await facenet.align(imageFile) * console.info(faceList) * // Output * // [ Face { * // id: 0, * // imageData: ImageData { data: [Object] }, * // confidence: 0.9999634027481079, * // landmark: * // { leftEye: [Object], * // rightEye: [Object], * // nose: [Object], * // leftMouthCorner: [Object], * // rightMouthCorner: [Object] }, * // location: { x: 360, y: 94, w: 230, h: 230 }, * // md5: '003c926dd9d2368a86e41a2938aacc98' }, * // Face { * // id: 1, * // imageData: ImageData { data: [Object] }, * // confidence: 0.9998626708984375, * // landmark: * // { leftEye: [Object], * // rightEye: [Object], * // nose: [Object], * // leftMouthCorner: [Object], * // rightMouthCorner: [Object] }, * // location: { x: 141, y: 87, w: 253, h: 253 }, * // md5: '0451a0737dd9e4315a21594c38bce485' } ] * // leftEye: [Object],rightEye: [Object],nose: [Object],leftMouthCorner: [Object],rightMouthCorner: [Object] -- Object is Point, something like { x: 441, y: 181 } * // imageData: ImageData { data: [Object] } -- Object is Uint8ClampedArray */ public async align (imageData: ImageData | string): Promise<Face[]> { if (typeof imageData === 'string') { log.verbose('Facenet', 'align(%s)', imageData) const image = await loadImage(imageData) imageData = imageToData(image) } else { log.verbose('Facenet', 'align(%dx%d)', imageData.width, imageData.height) } const [boundingBoxes, landmarks] = await this.pythonFacenet.align(imageData) log.silly('Facenet', 'align() pythonFacenet.align() done: %s', boundingBoxes) const xyLandmarks = this.transformMtcnnLandmarks(landmarks) const faceList: Face[] = [] for (const i in boundingBoxes) { const boundingBox = this.squareBox(boundingBoxes[i]) const confidence = boundingBoxes[i][4] const marks = xyLandmarks[i] // boundary out of image if (boundingBox[0] < 0 || boundingBox[1] < 0 || boundingBox[2] > imageData.width || boundingBox[3] > imageData.height ) { log.silly('Facenet', 'align(%dx%d) box[%s] out of boundary, skipped', imageData.width, imageData.height, boundingBox) continue } const face = new Face(imageData) await face.init({ boundingBox, landmarks: marks, confidence, }) if (face.width < MIN_FACE_SIZE) { log.verbose('Facenet', 'align() face skipped because width(%s) is less than MIN_FACE_SIZE(%s)', face.width, MIN_FACE_SIZE) continue } if ((face.confidence || 0) < MIN_FACE_CONFIDENCE) { log.verbose('Facenet', 'align() face skipped because confidence(%s) is less than MIN_FACE_CONFIDENCE(%s)', face.confidence, MIN_FACE_CONFIDENCE) continue } faceList.push(face) } return faceList } /** * * Calculate Face Embedding, get the 128 dims embeding from image(s) * * @param {Face} face * @returns {Promise<FaceEmbedding>} - return feature vector * @example * const imageFile = `${__dirname}/../tests/fixtures/two-faces.jpg` * const faceList = await facenet.align(imageFile) * for (const face of faceList) { * face.embedding = await facenet.embedding(face) * } * // Output, there are two faces in the picture, so return two 128 dims array * // array([ 0.03132, 0.05678, 0.06192, ..., 0.08909, 0.16793,-0.05703]) * // array([ 0.03422,-0.08358, 0.03549, ..., 0.07108, 0.14013,-0.01417]) */ public async embedding (face: Face): Promise<FaceEmbedding> { log.verbose('Facenet', 'embedding(%s)', face) let imageData = face.imageData if (!imageData) { throw new Error('no imageData!') } if (imageData.width !== imageData.height) { log.warn('Facenet', 'embedding(%s) %dx%d not square!', face, imageData.width, imageData.height) throw new Error('should be a square image because it will be resized to 160x160') } if (imageData.width !== INPUT_FACE_SIZE) { log.verbose('Facenet', 'embedding(%dx%d) got a face not 160x160, resizing...', imageData.width, imageData.height) imageData = await resizeImage( imageData, INPUT_FACE_SIZE, INPUT_FACE_SIZE, ) } const embedding = await this.pythonFacenet.embedding(imageData) // Set embedding to face // face.embedding = nj.array(embedding) return nj.array(embedding) } /** * @private */ public transformMtcnnLandmarks (landmarks: number[][]): number[][][] { // landmarks has a strange data structure: // https://github.com/kpzhang93/MTCNN_face_detection_alignment/blob/bace6de9fab6ddf41f1bdf1c2207c50f7039c877/code/codes/camera_demo/test.m#L70 const tLandmarks = nj.array(landmarks.reduce((a, b) => a.concat(b), [])) .reshape(10, -1) .T as nj.NdArray<number> const faceNum = tLandmarks.shape[0] const xyLandmarks = nj.zeros(tLandmarks.shape) const xLandmarks = xyLandmarks.slice(null as any, [null, xyLandmarks.shape[1], 2] as any) const yLandmarks = xyLandmarks.slice(null as any, [1, xyLandmarks.shape[1], 2] as any) xLandmarks.assign( tLandmarks.slice(null as any, [null, 5] as any), false, ) yLandmarks.assign( tLandmarks.slice(null as any, [5, 10] as any), false, ) const pairedLandmarks = xyLandmarks.reshape(faceNum, 5, 2) as nj.NdArray<number> // number[][][] return pairedLandmarks.tolist() as any as number[][][] } /** * @private */ public squareBox (box: number[]): number[] { let x0 = box[0] let y0 = box[1] let x1 = box[2] let y1 = box[3] // corner point: according to the canvas implementation: // it should include top left, but exclude bottom right. let w = x1 - x0 let h = y1 - y0 if (w !== h) { const halfDiff = Math.abs(w - h) / 2 if (w > h) { y0 -= halfDiff y1 += halfDiff } else { x0 -= halfDiff x1 += halfDiff } } // update w & h w = x1 - x0 h = y1 - y0 // keep w === h x0 = Math.round(x0) y0 = Math.round(y0) x1 = Math.round(x0 + w) y1 = Math.round(y0 + h) log.silly('Facenet', 'squareBox([%s]) -> [%d,%d,%d,%d]', box, x0, y0, x1, y1) return [x0, y0, x1, y1] } public distance(face: Face, faceList: Face[]): number[] public distance(embedding: number[], embeddingList: number[][]): number[] /** * Get distance between a face an each face in the faceList. * * @param {Face} face * @param {Face[]} faceList * @returns {number[]} * @example * const imageFile = `${__dirname}/../tests/fixtures/two-faces.jpg` * const faceList = await facenet.align(imageFile) * for (const face of faceList) { * face.embedding = await facenet.embedding(face) * } * const faceInFaceList = faceList[0] * const distance = facenet.distance(faceInFaceList, faceList) * console.info('distance:', distance) * // Output: * // distance: [ 0, 1.2971515811057608 ] * // The first face comes from the imageFile, the exactly same face, so the first result is 0. */ public distance (face: Face | number[], faceList: Face[] | number[][]): number[] { let embedding : number[] let embeddingList : number[][] if (Array.isArray(face)) { embedding = face embeddingList = faceList as number[][] } else { if (!face.embedding) { throw new Error('no face embedding!') } for (const theFace of (faceList as Face[])) { if (!theFace.embedding) { throw new Error('no aFace embedding!') } } embedding = face.embedding.tolist() embeddingList = (faceList as Face[]).map(f => (f.embedding as any).tolist()) // const embeddingNdArray = nj.stack<number>(embeddingList as any) } return distance( embedding, embeddingList, ) } }
the_stack
import {log} from '../console/log'; import {CombatIntel} from '../intel/CombatIntel'; import {Pathing} from '../movement/Pathing'; import {AttackStructurePriorities, AttackStructureScores} from '../priorities/priorities_structures'; import {profile} from '../profiler/decorator'; import {maxBy} from '../utilities/utils'; import {Visualizer} from '../visuals/Visualizer'; import {Swarm} from '../zerg/Swarm'; import {Zerg} from '../zerg/Zerg'; @profile export class CombatTargeting { /** * Finds the best target within a given range that a zerg can currently attack */ static findBestCreepTargetInRange(zerg: Zerg, range: number, targets = zerg.room.hostiles): Creep | undefined { const nearbyHostiles = _.filter(targets, c => zerg.pos.inRangeToXY(c.pos.x, c.pos.y, range)); return maxBy(nearbyHostiles, function(hostile) { if (hostile.hitsPredicted == undefined) hostile.hitsPredicted = hostile.hits; if (hostile.pos.lookForStructure(STRUCTURE_RAMPART)) return false; return hostile.hitsMax - hostile.hitsPredicted + CombatIntel.getHealPotential(hostile); // compute score }); } /** * Finds the best target within a given range that a zerg can currently attack */ static findBestStructureTargetInRange(zerg: Zerg, range: number, allowUnowned = true): Structure | undefined { let nearbyStructures = _.filter(zerg.room.hostileStructures, s => zerg.pos.inRangeToXY(s.pos.x, s.pos.y, range)); // If no owned structures to attack and not in colony room or outpost, target unowned structures if (allowUnowned && nearbyStructures.length == 0 && !Overmind.colonyMap[zerg.room.name]) { nearbyStructures = _.filter(zerg.room.structures, s => zerg.pos.inRangeToXY(s.pos.x, s.pos.y, range)); } return maxBy(nearbyStructures, function(structure) { let score = 10 * AttackStructureScores[structure.structureType]; if (structure.pos.lookForStructure(STRUCTURE_RAMPART)) score *= .1; return score; }); } /** * Standard target-finding logic */ static findTarget(zerg: Zerg, targets = zerg.room.hostiles): Creep | undefined { return maxBy(targets, function(hostile) { if (hostile.hitsPredicted == undefined) hostile.hitsPredicted = hostile.hits; if (hostile.pos.lookForStructure(STRUCTURE_RAMPART)) return false; return hostile.hitsMax - hostile.hitsPredicted + CombatIntel.getHealPotential(hostile) - 10 * zerg.pos.getMultiRoomRangeTo(hostile.pos); // compute score }); } /** * Finds the best target within a given range that a zerg can currently attack */ static findBestCreepTargetForTowers(room: Room, targets = room.hostiles): Creep | undefined { return maxBy(targets, function(hostile) { if (hostile.hitsPredicted == undefined) hostile.hitsPredicted = hostile.hits; if (hostile.pos.lookForStructure(STRUCTURE_RAMPART)) return false; return hostile.hitsMax - hostile.hitsPredicted + CombatIntel.getHealPotential(hostile) + (CombatIntel.towerDamageAtPos(hostile.pos) || 0); }); } static findClosestHostile(zerg: Zerg, checkReachable = false, ignoreCreepsAtEdge = true): Creep | undefined { if (zerg.room.hostiles.length > 0) { let targets: Creep[]; if (ignoreCreepsAtEdge) { targets = _.filter(zerg.room.hostiles, hostile => hostile.pos.rangeToEdge > 0); } else { targets = zerg.room.hostiles; } if (checkReachable) { const targetsByRange = _.sortBy(targets, target => zerg.pos.getRangeTo(target)); return _.find(targetsByRange, target => Pathing.isReachable(zerg.pos, target.pos, zerg.room.barriers)); } else { return zerg.pos.findClosestByRange(targets) as Creep | undefined; } } } // This method is expensive static findClosestReachable(pos: RoomPosition, targets: (Creep | Structure)[]): Creep | Structure | undefined { const targetsByRange = _.sortBy(targets, target => pos.getRangeTo(target)); return _.find(targetsByRange, target => Pathing.isReachable(pos, target.pos, target.room.barriers)); } static findClosestHurtFriendly(healer: Zerg): Creep | null { return healer.pos.findClosestByRange(_.filter(healer.room.creeps, creep => creep.hits < creep.hitsMax)); } /** * Finds the best (friendly) target in range that a zerg can currently heal */ static findBestHealingTargetInRange(healer: Zerg, range = 3, friendlies = healer.room.creeps): Creep | undefined { return maxBy(_.filter(friendlies, f => healer.pos.getRangeTo(f) <= range), friend => { if (friend.hitsPredicted == undefined) friend.hitsPredicted = friend.hits; const attackProbability = 0.5; for (const hostile of friend.pos.findInRange(friend.room.hostiles, 3)) { if (hostile.pos.isNearTo(friend)) { friend.hitsPredicted -= attackProbability * CombatIntel.getAttackDamage(hostile); } else { friend.hitsPredicted -= attackProbability * (CombatIntel.getAttackDamage(hostile) + CombatIntel.getRangedAttackDamage(hostile)); } } const healScore = friend.hitsMax - friend.hitsPredicted; if (healer.pos.getRangeTo(friend) > 1) { return healScore + CombatIntel.getRangedHealAmount(healer.creep); } else { return healScore + CombatIntel.getHealAmount(healer.creep); } }); } static findClosestPrioritizedStructure(zerg: Zerg, checkReachable = false): Structure | undefined { for (const structureType of AttackStructurePriorities) { const structures = _.filter(zerg.room.hostileStructures, s => s.structureType == structureType); if (structures.length == 0) continue; if (checkReachable) { const closestReachable = this.findClosestReachable(zerg.pos, structures) as Structure | undefined; if (closestReachable) return closestReachable; } else { return zerg.pos.findClosestByRange(structures) as Structure | undefined; } } } static findBestStructureTarget(pos: RoomPosition): Structure | undefined { const room = Game.rooms[pos.roomName]; // Don't accidentally destroy your own shit if (!room || room.my || room.reservedByMe) { return; } // Look for any unprotected structures const unprotectedRepairables = _.filter(room.repairables, s => { const rampart = s.pos.lookForStructure(STRUCTURE_RAMPART); return !rampart || rampart.hits < 10000; }); let approach = _.map(unprotectedRepairables, structure => { return {pos: structure.pos, range: 0}; }) as PathFinderGoal[]; if (room.barriers.length == 0 && unprotectedRepairables.length == 0) return; // if there's nothing in the room // Try to find a reachable unprotected structure if (approach.length > 0) { const ret = PathFinder.search(pos, approach, { maxRooms : 1, maxOps : 2000, roomCallback: roomName => { if (roomName != room.name) return false; const matrix = new PathFinder.CostMatrix(); for (const barrier of room.barriers) { matrix.set(barrier.pos.x, barrier.pos.y, 0xff); } return matrix; }, }); const targetPos = _.last(ret.path); if (!ret.incomplete && targetPos) { const targetStructure = _.first(_.filter(targetPos.lookFor(LOOK_STRUCTURES), s => { return s.structureType != STRUCTURE_ROAD && s.structureType != STRUCTURE_CONTAINER; })); if (targetStructure) { log.debug(`Found unprotected structure target @ ${targetPos.print}`); return targetStructure; } } } // Determine a "siege anchor" for what you eventually want to destroy let targets: Structure[] = room.spawns; if (targets.length == 0) targets = room.repairables; if (targets.length == 0) targets = room.barriers; if (targets.length == 0) targets = room.structures; if (targets.length == 0) return; // Recalculate approach targets approach = _.map(targets, s => { return {pos: s.pos, range: 0}; }); const maxWallHits = _.max(_.map(room.barriers, b => b.hits)) || 0; // Compute path with wall position costs weighted by fraction of highest wall const ret = PathFinder.search(pos, approach, { maxRooms : 1, plainCost : 1, swampCost : 2, roomCallback: roomName => { if (roomName != pos.roomName) return false; const matrix = new PathFinder.CostMatrix(); for (const barrier of room.barriers) { const cost = 100 + Math.round((barrier.hits / maxWallHits) * 100); matrix.set(barrier.pos.x, barrier.pos.y, cost); } return matrix; }, }); // Target the first non-road, non-container structure you find along the path for (const pos of ret.path) { const targetStructure = _.first(_.filter(pos.lookFor(LOOK_STRUCTURES), s => { return s.structureType != STRUCTURE_ROAD && s.structureType != STRUCTURE_CONTAINER; })); if (targetStructure) { log.debug(`Targeting structure @ ${targetStructure.pos.print}`); return targetStructure; } } } static findBestSwarmStructureTarget(swarm: Swarm, roomName: string, randomness = 0, displayCostMatrix = false): Structure | undefined { const room = Game.rooms[roomName]; // Don't accidentally destroy your own shit if (!room || room.my || room.reservedByMe) { return; } if (swarm.anchor.roomName != roomName) { log.warning(`Swarm is not in target room!`); return; } // // Look for any unprotected structures // let unprotectedRepairables = _.filter(room.repairables, s => { // let rampart = s.pos.lookForStructure(STRUCTURE_RAMPART); // return !rampart || rampart.hits < 10000; // }); // let approach = _.map(unprotectedRepairables, structure => { // return {pos: structure.pos, range: 0}; // }) as PathFinderGoal[]; // if (room.barriers.length == 0 && unprotectedRepairables.length == 0) return; // if there's nothing in the room // // // Try to find a reachable unprotected structure // if (approach.length > 0) { // let ret = PathFinder.search(swarm.anchor, approach, { // maxRooms : 1, // maxOps : 2000, // roomCallback: roomName => { // if (roomName != room.name) return false; // let matrix = Pathing.getSwarmTerrainMatrix(roomName, swarm.width, swarm.height).clone(); // for (let barrier of room.barriers) { // let setPositions = Pathing.getPosWindow(barrier.pos, -swarm.width, -swarm.height); // for (let pos of setPositions) { // matrix.set(pos.x, pos.y, 0xff); // } // } // return matrix; // }, // }); // let targetPos = _.last(ret.path); // if (!ret.incomplete && targetPos) { // let targetStructure = _.first(_.filter(targetPos.lookFor(LOOK_STRUCTURES), s => { // return s.structureType != STRUCTURE_ROAD && s.structureType != STRUCTURE_CONTAINER; // })); // if (targetStructure) { // log.debug(`Found unprotected structure target @ ${targetPos.print}`); // return targetStructure; // } // } // } // Determine a "siege anchor" for what you eventually want to destroy let targets: Structure[] = room.spawns; if (targets.length == 0) targets = room.towers; if (targets.length == 0) targets = room.repairables; if (targets.length == 0) targets = room.barriers; if (targets.length == 0) targets = room.structures; if (targets.length == 0) return; // Recalculate approach targets const approach = _.map(targets, s => { // TODO: might need to Pathing.getPosWindow() this return {pos: s.pos, range: 0}; }); const maxWallHits = _.max(_.map(room.barriers, b => b.hits)) || 0; // Compute path with wall position costs weighted by fraction of highest wall const ret = PathFinder.search(swarm.anchor, approach, { maxRooms : 1, plainCost : 1, swampCost : 2, roomCallback: rn => { if (rn != roomName) return false; const matrix = Pathing.getSwarmTerrainMatrix(roomName, swarm.width, swarm.height).clone(); for (const barrier of room.barriers) { const randomFactor = Math.min(Math.round(randomness * Math.random()), 100); const cost = 100 + Math.round((barrier.hits / maxWallHits) * 100) + randomFactor; const setPositions = Pathing.getPosWindow(barrier.pos, -swarm.width, -swarm.height); for (const pos of setPositions) { matrix.set(pos.x, pos.y, Math.max(cost, matrix.get(pos.x, pos.y))); } } if (displayCostMatrix) { Visualizer.displayCostMatrix(matrix, roomName); } return matrix; }, }); // Target the first non-road, non-container structure you find along the path or neighboring positions for (const pos of ret.path) { log.debug(`Searching path ${pos.print}...`); const searchPositions = Pathing.getPosWindow(pos, swarm.width, swarm.height); // not -1*width for (const searchPos of searchPositions) { const targetStructure = _.first(_.filter(searchPos.lookFor(LOOK_STRUCTURES), s => { return s.structureType != STRUCTURE_ROAD && s.structureType != STRUCTURE_CONTAINER; })); if (targetStructure) { log.debug(`Targeting structure @ ${targetStructure.pos.print}`); return targetStructure; } } } } }
the_stack
import uuid = require('node-uuid'); import io = require('socket.io-client'); import { Subject } from 'rxjs/Subject'; import { Observer } from 'rxjs/Observer'; import { Observable } from 'rxjs/Observable'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { Subscription } from 'rxjs/Subscription'; import { KSeq, Op } from '../kseq'; import { getSignalerURI, Message, PeersRequest, PeersUpdate, ConnectionRequest, ConnectionResponse, PadEdit, PadUpdate, CursorMap } from '../signaler/Protocol'; import { UserModel } from './UserModel'; import { BlindpadService } from './blindpad.service'; import { compressOpSet, decompressOpSet } from '../util/Compress'; import { diffStrings, DIFF_DELETE, DIFF_INSERT } from '../util/Diff'; import { interval } from '../util/Observables'; import { SeededRandom } from '../util/Random'; import { debounce } from '../util/Debounce'; /** * After how many milliseconds without an edit can we trigger a pad compaction (assuming all other conditions are met?) */ const COMPACTION_DELAY_MS = 4000; const PEER_TIMEOUT_POLL_MS = 5000; const COMPACTION_POLL_MS = 1000; export class PadModel { private useLog = true; private clientId: string; private signaler: SocketIOClient.Socket; private activePeers: Set<string>; private deadPeers: Set<string>; private users: Map<string, UserModel>; private activeUsers: Map<string, UserModel>; private mimeType: BehaviorSubject<string>; private doc: KSeq<string>; private base: string; private baseVersion: number; private opSet: Set<string>; private memoizedOpSetStr: string; private mostRecentCursors: CursorMap; private lastEditTime: number; private outgoingUserBroadcasts: Subject<Message>; private localEdits: Subject<PadEdit[]>; private remoteEdits: Subject<PadEdit[]>; private localCursors: Subject<CursorMap>; private remoteCursors: Subject<CursorMap>; private debouncedPadUpdate: () => void; private debouncedIsLightweight = true; private peerTimeoutSub: Subscription; private compactionSub: Subscription; constructor( private padId: string, private blindpadService: BlindpadService ) { this.clientId = uuid.v1(); this.activePeers = new Set<string>(); this.deadPeers = new Set<string>(); this.users = new Map<string, UserModel>(); this.mimeType = new BehaviorSubject(null); this.mostRecentCursors = null; this.outgoingUserBroadcasts = new Subject<Message>(); this.localEdits = new Subject<PadEdit[]>(); this.remoteEdits = new Subject<PadEdit[]>(); this.localCursors = new Subject<CursorMap>(); this.remoteCursors = new Subject<CursorMap>(); this.localEdits.subscribe(this.onLocalEdits); this.localCursors.subscribe(this.onLocalCursors); this.localEdits.subscribe(edits => this.lastEditTime = Date.now()); this.remoteEdits.subscribe(edits => this.lastEditTime = Date.now()); this.activePeers.add(this.clientId); this.updateUsers([], []); this.setBaseDoc('', 0); } getPadId(): string { return this.padId; } getClientId(): string { return this.clientId; } getLocalUser(): UserModel { return this.users.get(this.clientId); } getUsers(): Map<string, UserModel> { return this.activeUsers; } getAllUsers(): Map<string, UserModel> { return this.users; } log(...msg: any[]) { if (this.useLog) console.log('', ...msg); } // tslint:disable-line isSignalerConnected(): boolean { return this.signaler && this.signaler.connected; } getOutoingUserBroadcasts(): Observable<Message> { return this.outgoingUserBroadcasts; } getLocalEdits(): Observer<PadEdit[]> { return this.localEdits; } getRemoteEdits(): Observable<PadEdit[]> { return this.remoteEdits; } getLocalCursors(): Observer<CursorMap> { return this.localCursors; } getRemoteCursors(): Observable<CursorMap> { return this.remoteCursors; } getMimeType(): BehaviorSubject<string> { return this.mimeType; } setMimeType(mime: string) { if (mime !== this.mimeType.value) this.mimeType.next(mime); } buildPadUpdate(isLightweight = true): PadUpdate { const update = new PadUpdate(); update.srcId = this.clientId; update.padId = this.padId; if (this.mimeType.value) update.mimeType = this.mimeType.value; if (this.mostRecentCursors) update.cursors = this.mostRecentCursors; if (!isLightweight) { update.base = this.base; update.baseVersion = this.baseVersion; if (this.memoizedOpSetStr === null) { this.memoizedOpSetStr = compressOpSet(this.opSet); } update.opSetStr = this.memoizedOpSetStr; } return update; } start() { if (this.isStarted()) return; // already started const signalerURI = getSignalerURI(); this.log('Looking for signaler: ', signalerURI); this.signaler = io.connect(signalerURI); this.remoteEdits.next([]); // kind of a hack, tells the editor that we're starting this.setMimeType(null); this.signaler.on('connect', () => { this.log('Connected to signaler, asking for peers!'); const req = new PeersRequest(); req.padId = this.padId; req.srcId = this.clientId; req.knownActivePeers = Array.from(this.activePeers.values()); req.knownDeadPeers = Array.from(this.deadPeers.values()); this.signaler.emit(PeersRequest.messageType, req); }); this.signaler.on(PeersRequest.messageType, (data: PeersRequest) => { this.log(PeersRequest.messageType, data); if (!this.isValidMessage(data)) return; this.updateUsers(data.knownActivePeers, data.knownDeadPeers); // TODO: don't send response if they knew the same or more than us const update = new PeersUpdate(); update.padId = this.padId; update.srcId = this.clientId; update.activePeers = Array.from(this.activePeers.values()); update.deadPeers = Array.from(this.deadPeers.values()); this.signaler.emit(PeersUpdate.messageType, update); }); this.signaler.on(PeersUpdate.messageType, (data: PeersUpdate) => { this.log(PeersUpdate.messageType, data); if (!this.isValidMessage(data)) return; this.updateUsers(data.activePeers, data.deadPeers); }); this.signaler.on(ConnectionRequest.messageType, (data: ConnectionRequest) => { this.log(ConnectionRequest.messageType, data); if (!this.isValidConnectionMessage(data)) return; this.users.get(data.srcId).feedMessage(ConnectionRequest.messageType, data); }); this.signaler.on(ConnectionResponse.messageType, (data: ConnectionResponse) => { this.log(ConnectionResponse.messageType, data); if (!this.isValidConnectionMessage(data)) return; this.users.get(data.srcId).feedMessage(ConnectionResponse.messageType, data); }); this.signaler.on('DEBUG', (data: any) => { this.log('DEBUG (signaler): ', data); }); this.signaler.on('disconnect', () => { this.log('disconnected from signaler'); }); this.mimeType.subscribe(type => { if (type) this.firePadUpdate(true); }); this.peerTimeoutSub = interval(PEER_TIMEOUT_POLL_MS).subscribe(this.onPeerTimeoutTick); this.compactionSub = interval(COMPACTION_POLL_MS).subscribe(this.onCompactionTick); } close() { if (!this.isStarted()) return; this.killUsersAndSignal([this.clientId]); this.users.forEach(user => { user.close(); }); this.users.clear(); if (this.signaler) this.signaler.close(); this.mimeType.complete(); this.localEdits.complete(); this.remoteEdits.complete(); this.localCursors.complete(); this.remoteCursors.complete(); this.peerTimeoutSub.unsubscribe(); this.compactionSub.unsubscribe(); } isStarted(): boolean { return !!this.signaler; } /* private methods */ private updateUsers(actives: string[], deads: string[]) { // process any new peer information in the request actives.forEach(activeId => { // old news if (this.deadPeers.has(activeId)) { return; } this.activePeers.add(activeId); }); deads.forEach(deadId => { if (this.activePeers.has(deadId)) { this.activePeers.delete(deadId); } this.deadPeers.add(deadId); }); const oldUsers = this.users; this.users = new Map<string, UserModel>(); this.activeUsers = new Map<string, UserModel>(); [this.activePeers, this.deadPeers].forEach(set => { set.forEach(peerId => { let user = oldUsers.get(peerId); if (!user) { user = new UserModel(peerId, this, this.blindpadService); if (this.activePeers.has(peerId)) { user.getMessagesOut(ConnectionRequest.messageType).subscribe(this.signalRequest); user.getMessagesOut(ConnectionResponse.messageType).subscribe(this.signalResponse); user.getMessagesIn(PadUpdate.messageType).subscribe(this.onPadUpdate); } } this.users.set(peerId, user); if (this.activePeers.has(peerId)) { this.activeUsers.set(peerId, user); if (!user.isStarted()) user.start(); } if (this.deadPeers.has(peerId)) { if (!user.isClosed()) { user.close(); // make sure to clear the cursor of anyone we see die const tombstoneCursor: CursorMap = {}; tombstoneCursor[peerId] = null; this.remoteCursors.next(tombstoneCursor); } } }); }); } private onLocalEdits = (edits: PadEdit[]) => { if (!edits || edits.length === 0) return; const newOps: Op[] = []; edits.forEach(edit => { const text = edit.text; const idx = edit.index; if (edit.isInsert) { for (let i = text.length - 1; i >= 0; i--) { const op = this.doc.insert(text.charAt(i), idx); newOps.push(op); } } else { for (let i = 0, l = text.length; i < l; i++) { const op = this.doc.remove(idx); newOps.push(op); } } }); if (newOps.length > 0) { newOps.forEach(op => this.opSet.add(op.toString())); this.memoizedOpSetStr = null; // clear a saved value since we changed the canonical one this.firePadUpdate(false); } }; private onPadUpdate = (update: PadUpdate) => { if (update.mimeType !== undefined && update.mimeType !== this.mimeType.value) { this.mimeType.next(update.mimeType); } if (update.base !== undefined && update.baseVersion !== undefined && update.opSetStr !== undefined) { if (this.base === update.base && this.baseVersion === update.baseVersion) { // regular update: we agree on base and version, let's just combine our ops and be done const opsToApply: string[] = []; const haveUpdate = !!update.opSetStr; const sameAsMemoized = this.memoizedOpSetStr && this.memoizedOpSetStr === update.opSetStr; if (haveUpdate && !sameAsMemoized) { decompressOpSet(update.opSetStr).forEach(op => { if (!this.opSet.has(op)) opsToApply.push(op); }); } this.applyOpsAndRender(opsToApply); } else if (update.baseVersion > this.baseVersion) { // remote is newer, blow ours away this.setBaseDoc(update.base, update.baseVersion); this.applyOpsAndRender(decompressOpSet(update.opSetStr)); } else if (this.baseVersion === update.baseVersion && this.base !== update.base) { // we must've had a split compaction (two people thought they were the master and advanced) if (update.srcId > this.clientId) { // accept the bigger client's view of reality this.setBaseDoc(update.base, update.baseVersion); this.applyOpsAndRender(decompressOpSet(update.opSetStr)); } } } if (update.cursors !== undefined) { const newCursors: CursorMap = {}; Object.keys(update.cursors || {}).forEach(userId => { const cursor = update.cursors[userId]; // ignore the cursor if they're not alive if (!this.activeUsers.has(userId)) return; // ignore ours (this is only for remote cursors: we trust ourselves to know our own cursor) if (userId === this.clientId) return; // we could either take every cursor with every update // or we could only update the ones coming authoritatively from the sender // of the update and allow the pad changes / codemirror logic to do the rest. // we're going to do the latter for now if (userId === update.srcId) { newCursors[userId] = cursor; } }); this.remoteCursors.next(newCursors); } }; private applyOpsAndRender(ops: string[]) { ops = ops || []; if (ops.length === 0) return; const oldVersion = this.doc.toArray().join(''); let numApplied = 0; ops.forEach(op => { if (this.opSet.has(op)) return; this.doc.apply(Op.parse(op)); this.opSet.add(op); numApplied++; }); if (numApplied === 0) return; const newVersion = this.doc.toArray().join(''); const versionDiff = diffStrings(oldVersion, newVersion); let idx = 0; const edits: PadEdit[] = []; versionDiff.forEach(([type, value]) => { if (type === DIFF_INSERT) { const insert = new PadEdit(); insert.index = idx; insert.isInsert = true; insert.text = value; edits.push(insert); } else if (type === DIFF_DELETE) { const remove = new PadEdit(); remove.index = idx; remove.isInsert = false; remove.text = value; edits.push(remove); } if (type !== DIFF_DELETE) idx += value.length; }); if (edits.length > 0) this.remoteEdits.next(edits); } private onLocalCursors = (cursors: CursorMap) => { this.mostRecentCursors = cursors; this.firePadUpdate(true); }; /** * Broadcast an update in our version of the pad to other users: to save on bandwidth * calls to this will be debounced based on the size of the current opSet (which dominates the * size of the message). */ private firePadUpdate(isLightweight: boolean) { this.debouncedIsLightweight = !!this.debouncedIsLightweight && isLightweight; if (!this.debouncedPadUpdate) { const delay = 25 * Math.pow(Math.log10(this.opSet.size + 1), 2); this.debouncedPadUpdate = debounce(() => { this.sendUpdateNow(this.debouncedIsLightweight); this.debouncedPadUpdate = null; this.debouncedIsLightweight = true; }, delay); } this.debouncedPadUpdate(); } private sendUpdateNow(isLightweight: boolean) { this.outgoingUserBroadcasts.next({ type: PadUpdate.messageType, data: this.buildPadUpdate(isLightweight) }); } private onCompactionTick = () => { // if (1 === 1) return; // disble compaction // conditions under which we should broadcast a compaction: // we're not dead if (!this.activePeers.has(this.clientId)) return; // we have an opset if (this.opSet.size === 0) return; // we're the largest client id in the swarm (kind of a janky master) if (!this.isLargestPeer()) return; // we're either by ourself or we have at least one responsive peer (i.e. we're not totally isolated from the swarm) if (this.activePeers.size > 1 && this.getResponsivePeers().length === 0) return; // it's been more than a certain fixed amount of time since the last pad edit if (Date.now() - this.lastEditTime < COMPACTION_DELAY_MS) return; this.setBaseDoc(this.doc.toArray().join(''), this.baseVersion + 1); this.sendUpdateNow(false); }; private onPeerTimeoutTick = () => { // conditions under which we should broadcast timed out peers as dead // we're not dead if (!this.activePeers.has(this.clientId)) return; // we have peers if (this.activePeers.size < 2) return; // at least one of them is timed out if (this.getTimedOutPeers().length === 0) return; // we can hit the network (to ensure we're not isolated) const req = new XMLHttpRequest(); req.onreadystatechange = () => { if (req.readyState !== XMLHttpRequest.DONE || req.status !== 200) return; // we know we're online const timedOutIds = this.getTimedOutPeers().map(user => user.getId()); if (timedOutIds.length > 0) this.killUsersAndSignal(timedOutIds); }; req.timeout = PEER_TIMEOUT_POLL_MS / 2; req.open('GET', `/index.html?t=${Date.now()}`, true); // prevent caching req.send(); } private getResponsivePeers(): Array<UserModel> { return Array.from(this.activeUsers.values()).filter(user => user.isRemoteUser() && !user.isUnavailable()); } private getTimedOutPeers(): Array<UserModel> { return Array.from(this.activeUsers.values()).filter(user => user.isRemoteUser() && user.isTimedOut()); } private isLargestPeer(): boolean { return this.clientId !== Array.from(this.activePeers).reduce((prev, cur) => cur > prev ? cur : prev); } private killUsersAndSignal(peerIds: Array<string>) { this.updateUsers([], peerIds); const update = new PeersUpdate(); update.padId = this.padId; update.srcId = this.clientId; update.activePeers = Array.from(this.activePeers.values()); update.deadPeers = Array.from(this.deadPeers.values()); this.signaler.emit(PeersUpdate.messageType, update); } private setBaseDoc(base: string, version: number) { const oldVersion = this.doc ? this.doc.toArray().join('') : ''; this.base = base; this.baseVersion = version; this.doc = new KSeq<string>(this.clientId.substring(0, 6)); // this is probably way too collision-happy this.opSet = new Set<string>(); // for correctness our "base" text" just implies a set of operations // that all peers agree on (in this case made by a simulated third party) const rng = new SeededRandom(version); const baseDoc = new KSeq<string>('' + version, () => version, () => rng.random()); for (let i = 0, l = base.length; i < l; i++) { this.doc.apply(baseDoc.insert(base.charAt(i), i)); } this.memoizedOpSetStr = null; this.lastEditTime = Date.now(); // if post-compaction the doc has changed flush the new version of the doc as remove+insert edits if (oldVersion !== this.base) { const remove = new PadEdit(); remove.index = 0; remove.isInsert = false; remove.text = oldVersion; const add = new PadEdit(); add.index = 0; add.isInsert = true; add.text = this.base; this.remoteEdits.next([remove, add]); } } private signalRequest = (req: ConnectionRequest) => { this.signaler.emit(ConnectionRequest.messageType, req); }; private signalResponse = (res: ConnectionResponse) => { this.signaler.emit(ConnectionResponse.messageType, res); }; private isValidMessage(msg: PeersRequest | PeersUpdate | ConnectionRequest | ConnectionResponse): boolean { if (msg.padId !== this.padId) { console.log(`Message padId (${msg.padId}) doesn't match local padId: ${this.padId}, ignoring...`); // tslint:disable-line return false; } return true; } private isValidConnectionMessage(msg: ConnectionRequest | ConnectionResponse): boolean { if (!this.isValidMessage(msg)) return false; if (!msg.destId || msg.destId !== this.clientId) { this.log('destId missing or not for us, ignoring...'); return false; } if (!msg.srcId) { this.log('srcId missing, ignoring...'); return false; } if (!this.activePeers.has(msg.srcId)) { this.log(`srcId ${msg.srcId} not an active peer, ignoring...`); return false; } return true; } }
the_stack
import { Channel } from 'channel/channel' import { ExtendedSocket } from 'extendedsocket' import { CSO2TakeDamageInfo, TDIKillFlags } from 'gametypes/cso2takedamageinfo' import { CSTeamNum, RoomTeamBalance, RoomGamemode } from 'gametypes/shareddefs' import { MatchProgress } from 'room/matchprogress' import { RoomSettings } from 'room/roomsettings' import { RoomUserEntry } from 'room/roomuserentry' import { InRoomUpdateSettings } from 'packets/in/room/updatesettings' import { OutHostPacket } from 'packets/out/host' import { OutRoomPacket } from 'packets/out/room' import { OutUdpPacket } from 'packets/out/udp' import { OutUserInfoPacket } from 'packets/out/userinfo' import { ActiveConnections } from 'storage/activeconnections' import { UserSession } from 'user/usersession' import { UserService } from 'services/userservice' export enum RoomReadyStatus { NotReady = 0, Ingame = 1, Ready = 2 } export interface IRoomOptions { roomName?: string roomPassword?: string gameModeId?: number mapId?: number winLimit?: number killLimit?: number startMoney?: number forceCamera?: number nextMapEnabled?: number changeTeams?: number enableBots?: boolean difficulty?: number respawnTime?: number teamBalance?: number weaponRestrictions?: number hltvEnabled?: number } export enum RoomStatus { Waiting = 1, Ingame = 2 } const defaultCountdownNum = 7 export class Room { /** * remove an user from its current room * if the user isn't in a room then it won't do anything * @param user the target user * @returns true if successful or if not in a room, false if not */ public static cleanUpUser(conn: ExtendedSocket): boolean { const session: UserSession = conn.session if (session == null) { return false } const room: Room = session.currentRoom if (room == null) { return false } room.removeUser(session.user.id) session.currentRoom = null return true } public id: number public settings: RoomSettings public host: RoomUserEntry public usersInfo: RoomUserEntry[] private emptyRoomCallback: (emptyRoom: Room, channel: Channel) => void private parentChannel: Channel private countingDown: boolean private countdown: number private ingameMatchProgress: MatchProgress constructor( roomId: number, hostUserId: number, hostConn: ExtendedSocket, parentChannel: Channel, emptyRoomCallback?: (emptyRoom: Room, channel: Channel) => void, options?: IRoomOptions ) { this.id = roomId this.usersInfo = [] this.parentChannel = parentChannel this.emptyRoomCallback = emptyRoomCallback this.settings = new RoomSettings(options) this.countingDown = false this.countdown = defaultCountdownNum this.host = this.addUser(hostUserId, hostConn) this.ingameMatchProgress = new MatchProgress() } /** * gives the ammount of player slots available in the room * @returns the free player slots */ public getFreeSlots(): number { const availableSlots: number = this.settings.maxPlayers - this.usersInfo.length return Math.max(0, availableSlots) } /** * does this room have free player slots? * @returns true if so, false if not */ public hasFreeSlots(): boolean { return this.getFreeSlots() !== 0 } /** * is this room password protected? * @returns true if so, false if not */ public IsPasswordProtected(): boolean { return ( this.settings.roomPassword != null && this.settings.roomPassword.length > 0 ) } /** * compares any password with the room's * @param password the password we need to check * @returns true if the password matches, false if it doesn't */ public ComparePassword(password: string): boolean { return this.settings.roomPassword === password } /** * is the user in the room? * @param userId the user ID to find * @returns true the user is found, false if not */ public hasUser(userId: number): boolean { return this.getRoomUser(userId) != null } /** * add an user to a room * @param userId the target user's ID * @returns the created user's room data */ public addUser(userId: number, connection: ExtendedSocket): RoomUserEntry { const userData: RoomUserEntry = new RoomUserEntry( userId, connection, this.findDesirableTeamNum(), RoomReadyStatus.NotReady ) this.usersInfo.push(userData) return userData } /** * remove an user from a room * @param userId the user to be removed ID */ public removeUser(userId: number): void { for (const info of this.usersInfo) { if (info.userId === userId) { this.usersInfo.splice(this.usersInfo.indexOf(info), 1) this.onUserRemoved(info.userId) return } } } /** * count the ammount of users on each team and returns the team with less users * @returns the team with less users */ public findDesirableTeamNum(): CSTeamNum { let trNum = 0 let ctNum = 0 for (const userData of this.usersInfo.values()) { const team: CSTeamNum = userData.team if (team === CSTeamNum.Terrorist) { trNum++ } else if (team === CSTeamNum.CounterTerrorist) { ctNum++ } else { console.warn('Room::findDesirableTeamNum: Unknown team number') } } // // send new players to the host's team, if bot mode is enabled // if (this.settings.areBotsEnabled) { // make sure there is at least one human player if (trNum + ctNum > 0) { const hostTeamNum: CSTeamNum = this.host.team return hostTeamNum } } if (trNum < ctNum) { return CSTeamNum.Terrorist } else { return CSTeamNum.CounterTerrorist } } /** * returns an user's current team * @param userId the target user's ID */ public getUserTeam(userId: number): CSTeamNum { const info: RoomUserEntry = this.getRoomUser(userId) if (info == null) { console.warn('getUserTeam: userId %i not found', userId) return CSTeamNum.Unknown } return info.team } /** * gives the number of playersthat are ready * @returns the num of players ready */ public getNumOfReadyRealPlayers(): number { let numReadyPlayers = 0 for (const info of this.usersInfo) { if (info.isReady() === true || info === this.host) { numReadyPlayers++ } } return numReadyPlayers } /** * gives the number of elements in the counter terrorist team */ public getNumOfRealCts(): number { let numCt = 0 for (const userData of this.usersInfo.values()) { const team: CSTeamNum = userData.team if (team === CSTeamNum.CounterTerrorist) { numCt++ } } return numCt } /** * gives the number of elements in the terrorist team */ public getNumOfRealTerrorists(): number { let numTerrorists = 0 for (const userData of this.usersInfo.values()) { const team: CSTeamNum = userData.team if (team === CSTeamNum.Terrorist) { numTerrorists++ } } return numTerrorists } /** * gives the number of players (bots included) that are ready * @returns the num of players ready */ public getNumOfReadyPlayers(): number { let botPlayers: number = this.settings.numCtBots + this.settings.numTrBots if (this.settings.teamBalanceType === RoomTeamBalance.WithBots) { const numCts: number = this.getNumOfRealCts() const numTer: number = this.getNumOfRealTerrorists() const requiredBalanceBots: number = Math.abs(numCts - numTer) botPlayers = Math.max(botPlayers, requiredBalanceBots) } return this.getNumOfReadyRealPlayers() + botPlayers } /** * get's an user's room information through its ID * @param userId the target user's ID * @returns the user's room info if found, else it returns null */ public getRoomUser(userId: number): RoomUserEntry { return this.usersInfo.find((u: RoomUserEntry) => u.userId === userId) } /** * returns an user's ready status * @param userId the target user's ID */ public getUserReadyStatus(user: RoomUserEntry): RoomReadyStatus { return user.ready } /** * checks if an user is ready * @param userId the target user's ID * @returns true if an user is ready, false if not */ public isUserReady(userId: number): boolean { const userInfo: RoomUserEntry = this.getRoomUser(userId) if (userInfo == null) { console.warn(`couldnt get user's room data (userId: ${userId})`) return false } return userInfo.ready === RoomReadyStatus.Ready } /** * is the user ingame? * @param userId the target user's ID * @returns true if it is, false if not */ public isUserIngame(userId: number): boolean { const user: RoomUserEntry = this.getRoomUser(userId) if (user == null) { return false } return user.isIngame } /** * checks if the room's users are ready * @returns true if everyone is ready, false if not */ public isRoomReady(): boolean { for (const info of this.usersInfo) { if (info.isReady() === false) { return false } } return true } /** * set's an user's current team number and sends it to everyone in the room * @param user the target user's ID * @param newTeam the user's new team */ public updateUserTeam(userId: number, newTeam: CSTeamNum): void { const user: RoomUserEntry = this.getRoomUser(userId) user.team = newTeam // inform every user in the room of the changes this.broadcastNewUserTeamNum(userId, newTeam) } /** * set's an user's ingame status * @param user the target user * @param ingame the new ingame status */ public setUserIngame(user: RoomUserEntry, ingame: boolean): void { user.isIngame = ingame user.ready = ingame ? RoomReadyStatus.Ingame : RoomReadyStatus.NotReady } /** * toggles the user's room ready status * @param userId the target user's ID * @param newStatus the user's new ready status * @returns the new ready state */ public toggleUserReadyStatus(userId: number): RoomReadyStatus { if (userId === this.host.userId) { console.warn('toggleUserReadyStatus: host tried to toggle ready') return null } const userInfo: RoomUserEntry = this.getRoomUser(userId) if (userInfo == null) { console.warn('toggleUserReadyStatus: couldnt get userinfo') return null } if (userInfo.isIngame === true) { console.warn( `toggleUserReadyStatus: user ${userId} tried to toggle ready status while ingame` ) return null } const curStatus: RoomReadyStatus = userInfo.ready const newStatus: RoomReadyStatus = curStatus === RoomReadyStatus.NotReady ? RoomReadyStatus.Ready : RoomReadyStatus.NotReady userInfo.ready = newStatus return newStatus } /** * resets the ready status of ingame users * @returns true if reset successfully, false if not */ public resetIngameUsersReadyStatus(): boolean { for (const user of this.usersInfo) { if (user == null) { console.warn( 'resetIngameUsersReadyStatus: couldnt get userinfo' ) return false } user.ready = RoomReadyStatus.NotReady } return true } /** * get's a room's status * @returns the room's status */ public getStatus(): RoomStatus { return this.settings.status } /** * set a room's status * @param newStatus the new room's status */ public setStatus(newStatus: RoomStatus): void { this.settings.status = newStatus this.settings.isIngame = newStatus === RoomStatus.Ingame this.ingameMatchProgress.SetIngame(this.settings.isIngame) } /** * progress through the 'game start' countdown * the room's host must send countdown requests in order to progress it * TODO: maybe do the countdown without depending on the room's host * @param hostNextNum the host's next countdown number */ public progressCountdown(hostNextNum: number): void { if (this.countdown > defaultCountdownNum || this.countdown < 0) { console.warn('Room: the saved countdown is invalid!') this.countdown = 0 } if (this.countingDown === false) { this.countingDown = true } this.countdown-- if (this.countdown !== hostNextNum) { console.warn( `host's countdown does not match ours. ours ${this.countdown} host ${hostNextNum}` ) } } /** * @returns the current room countdown number */ public getCountdown(): number { if (this.countingDown === false) { console.warn( 'getCountdown: tried to get countdown without counting down' + 'this is most likely a bug' ) return 0 } // make sure the countdown is inbounds if (this.countdown > defaultCountdownNum || this.countdown < 0) { console.warn( `our countdown is out of bounds. it's ${this.countdown}` ) this.countdown = 0 } return this.countdown } /** * checks if a room's game countdown is in progress * @returns true if it's in progress, false if not */ public isGlobalCountdownInProgress(): boolean { return this.countingDown } /** * stops and resets the 'game start' countdown */ public stopCountdown(): void { this.countingDown = false this.countdown = defaultCountdownNum } /** * ends a match and sends players to the match results screen */ public async endGame(): Promise<void> { this.setStatus(RoomStatus.Waiting) this.resetIngameUsersReadyStatus() this.recurseUsers((u: RoomUserEntry): void => { this.sendRoomStatusTo(u) this.sendRoomUsersReadyStatusTo(u) if (this.isUserIngame(u.userId) === true) { this.sendGameEnd(u) this.setUserIngame(u, false) } }) this.sendBroadcastReadyStatus() await this.RewardUsers() } /** * can we start counting down until the game start? * @returns true if we can countdown, else false */ public canStartGame(): boolean { const gamemode = this.settings.gameModeId switch (gamemode) { case RoomGamemode.deathmatch: case RoomGamemode.original: case RoomGamemode.originalmr: case RoomGamemode.casualbomb: case RoomGamemode.casualoriginal: case RoomGamemode.eventmod01: case RoomGamemode.eventmod02: case RoomGamemode.diy: case RoomGamemode.campaign1: case RoomGamemode.campaign2: case RoomGamemode.campaign3: case RoomGamemode.campaign4: case RoomGamemode.campaign5: case RoomGamemode.tdm_small: case RoomGamemode.de_small: case RoomGamemode.madcity: case RoomGamemode.madcity_team: case RoomGamemode.gunteamdeath: case RoomGamemode.gunteamdeath_re: case RoomGamemode.stealth: case RoomGamemode.teamdeath: case RoomGamemode.teamdeath_mutation: if (this.getNumOfReadyPlayers() < 2) { return false } break case RoomGamemode.giant: case RoomGamemode.hide: case RoomGamemode.hide2: case RoomGamemode.hide_match: case RoomGamemode.hide_origin: case RoomGamemode.hide_Item: case RoomGamemode.hide_multi: case RoomGamemode.ghost: case RoomGamemode.pig: case RoomGamemode.tag: case RoomGamemode.zombie: case RoomGamemode.zombiecraft: case RoomGamemode.zombie_commander: case RoomGamemode.zombie_prop: case RoomGamemode.zombie_zeta: if (this.getNumOfReadyRealPlayers() < 2) { return false } break } return true } /** * loop through all the players * @param fn the func to call in each user */ public recurseUsers(fn: (u: RoomUserEntry) => void): void { for (const user of this.usersInfo) { fn(user) } } /** * loop through all the non host players * @param fn the func to call in each user */ public recurseNonHostUsers(fn: (u: RoomUserEntry) => void): void { for (const user of this.usersInfo) { if (user !== this.host) { fn(user) } } } /** * send the room's data to the user that joined the room * @param userId the new user's ID */ public sendJoinNewRoom(userId: number): void { const user: RoomUserEntry = this.getRoomUser(userId) user.conn.send(OutRoomPacket.createAndJoin(this)) } /** * update room's settings and broadcast them to everyone in it * @param newSettings the requested new room's settings */ public updateSettings(newSettings: InRoomUpdateSettings): void { if (newSettings.roomName != null) { this.settings.roomName = newSettings.roomName } if (newSettings.roomPassword != null) { this.settings.roomPassword = newSettings.roomPassword } if (newSettings.gameModeId != null) { this.settings.gameModeId = newSettings.gameModeId } if (newSettings.mapId != null) { this.settings.mapId = newSettings.mapId } if (newSettings.killLimit != null) { this.settings.killLimit = newSettings.killLimit } if (newSettings.winLimit != null) { this.settings.winLimit = newSettings.winLimit } if (newSettings.startMoney != null) { this.settings.startMoney = newSettings.startMoney } if (newSettings.maxPlayers != null) { this.updateMaxPlayers(newSettings.maxPlayers) } if (newSettings.respawnTime != null) { this.settings.respawnTime = newSettings.respawnTime } if (newSettings.changeTeams != null) { this.settings.changeTeams = newSettings.changeTeams } if (newSettings.forceCamera != null) { this.settings.forceCamera = newSettings.forceCamera } if (newSettings.teamBalanceType != null) { this.settings.teamBalanceType = newSettings.teamBalanceType } if (newSettings.weaponRestrictions != null) { this.settings.weaponRestrictions = newSettings.weaponRestrictions } if (newSettings.hltvEnabled != null) { this.settings.hltvEnabled = newSettings.hltvEnabled } if (newSettings.mapCycleType != null) { this.settings.mapCycleType = newSettings.mapCycleType } if (newSettings.multiMaps != null) { this.settings.multiMaps = newSettings.multiMaps } // which flag enabled this? /* if (newSettings.nextMapEnabled != null) { this.settings.nextMapEnabled = newSettings.nextMapEnabled }*/ if (newSettings.botEnabled != null) { this.updateBotEnabled( newSettings.botEnabled, newSettings.botDifficulty, newSettings.numCtBots, newSettings.numTrBots ) } if (newSettings.unk00 != null) { this.settings.unk00 = newSettings.unk00 } if (newSettings.unk01 != null) { this.settings.unk01 = newSettings.unk01 } if (newSettings.unk02 != null) { this.settings.unk02 = newSettings.unk02 } if (newSettings.unk03 != null) { this.settings.unk03 = newSettings.unk03 } if (newSettings.unk10 != null) { this.settings.unk10 = newSettings.unk10 } if (newSettings.unk13 != null) { this.settings.unk13 = newSettings.unk13 } if (newSettings.unk17 != null) { this.settings.unk17 = newSettings.unk17 } if (newSettings.unk18 != null) { this.settings.unk18 = newSettings.unk18 } if (newSettings.status != null) { this.settings.status = newSettings.status } if (newSettings.unk21 != null) { this.settings.unk21 = newSettings.unk21 } if (newSettings.unk23 != null) { this.settings.unk23 = newSettings.unk23 } if (newSettings.unk24 != null) { this.settings.unk24 = newSettings.unk24 } if (newSettings.unk25 != null) { this.settings.unk25 = newSettings.unk25 } if (newSettings.unk29 != null) { this.settings.unk29 = newSettings.unk29 } if (newSettings.unk30 != null) { this.settings.unk30 = newSettings.unk30 } if (newSettings.unk31 != null) { this.settings.unk31 = newSettings.unk31 } if (newSettings.unk32 != null) { this.settings.unk32 = newSettings.unk32 } if (newSettings.unk33 != null) { this.settings.unk33 = newSettings.unk33 } if (newSettings.unk35 != null) { this.settings.unk35 = newSettings.unk35 } if (newSettings.unk36 != null) { this.settings.unk36 = newSettings.unk36 } if (newSettings.unk37 != null) { this.settings.unk37 = newSettings.unk37 } if (newSettings.unk38 != null) { this.settings.unk38 = newSettings.unk38 } if (newSettings.unk39 != null) { this.settings.unk39 = newSettings.unk39 } if (newSettings.isIngame != null) { this.settings.isIngame = newSettings.isIngame } if (newSettings.unk43 != null) { this.settings.unk43 = newSettings.unk43 } if (newSettings.difficulty != null) { this.settings.difficulty = newSettings.difficulty } // inform every user in the room of the changes this.broadcastNewRoomSettings() } public onPlayerKilled(damageInfo: CSO2TakeDamageInfo): void { console.debug(this.GetDebugKillMessage(damageInfo)) this.HandlePlayerKilled(damageInfo) this.HandlePlayerDeath(damageInfo) } public onUserAssisted(userId: number, assists: number): void { const user = this.getRoomUser(userId) user.assists += assists } public onRoundWon(winningTeam: CSTeamNum): void { this.ingameMatchProgress.ScoreTeam(winningTeam) console.debug( this.ingameMatchProgress.GetDebugRoundEndMessage(winningTeam) ) } /** * send to the user the room's settings * @param user the target user */ public sendRoomSettingsTo(userId: number): void { const user: RoomUserEntry = this.getRoomUser(userId) user.conn.send(OutRoomPacket.updateSettings(this.settings)) } public sendUpdateRoomSettingsTo( user: RoomUserEntry, updatedSettings: RoomSettings ): void { user.conn.send(OutRoomPacket.updateSettings(updatedSettings)) } /** * tell the user about a new user in the room * @param user the player to send the other player's ready status * @param newUser the player whose ready status will be sent */ public sendNewUserTo(user: RoomUserEntry, newUser: RoomUserEntry): void { const team: CSTeamNum = newUser.team if (team == null) { console.warn( 'sendNewUserTo: couldnt get user team (userId: %i room "%s" room id %i)', user.userId, this.settings.roomName, this.id ) return null } user.conn.send(OutRoomPacket.playerJoin(newUser, team)) } /** * send a new player's ready status to everyone * also sends everyone's ready status to the new player * @param userId the new player's user ID */ public updateNewPlayerReadyStatus(userId: number): void { const target: RoomUserEntry = this.getRoomUser(userId) this.recurseUsers((u: RoomUserEntry): void => { // send everyone's status to the new user this.sendUserReadyStatusTo(target, u) if (u !== target) { // tell other room members about the new addition this.sendNewUserTo(u, target) this.sendUserReadyStatusTo(u, target) } }) } public hostGameStart(): void { this.stopCountdown() this.setStatus(RoomStatus.Ingame) this.setUserIngame(this.host, true) this.recurseNonHostUsers((u: RoomUserEntry): void => { this.sendRoomStatusTo(u) if (u.isReady()) { this.setUserIngame(u, true) this.sendConnectHostTo(u, this.host) this.sendGuestDataTo(this.host, u) } }) this.sendBroadcastReadyStatus() this.sendStartMatchTo(this.host) } public guestGameJoin(guestUserId: number): void { const guest: RoomUserEntry = this.getRoomUser(guestUserId) this.sendRoomStatusTo(guest) this.setUserIngame(guest, true) this.sendConnectHostTo(guest, this.host) this.sendGuestDataTo(this.host, guest) this.sendBroadcastReadyStatus() } /** * send an user's updated ready status to everyone else * @param sourceUserId the user ID of the player who updated their ready status */ public broadcastNewUserReadyStatus(sourceUserId: number): void { const sourceUser: RoomUserEntry = this.getRoomUser(sourceUserId) this.recurseUsers((u: RoomUserEntry): void => { this.sendUserReadyStatusTo(u, sourceUser) }) } /** * sends updated room settings to everyone in it */ public broadcastNewRoomSettings(): void { this.recurseUsers((u: RoomUserEntry): void => { this.sendUpdateRoomSettingsTo(u, this.settings) }) } /** * sends everyone a new user's team number * @param sourceUserId the user whose team number changed * @param newTeamNum the new team number */ public broadcastNewUserTeamNum( sourceUserId: number, newTeamNum: CSTeamNum ): void { const sourceUser: RoomUserEntry = this.getRoomUser(sourceUserId) this.recurseUsers((u: RoomUserEntry): void => { this.sendTeamChangeTo(u, sourceUser, newTeamNum) if (this.settings.areBotsEnabled) { u.team = newTeamNum this.sendTeamChangeGlobal(u, newTeamNum) } }) } /** * sends everyone in the room the room's countdown * @param shouldCountdown should the countdown continue? */ public broadcastCountdown(shouldCountdown: boolean): void { this.recurseUsers((u: RoomUserEntry): void => { this.sendCountdownTo(u, shouldCountdown) }) } /** * send an user's ready status to another user * @param user the player to send the other player's ready status * @param player the player whose ready status will be sent */ public sendUserReadyStatusTo( user: RoomUserEntry, player: RoomUserEntry ): void { const ready: RoomReadyStatus = player.ready if (ready == null) { console.warn( 'sendUserReadyStatusTo: couldnt get user status (userId: %i room "%s" room id %i)', user.userId, this.settings.roomName, this.id ) return null } user.conn.send(OutRoomPacket.setUserReadyStatus(player.userId, ready)) } /** * send everyone's ready status to an user * @param targetUser the user to send the info to */ public sendRoomUsersReadyStatusTo(targetUser: RoomUserEntry): void { this.recurseUsers((u: RoomUserEntry): void => { this.sendUserReadyStatusTo(targetUser, u) }) } /** * send everyone everyone's ready status */ public sendBroadcastReadyStatus(): void { this.recurseUsers((u: RoomUserEntry): void => { this.sendRoomUsersReadyStatusTo(u) }) } /** * tell the user to connect to a host * @param user the user that will connect to the host * @param host the host to connect to */ public sendConnectHostTo(user: RoomUserEntry, host: RoomUserEntry): void { const hostSession = host.conn.session if (hostSession == null) { return } user.conn.send( new OutUdpPacket( true, host.userId, hostSession.externalNet.ipAddress, hostSession.externalNet.serverPort ) ) user.conn.send(OutHostPacket.joinHost(host.userId)) } /** * send the host the guest that will connect to it * @param host the user hosting the match * @param guest the guest player joining the host's match */ public sendGuestDataTo(host: RoomUserEntry, guest: RoomUserEntry): void { const guestSession: UserSession = guest.conn.session if (guestSession == null) { return } host.conn.send( new OutUdpPacket( false, guest.userId, guestSession.externalNet.ipAddress, guestSession.externalNet.clientPort ) ) } /** * tell the host to start the game match * @param host the game match's host */ public sendStartMatchTo(host: RoomUserEntry): void { host.conn.send(OutHostPacket.gameStart(host.userId)) } /** * send a new player's team to an user * @param user the target user * @param player the user who changed its team * @param newTeamNum the player's new team number */ public sendTeamChangeTo( user: RoomUserEntry, player: RoomUserEntry, newTeamNum: CSTeamNum ): void { user.conn.send(OutRoomPacket.setUserTeam(player.userId, newTeamNum)) } /** * send a new player's team to everyone in the room * @param player the user who changed its team * @param newTeamNum the player's new team number */ public sendTeamChangeGlobal( player: RoomUserEntry, newTeamNum: CSTeamNum ): void { this.recurseUsers((u: RoomUserEntry) => { this.sendTeamChangeTo(u, player, newTeamNum) }) } /** * sends the global countdown number or stops it to the user * @param user the user to send the countdown to * @param shouldCountdown should the countdown continue */ public sendCountdownTo( user: RoomUserEntry, shouldCountdown: boolean ): void { user.conn.send( shouldCountdown ? OutRoomPacket.progressCountdown(this.getCountdown()) : OutRoomPacket.stopCountdown() ) } /** * ends a room's match and sends the players to the result window */ public sendGameEnd(user: RoomUserEntry): void { // TODO: set game end to ingame users only user.conn.send(OutHostPacket.hostStop()) user.conn.send(OutRoomPacket.setGameResult()) } /** * send an user its current room's status * @param user the target user */ public sendRoomStatusTo(user: RoomUserEntry): void { const settings: RoomSettings = new RoomSettings() settings.status = this.settings.status settings.isIngame = this.settings.isIngame user.conn.send(OutRoomPacket.updateSettings(settings)) } /** * handle max players setting's update event * @param newMaxPlayers the requested new max players number */ private updateMaxPlayers(newMaxPlayers: number): void { // reset bot number to 4 for each team when max players is changed // and the old max players value is bigger than the new one // this stops overflowing the max player number (where bots are included) if (this.settings.maxPlayers > newMaxPlayers) { if (this.settings.areBotsEnabled) { this.settings.numCtBots = this.settings.numTrBots = 4 } } this.settings.maxPlayers = newMaxPlayers } /** * handle bot enabled setting's update event * @param newMaxPlayers should enable the bots? */ private updateBotEnabled( botEnabled: number, botDifficulty: number, ctBots: number, terBots: number ): void { this.settings.areBotsEnabled = !!botEnabled if (this.settings.areBotsEnabled) { this.settings.botDifficulty = botDifficulty this.settings.numCtBots = ctBots this.settings.numTrBots = terBots // // set everyone to the host's team if bot mode is enabled // const hostTeamNum: CSTeamNum = this.host.team this.recurseNonHostUsers((u: RoomUserEntry): void => { const curUserTeamNum: CSTeamNum = this.getUserTeam(u.userId) if (curUserTeamNum !== hostTeamNum) { u.team = hostTeamNum // tell everyone the new user's team this.sendTeamChangeGlobal(u, hostTeamNum) } }) } else { this.settings.botDifficulty = 0 this.settings.numCtBots = 0 this.settings.numTrBots = 0 } } /** * called when an user is succesfully removed * if the room is empty, inform the channel to delete us * else, find a new host * @param userId the target user's id */ private onUserRemoved(userId: number): void { if (this.usersInfo.length !== 0) { this.sendRemovedUser(userId) // if the host leaves, assign someone else as the new host if (userId === this.host.userId) { this.findAndUpdateNewHost() } } else { this.emptyRoomCallback(this, this.parentChannel) } } /** * inform the users about an user being removed * @param deletedUserId the removed user's ID */ private sendRemovedUser(deletedUserId: number) { for (const info of this.usersInfo) { info.conn.send(OutRoomPacket.playerLeave(deletedUserId)) } } /** * sets the new room host and tells the users about it * @param newHost the new host user */ private updateHost(newHost: RoomUserEntry): void { this.host = newHost for (const user of this.usersInfo) { user.conn.send(OutRoomPacket.setHost(this.host.userId)) } } /** * assign the first available user as a host, * and updates the users about it * only if the room isn't empty * @returns true if a new host was found, false if not */ private findAndUpdateNewHost(): boolean { if (this.usersInfo.length === 0) { return false } this.updateHost(this.usersInfo[0]) return true } private GetDebugKillMessage(damageInfo: CSO2TakeDamageInfo): string { let attackerName = null let victimName = null const attackerConn = ActiveConnections.Singleton().FindByOwnerId( damageInfo.attacker.userId ) const victimConn = ActiveConnections.Singleton().FindByOwnerId( damageInfo.victim.userId ) if (attackerConn != null) { attackerName = attackerConn.session.user.playername } if (victimConn != null) { victimName = victimConn.session.user.playername } return `${attackerName} killed ${victimName} with ${ damageInfo.attacker.weaponId } (killFlags: ${damageInfo.killFlags.toString(16)})` } private HandlePlayerKilled(damageInfo: CSO2TakeDamageInfo): void { if (damageInfo.attacker.userId === 0) { // this means the attacker is a bot return } const attackerConn = ActiveConnections.Singleton().FindByOwnerId( damageInfo.attacker.userId ) if (attackerConn == null) { console.warn('Could not get the connection of the attacker') return } if (attackerConn.session.currentRoom !== this) { console.warn('The attacker is not on the same room as the host') return } const attackerEntry = this.getRoomUser(damageInfo.attacker.userId) attackerEntry.kills++ if (damageInfo.killFlags & TDIKillFlags.KilledByHeadshot) { attackerEntry.headshots++ } } private HandlePlayerDeath(damageInfo: CSO2TakeDamageInfo): void { if (damageInfo.victim.userId === 0) { // this means the victim is a bot return } const victimConn = ActiveConnections.Singleton().FindByOwnerId( damageInfo.victim.userId ) if (victimConn == null) { console.warn('Could not get the connection of the victim') return } if (victimConn.session.currentRoom !== this) { console.warn('The victim is not on the same room as the host') return } const roomUser = this.getRoomUser(damageInfo.victim.userId) roomUser.deaths++ } private async RewardUsers(): Promise<void> { const updatePromises = [] const winnerTeam = this.ingameMatchProgress.GetWinningTeam() for (const userInfo of this.usersInfo) { const userConn = userInfo.conn if (userConn == null) { console.warn( `RewardUsers: user's connection with id ${userInfo.userId} is null` ) continue } const user = userConn.session.user if (user == null) { console.warn( `RewardUsers: got user's ${userInfo.userId} connection but not the data?` ) continue } user.kills += userInfo.kills user.headshots += userInfo.headshots user.deaths += userInfo.deaths user.assists += userInfo.assists user.played_matches++ if (userInfo.team === winnerTeam) { user.wins++ } updatePromises.push( UserService.UpdatePartial( { kills: user.kills, headshots: user.headshots, deaths: user.deaths, assists: user.assists, played_matches: user.played_matches, wins: user.wins }, user.id ) ) userConn.send(OutUserInfoPacket.updateGameStats(user)) } const updateRes = await Promise.all(updatePromises) for (const res of updateRes) { if (res === false) { console.warn('RewardUsers: failed to update an user') } } } }
the_stack
import { browser } from '$app/env'; import * as Types from '$lib/graphql/_kitql/graphqlTypes'; import { defaultStoreValue, RequestStatus, ResponseResultType, type PatchType, type RequestParameters, type RequestQueryParameters, type RequestResult } from '@kitql/client'; import { get, writable } from 'svelte/store'; import { kitQLClient } from '../kitQLClient'; /** * Init KitQL (to have clientStarted = true!) * * Waiting for: https://github.com/sveltejs/kit/issues/4447 */ export function KQL__Init() {} /* Internal. To skip await on a client side navigation in the load function (from queryLoad)! */ let clientStarted = false; // Will be true on a client side navigation if (browser) { addEventListener('sveltekit:start', () => { clientStarted = true; }); } /** * ResetAllCaches in One function! */ export function KQL__ResetAllCaches() { KQL_Initialize.resetCache(); KQL_Issue.resetCache(); KQL_Issues.resetCache(); KQL_Milestones.resetCache(); } /* Operations 👇 */ function KQL_AddCommentStore() { const operationName = 'KQL_AddComment'; const operationType = ResponseResultType.Mutation; // prettier-ignore const { subscribe, set, update } = writable<RequestResult<Types.AddCommentMutation, Types.AddCommentMutationVariables>>({...defaultStoreValue, operationName, operationType}); async function mutateLocal( params?: RequestParameters<Types.AddCommentMutationVariables> ): Promise<RequestResult<Types.AddCommentMutation, Types.AddCommentMutationVariables>> { let { fetch, variables } = params ?? {}; const storedVariables = get(KQL_AddComment).variables; variables = variables ?? storedVariables; update((c) => { return { ...c, isFetching: true, status: RequestStatus.LOADING }; }); // prettier-ignore const res = await kitQLClient.request<Types.AddCommentMutation, Types.AddCommentMutationVariables>({ skFetch: fetch, document: Types.AddCommentDocument, variables, operationName, operationType, browser }); const result = { ...res, isFetching: false, status: RequestStatus.DONE, variables }; set(result); return result; } return { subscribe, /** * Can be used for SSR, but simpler option is `.queryLoad` * @returns fill this store & the cache */ mutate: mutateLocal, }; } /** * KitQL Svelte Store with the latest `AddComment` Operation */ export const KQL_AddComment = KQL_AddCommentStore(); function KQL_AddReactionStore() { const operationName = 'KQL_AddReaction'; const operationType = ResponseResultType.Mutation; // prettier-ignore const { subscribe, set, update } = writable<RequestResult<Types.AddReactionMutation, Types.AddReactionMutationVariables>>({...defaultStoreValue, operationName, operationType}); async function mutateLocal( params?: RequestParameters<Types.AddReactionMutationVariables> ): Promise<RequestResult<Types.AddReactionMutation, Types.AddReactionMutationVariables>> { let { fetch, variables } = params ?? {}; const storedVariables = get(KQL_AddReaction).variables; variables = variables ?? storedVariables; update((c) => { return { ...c, isFetching: true, status: RequestStatus.LOADING }; }); // prettier-ignore const res = await kitQLClient.request<Types.AddReactionMutation, Types.AddReactionMutationVariables>({ skFetch: fetch, document: Types.AddReactionDocument, variables, operationName, operationType, browser }); const result = { ...res, isFetching: false, status: RequestStatus.DONE, variables }; set(result); return result; } return { subscribe, /** * Can be used for SSR, but simpler option is `.queryLoad` * @returns fill this store & the cache */ mutate: mutateLocal, }; } /** * KitQL Svelte Store with the latest `AddReaction` Operation */ export const KQL_AddReaction = KQL_AddReactionStore(); function KQL_CreateIssueStore() { const operationName = 'KQL_CreateIssue'; const operationType = ResponseResultType.Mutation; // prettier-ignore const { subscribe, set, update } = writable<RequestResult<Types.CreateIssueMutation, Types.CreateIssueMutationVariables>>({...defaultStoreValue, operationName, operationType}); async function mutateLocal( params?: RequestParameters<Types.CreateIssueMutationVariables> ): Promise<RequestResult<Types.CreateIssueMutation, Types.CreateIssueMutationVariables>> { let { fetch, variables } = params ?? {}; const storedVariables = get(KQL_CreateIssue).variables; variables = variables ?? storedVariables; update((c) => { return { ...c, isFetching: true, status: RequestStatus.LOADING }; }); // prettier-ignore const res = await kitQLClient.request<Types.CreateIssueMutation, Types.CreateIssueMutationVariables>({ skFetch: fetch, document: Types.CreateIssueDocument, variables, operationName, operationType, browser }); const result = { ...res, isFetching: false, status: RequestStatus.DONE, variables }; set(result); return result; } return { subscribe, /** * Can be used for SSR, but simpler option is `.queryLoad` * @returns fill this store & the cache */ mutate: mutateLocal, }; } /** * KitQL Svelte Store with the latest `CreateIssue` Operation */ export const KQL_CreateIssue = KQL_CreateIssueStore(); function KQL_InitializeStore() { const operationName = 'KQL_Initialize'; const operationType = ResponseResultType.Query; // prettier-ignore const { subscribe, set, update } = writable<RequestResult<Types.InitializeQuery, Types.InitializeQueryVariables>>({...defaultStoreValue, operationName, operationType}); async function queryLocal( params?: RequestQueryParameters<Types.InitializeQueryVariables> ): Promise<RequestResult<Types.InitializeQuery, Types.InitializeQueryVariables>> { let { fetch, variables, settings } = params ?? {}; let { cacheMs, policy } = settings ?? {}; const storedVariables = get(KQL_Initialize).variables; variables = variables ?? storedVariables; policy = policy ?? kitQLClient.policy; // Cache only in the browser for now. In SSR, we will need session identif to not mix peoples data if (browser) { if (policy !== 'network-only') { // prettier-ignore const cachedData = kitQLClient.requestCache<Types.InitializeQuery, Types.InitializeQueryVariables>({ variables, operationName, cacheMs, browser }); if (cachedData) { const result = { ...cachedData, isFetching: false, status: RequestStatus.DONE }; if (policy === 'cache-first') { set(result); if (!result.isOutdated) { return result; } } else if (policy === 'cache-only') { set(result); return result; } else if (policy === 'cache-and-network') { set(result); } } } } update((c) => { return { ...c, isFetching: true, status: RequestStatus.LOADING }; }); // prettier-ignore const res = await kitQLClient.request<Types.InitializeQuery, Types.InitializeQueryVariables>({ skFetch: fetch, document: Types.InitializeDocument, variables, operationName, operationType, browser }); const result = { ...res, isFetching: false, status: RequestStatus.DONE, variables }; set(result); return result; } return { subscribe, /** * Can be used for SSR, but simpler option is `.queryLoad` * @returns fill this store & the cache */ query: queryLocal, /** * Ideal for SSR query. To be used in SvelteKit load function * @returns fill this store & the cache */ queryLoad: async ( params?: RequestQueryParameters<Types.InitializeQueryVariables> ): Promise<void> => { if (clientStarted) { queryLocal(params); // No await in purpose, we are in a client navigation. } else { await queryLocal(params); } }, /** * Reset Cache */ resetCache( variables: Types.InitializeQueryVariables | null = null, allOperationKey: boolean = true, withResetStore: boolean = true ) { kitQLClient.cacheRemove(operationName, { variables, allOperationKey }); if (withResetStore) { set({ ...defaultStoreValue, operationName }); } }, /** * Patch the store &&|| cache with some data. */ // prettier-ignore patch(data: Types.InitializeQuery, variables: Types.InitializeQueryVariables | null = null, type: PatchType = 'cache-and-store'): void { let updatedCacheStore = undefined; if(type === 'cache-only' || type === 'cache-and-store') { updatedCacheStore = kitQLClient.cacheUpdate<Types.InitializeQuery, Types.InitializeQueryVariables>(operationName, data, { variables }); } if(type === 'store-only' ) { let toReturn = { ...get(KQL_Initialize), data, variables } ; set(toReturn); } if(type === 'cache-and-store' ) { set({...get(KQL_Initialize), ...updatedCacheStore}); } kitQLClient.logInfo(operationName, "patch", type); } }; } /** * KitQL Svelte Store with the latest `Initialize` Operation */ export const KQL_Initialize = KQL_InitializeStore(); function KQL_IssueStore() { const operationName = 'KQL_Issue'; const operationType = ResponseResultType.Query; // prettier-ignore const { subscribe, set, update } = writable<RequestResult<Types.IssueQuery, Types.IssueQueryVariables>>({...defaultStoreValue, operationName, operationType}); async function queryLocal( params?: RequestQueryParameters<Types.IssueQueryVariables> ): Promise<RequestResult<Types.IssueQuery, Types.IssueQueryVariables>> { let { fetch, variables, settings } = params ?? {}; let { cacheMs, policy } = settings ?? {}; const storedVariables = get(KQL_Issue).variables; variables = variables ?? storedVariables; policy = policy ?? kitQLClient.policy; // Cache only in the browser for now. In SSR, we will need session identif to not mix peoples data if (browser) { if (policy !== 'network-only') { // prettier-ignore const cachedData = kitQLClient.requestCache<Types.IssueQuery, Types.IssueQueryVariables>({ variables, operationName, cacheMs, browser }); if (cachedData) { const result = { ...cachedData, isFetching: false, status: RequestStatus.DONE }; if (policy === 'cache-first') { set(result); if (!result.isOutdated) { return result; } } else if (policy === 'cache-only') { set(result); return result; } else if (policy === 'cache-and-network') { set(result); } } } } update((c) => { return { ...c, isFetching: true, status: RequestStatus.LOADING }; }); // prettier-ignore const res = await kitQLClient.request<Types.IssueQuery, Types.IssueQueryVariables>({ skFetch: fetch, document: Types.IssueDocument, variables, operationName, operationType, browser }); const result = { ...res, isFetching: false, status: RequestStatus.DONE, variables }; set(result); return result; } return { subscribe, /** * Can be used for SSR, but simpler option is `.queryLoad` * @returns fill this store & the cache */ query: queryLocal, /** * Ideal for SSR query. To be used in SvelteKit load function * @returns fill this store & the cache */ queryLoad: async ( params?: RequestQueryParameters<Types.IssueQueryVariables> ): Promise<void> => { if (clientStarted) { queryLocal(params); // No await in purpose, we are in a client navigation. } else { await queryLocal(params); } }, /** * Reset Cache */ resetCache( variables: Types.IssueQueryVariables | null = null, allOperationKey: boolean = true, withResetStore: boolean = true ) { kitQLClient.cacheRemove(operationName, { variables, allOperationKey }); if (withResetStore) { set({ ...defaultStoreValue, operationName }); } }, /** * Patch the store &&|| cache with some data. */ // prettier-ignore patch(data: Types.IssueQuery, variables: Types.IssueQueryVariables | null = null, type: PatchType = 'cache-and-store'): void { let updatedCacheStore = undefined; if(type === 'cache-only' || type === 'cache-and-store') { updatedCacheStore = kitQLClient.cacheUpdate<Types.IssueQuery, Types.IssueQueryVariables>(operationName, data, { variables }); } if(type === 'store-only' ) { let toReturn = { ...get(KQL_Issue), data, variables } ; set(toReturn); } if(type === 'cache-and-store' ) { set({...get(KQL_Issue), ...updatedCacheStore}); } kitQLClient.logInfo(operationName, "patch", type); } }; } /** * KitQL Svelte Store with the latest `Issue` Operation */ export const KQL_Issue = KQL_IssueStore(); function KQL_IssuesStore() { const operationName = 'KQL_Issues'; const operationType = ResponseResultType.Query; // prettier-ignore const { subscribe, set, update } = writable<RequestResult<Types.IssuesQuery, Types.IssuesQueryVariables>>({...defaultStoreValue, operationName, operationType}); async function queryLocal( params?: RequestQueryParameters<Types.IssuesQueryVariables> ): Promise<RequestResult<Types.IssuesQuery, Types.IssuesQueryVariables>> { let { fetch, variables, settings } = params ?? {}; let { cacheMs, policy } = settings ?? {}; const storedVariables = get(KQL_Issues).variables; variables = variables ?? storedVariables; policy = policy ?? kitQLClient.policy; // Cache only in the browser for now. In SSR, we will need session identif to not mix peoples data if (browser) { if (policy !== 'network-only') { // prettier-ignore const cachedData = kitQLClient.requestCache<Types.IssuesQuery, Types.IssuesQueryVariables>({ variables, operationName, cacheMs, browser }); if (cachedData) { const result = { ...cachedData, isFetching: false, status: RequestStatus.DONE }; if (policy === 'cache-first') { set(result); if (!result.isOutdated) { return result; } } else if (policy === 'cache-only') { set(result); return result; } else if (policy === 'cache-and-network') { set(result); } } } } update((c) => { return { ...c, isFetching: true, status: RequestStatus.LOADING }; }); // prettier-ignore const res = await kitQLClient.request<Types.IssuesQuery, Types.IssuesQueryVariables>({ skFetch: fetch, document: Types.IssuesDocument, variables, operationName, operationType, browser }); const result = { ...res, isFetching: false, status: RequestStatus.DONE, variables }; set(result); return result; } return { subscribe, /** * Can be used for SSR, but simpler option is `.queryLoad` * @returns fill this store & the cache */ query: queryLocal, /** * Ideal for SSR query. To be used in SvelteKit load function * @returns fill this store & the cache */ queryLoad: async ( params?: RequestQueryParameters<Types.IssuesQueryVariables> ): Promise<void> => { if (clientStarted) { queryLocal(params); // No await in purpose, we are in a client navigation. } else { await queryLocal(params); } }, /** * Reset Cache */ resetCache( variables: Types.IssuesQueryVariables | null = null, allOperationKey: boolean = true, withResetStore: boolean = true ) { kitQLClient.cacheRemove(operationName, { variables, allOperationKey }); if (withResetStore) { set({ ...defaultStoreValue, operationName }); } }, /** * Patch the store &&|| cache with some data. */ // prettier-ignore patch(data: Types.IssuesQuery, variables: Types.IssuesQueryVariables | null = null, type: PatchType = 'cache-and-store'): void { let updatedCacheStore = undefined; if(type === 'cache-only' || type === 'cache-and-store') { updatedCacheStore = kitQLClient.cacheUpdate<Types.IssuesQuery, Types.IssuesQueryVariables>(operationName, data, { variables }); } if(type === 'store-only' ) { let toReturn = { ...get(KQL_Issues), data, variables } ; set(toReturn); } if(type === 'cache-and-store' ) { set({...get(KQL_Issues), ...updatedCacheStore}); } kitQLClient.logInfo(operationName, "patch", type); } }; } /** * KitQL Svelte Store with the latest `Issues` Operation */ export const KQL_Issues = KQL_IssuesStore(); function KQL_MilestonesStore() { const operationName = 'KQL_Milestones'; const operationType = ResponseResultType.Query; // prettier-ignore const { subscribe, set, update } = writable<RequestResult<Types.MilestonesQuery, Types.MilestonesQueryVariables>>({...defaultStoreValue, operationName, operationType}); async function queryLocal( params?: RequestQueryParameters<Types.MilestonesQueryVariables> ): Promise<RequestResult<Types.MilestonesQuery, Types.MilestonesQueryVariables>> { let { fetch, variables, settings } = params ?? {}; let { cacheMs, policy } = settings ?? {}; const storedVariables = get(KQL_Milestones).variables; variables = variables ?? storedVariables; policy = policy ?? kitQLClient.policy; // Cache only in the browser for now. In SSR, we will need session identif to not mix peoples data if (browser) { if (policy !== 'network-only') { // prettier-ignore const cachedData = kitQLClient.requestCache<Types.MilestonesQuery, Types.MilestonesQueryVariables>({ variables, operationName, cacheMs, browser }); if (cachedData) { const result = { ...cachedData, isFetching: false, status: RequestStatus.DONE }; if (policy === 'cache-first') { set(result); if (!result.isOutdated) { return result; } } else if (policy === 'cache-only') { set(result); return result; } else if (policy === 'cache-and-network') { set(result); } } } } update((c) => { return { ...c, isFetching: true, status: RequestStatus.LOADING }; }); // prettier-ignore const res = await kitQLClient.request<Types.MilestonesQuery, Types.MilestonesQueryVariables>({ skFetch: fetch, document: Types.MilestonesDocument, variables, operationName, operationType, browser }); const result = { ...res, isFetching: false, status: RequestStatus.DONE, variables }; set(result); return result; } return { subscribe, /** * Can be used for SSR, but simpler option is `.queryLoad` * @returns fill this store & the cache */ query: queryLocal, /** * Ideal for SSR query. To be used in SvelteKit load function * @returns fill this store & the cache */ queryLoad: async ( params?: RequestQueryParameters<Types.MilestonesQueryVariables> ): Promise<void> => { if (clientStarted) { queryLocal(params); // No await in purpose, we are in a client navigation. } else { await queryLocal(params); } }, /** * Reset Cache */ resetCache( variables: Types.MilestonesQueryVariables | null = null, allOperationKey: boolean = true, withResetStore: boolean = true ) { kitQLClient.cacheRemove(operationName, { variables, allOperationKey }); if (withResetStore) { set({ ...defaultStoreValue, operationName }); } }, /** * Patch the store &&|| cache with some data. */ // prettier-ignore patch(data: Types.MilestonesQuery, variables: Types.MilestonesQueryVariables | null = null, type: PatchType = 'cache-and-store'): void { let updatedCacheStore = undefined; if(type === 'cache-only' || type === 'cache-and-store') { updatedCacheStore = kitQLClient.cacheUpdate<Types.MilestonesQuery, Types.MilestonesQueryVariables>(operationName, data, { variables }); } if(type === 'store-only' ) { let toReturn = { ...get(KQL_Milestones), data, variables } ; set(toReturn); } if(type === 'cache-and-store' ) { set({...get(KQL_Milestones), ...updatedCacheStore}); } kitQLClient.logInfo(operationName, "patch", type); } }; } /** * KitQL Svelte Store with the latest `Milestones` Operation */ export const KQL_Milestones = KQL_MilestonesStore(); function KQL_MinimizeCommentStore() { const operationName = 'KQL_MinimizeComment'; const operationType = ResponseResultType.Mutation; // prettier-ignore const { subscribe, set, update } = writable<RequestResult<Types.MinimizeCommentMutation, Types.MinimizeCommentMutationVariables>>({...defaultStoreValue, operationName, operationType}); async function mutateLocal( params?: RequestParameters<Types.MinimizeCommentMutationVariables> ): Promise<RequestResult<Types.MinimizeCommentMutation, Types.MinimizeCommentMutationVariables>> { let { fetch, variables } = params ?? {}; const storedVariables = get(KQL_MinimizeComment).variables; variables = variables ?? storedVariables; update((c) => { return { ...c, isFetching: true, status: RequestStatus.LOADING }; }); // prettier-ignore const res = await kitQLClient.request<Types.MinimizeCommentMutation, Types.MinimizeCommentMutationVariables>({ skFetch: fetch, document: Types.MinimizeCommentDocument, variables, operationName, operationType, browser }); const result = { ...res, isFetching: false, status: RequestStatus.DONE, variables }; set(result); return result; } return { subscribe, /** * Can be used for SSR, but simpler option is `.queryLoad` * @returns fill this store & the cache */ mutate: mutateLocal, }; } /** * KitQL Svelte Store with the latest `MinimizeComment` Operation */ export const KQL_MinimizeComment = KQL_MinimizeCommentStore(); function KQL_UpdateIssueCommentStore() { const operationName = 'KQL_UpdateIssueComment'; const operationType = ResponseResultType.Mutation; // prettier-ignore const { subscribe, set, update } = writable<RequestResult<Types.UpdateIssueCommentMutation, Types.UpdateIssueCommentMutationVariables>>({...defaultStoreValue, operationName, operationType}); async function mutateLocal( params?: RequestParameters<Types.UpdateIssueCommentMutationVariables> ): Promise<RequestResult<Types.UpdateIssueCommentMutation, Types.UpdateIssueCommentMutationVariables>> { let { fetch, variables } = params ?? {}; const storedVariables = get(KQL_UpdateIssueComment).variables; variables = variables ?? storedVariables; update((c) => { return { ...c, isFetching: true, status: RequestStatus.LOADING }; }); // prettier-ignore const res = await kitQLClient.request<Types.UpdateIssueCommentMutation, Types.UpdateIssueCommentMutationVariables>({ skFetch: fetch, document: Types.UpdateIssueCommentDocument, variables, operationName, operationType, browser }); const result = { ...res, isFetching: false, status: RequestStatus.DONE, variables }; set(result); return result; } return { subscribe, /** * Can be used for SSR, but simpler option is `.queryLoad` * @returns fill this store & the cache */ mutate: mutateLocal, }; } /** * KitQL Svelte Store with the latest `UpdateIssueComment` Operation */ export const KQL_UpdateIssueComment = KQL_UpdateIssueCommentStore();
the_stack
import { IGraph, prepScopes, CacheItem, CacheService, CacheStore } from '@microsoft/mgt-element'; import { User } from '@microsoft/microsoft-graph-types'; import { findPeople, PersonType } from './graph.people'; import { schemas } from './cacheStores'; /** * Object to be stored in cache */ export interface CacheUser extends CacheItem { /** * stringified json representing a user */ user?: string; } /** * Object to be stored in cache */ export interface CacheUserQuery extends CacheItem { /** * max number of results the query asks for */ maxResults?: number; /** * list of users returned by query */ results?: string[]; } /** * Defines the time it takes for objects in the cache to expire */ export const getUserInvalidationTime = (): number => CacheService.config.users.invalidationPeriod || CacheService.config.defaultInvalidationPeriod; /** * Whether or not the cache is enabled */ export const getIsUsersCacheEnabled = (): boolean => CacheService.config.users.isEnabled && CacheService.config.isEnabled; /** * async promise, returns Graph User data relating to the user logged in * * @returns {(Promise<User>)} * @memberof Graph */ export async function getMe(graph: IGraph, requestedProps?: string[]): Promise<User> { let cache: CacheStore<CacheUser>; if (getIsUsersCacheEnabled()) { cache = CacheService.getCache<CacheUser>(schemas.users, schemas.users.stores.users); const me = await cache.getValue('me'); if (me && getUserInvalidationTime() > Date.now() - me.timeCached) { const cachedData = JSON.parse(me.user); const uniqueProps = requestedProps ? requestedProps.filter(prop => !Object.keys(cachedData).includes(prop)) : null; // if requestedProps doesn't contain any unique props other than "@odata.context" if (!uniqueProps || uniqueProps.length <= 1) { return cachedData; } } } let apiString = 'me'; if (requestedProps) { apiString = apiString + '?$select=' + requestedProps.toString(); } const response = graph.api(apiString).middlewareOptions(prepScopes('user.read')).get(); if (getIsUsersCacheEnabled()) { cache.putValue('me', { user: JSON.stringify(await response) }); } return response; } /** * async promise, returns all Graph users associated with the userPrincipleName provided * * @param {string} userPrincipleName * @returns {(Promise<User>)} * @memberof Graph */ export async function getUser(graph: IGraph, userPrincipleName: string, requestedProps?: string[]): Promise<User> { const scopes = 'user.readbasic.all'; let cache: CacheStore<CacheUser>; if (getIsUsersCacheEnabled()) { cache = CacheService.getCache<CacheUser>(schemas.users, schemas.users.stores.users); // check cache const user = await cache.getValue(userPrincipleName); // is it stored and is timestamp good? if (user && getUserInvalidationTime() > Date.now() - user.timeCached) { const cachedData = user.user ? JSON.parse(user.user) : null; const uniqueProps = requestedProps && cachedData ? requestedProps.filter(prop => !Object.keys(cachedData).includes(prop)) : null; // return without any worries if (!uniqueProps || uniqueProps.length <= 1) { return cachedData; } } } let apiString = `/users/${userPrincipleName}`; if (requestedProps) { apiString = apiString + '?$select=' + requestedProps.toString(); } // else we must grab it let response; try { response = await graph.api(apiString).middlewareOptions(prepScopes(scopes)).get(); } catch (_) {} if (getIsUsersCacheEnabled()) { cache.putValue(userPrincipleName, { user: JSON.stringify(response) }); } return response; } /** * Returns a Promise of Graph Users array associated with the user ids array * * @export * @param {IGraph} graph * @param {string[]} userIds, an array of string ids * @returns {Promise<User[]>} */ export async function getUsersForUserIds(graph: IGraph, userIds: string[], searchInput: string = ''): Promise<User[]> { if (!userIds || userIds.length === 0) { return []; } const batch = graph.createBatch(); const peopleDict = {}; const peopleSearchMatches = {}; const notInCache = []; searchInput = searchInput.toLowerCase(); let cache: CacheStore<CacheUser>; if (getIsUsersCacheEnabled()) { cache = CacheService.getCache<CacheUser>(schemas.users, schemas.users.stores.users); } for (const id of userIds) { peopleDict[id] = null; let user = null; if (getIsUsersCacheEnabled()) { user = await cache.getValue(id); } if (user && getUserInvalidationTime() > Date.now() - user.timeCached) { user = JSON.parse(user?.user); const displayName = user.displayName; const searchMatches = displayName && displayName.toLowerCase().includes(searchInput) ? true : false; if (searchInput && searchMatches) { peopleSearchMatches[id] = user ? user : null; } else { peopleDict[id] = user ? user : null; } } else if (id !== '') { if (id.toString() === 'me') { peopleDict[id] = await getMe(graph); } else { batch.get(id, `/users/${id}`, ['user.readbasic.all']); } } } try { const responses = await batch.executeAll(); // iterate over userIds to ensure the order of ids for (const id of userIds) { const response = responses.get(id); if (response && response.content) { const user = response.content; if (searchInput) { const displayName = user?.displayName.toLowerCase(); if (displayName.contains(searchInput)) { peopleSearchMatches[id] = user; } } else { peopleDict[id] = user; } if (getIsUsersCacheEnabled()) { cache.putValue(id, { user: JSON.stringify(user) }); } } } if (searchInput && Object.keys(peopleSearchMatches).length) { return Promise.all(Object.values(peopleSearchMatches)); } return Promise.all(Object.values(peopleDict)); } catch (_) { // fallback to making the request one by one try { // call getUser for all the users that weren't cached userIds.filter(id => notInCache.includes(id)).forEach(id => (peopleDict[id] = getUser(graph, id))); if (getIsUsersCacheEnabled()) { // store all users that weren't retrieved from the cache, into the cache userIds .filter(id => notInCache.includes(id)) .forEach(async id => cache.putValue(id, { user: JSON.stringify(await peopleDict[id]) })); } return Promise.all(Object.values(peopleDict)); } catch (_) { return []; } } } /** * Returns a Promise of Graph Users array associated with the people queries array * * @export * @param {IGraph} graph * @param {string[]} peopleQueries, an array of string ids * @returns {Promise<User[]>} */ export async function getUsersForPeopleQueries(graph: IGraph, peopleQueries: string[]): Promise<User[]> { if (!peopleQueries || peopleQueries.length === 0) { return []; } const batch = graph.createBatch(); const people = []; let cacheRes: CacheUserQuery; let cache: CacheStore<CacheUserQuery>; if (getIsUsersCacheEnabled()) { cache = CacheService.getCache<CacheUserQuery>(schemas.users, schemas.users.stores.usersQuery); } for (const personQuery of peopleQueries) { if (getIsUsersCacheEnabled()) { cacheRes = await cache.getValue(personQuery); } if (getIsUsersCacheEnabled() && cacheRes && getUserInvalidationTime() > Date.now() - cacheRes.timeCached) { people.push(JSON.parse(cacheRes.results[0])); } else if (personQuery !== '') { batch.get(personQuery, `/me/people?$search="${personQuery}"`, ['people.read']); } } try { const responses = await batch.executeAll(); for (const personQuery of peopleQueries) { const response = responses.get(personQuery); if (response && response.content && response.content.value && response.content.value.length > 0) { people.push(response.content.value[0]); if (getIsUsersCacheEnabled()) { cache.putValue(personQuery, { maxResults: 1, results: [JSON.stringify(response.content.value[0])] }); } } else { people.push(null); } } return people; } catch (_) { try { return Promise.all( peopleQueries .filter(personQuery => personQuery && personQuery !== '') .map(async personQuery => { const personArray = await findPeople(graph, personQuery, 1); if (personArray && personArray.length) { if (getIsUsersCacheEnabled()) { cache.putValue(personQuery, { maxResults: 1, results: [JSON.stringify(personArray[0])] }); } return personArray[0]; } }) ); } catch (_) { return []; } } } /** * Search Microsoft Graph for Users in the organization * * @export * @param {IGraph} graph * @param {string} query - the string to search for * @param {number} [top=10] - maximum number of results to return * @returns {Promise<User[]>} */ export async function findUsers(graph: IGraph, query: string, top: number = 10): Promise<User[]> { const scopes = 'User.ReadBasic.All'; const item = { maxResults: top, results: null }; let cache: CacheStore<CacheUserQuery>; if (getIsUsersCacheEnabled()) { cache = CacheService.getCache<CacheUserQuery>(schemas.users, schemas.users.stores.usersQuery); const result: CacheUserQuery = await cache.getValue(query); if (result && getUserInvalidationTime() > Date.now() - result.timeCached) { return result.results.map(userStr => JSON.parse(userStr)); } } let graphResult; let encodedQuery = `${query.replace(/#/g, '%2523')}`; try { graphResult = await graph .api('users') .header('ConsistencyLevel', 'eventual') .count(true) .search(`"displayName:${encodedQuery}" OR "mail:${encodedQuery}"`) .top(top) .middlewareOptions(prepScopes(scopes)) .get(); } catch {} if (getIsUsersCacheEnabled() && graphResult) { item.results = graphResult.value.map(userStr => JSON.stringify(userStr)); cache.putValue(query, item); } return graphResult ? graphResult.value : null; } /** * async promise, returns all matching Graph users who are member of the specified group * * @param {string} query * @param {string} groupId - the group to query * @param {number} [top=10] - number of people to return * @param {PersonType} [personType=PersonType.person] - the type of person to search for * @param {boolean} [transitive=false] - whether the return should contain a flat list of all nested members * @returns {(Promise<User[]>)} */ export async function findGroupMembers( graph: IGraph, query: string, groupId: string, top: number = 10, personType: PersonType = PersonType.person, transitive: boolean = false ): Promise<User[]> { const scopes = ['user.read.all', 'people.read']; const item = { maxResults: top, results: null }; let cache: CacheStore<CacheUserQuery>; const key = `${groupId || '*'}:${query || '*'}:${personType}:${transitive}`; if (getIsUsersCacheEnabled()) { cache = CacheService.getCache<CacheUserQuery>(schemas.users, schemas.users.stores.usersQuery); const result: CacheUserQuery = await cache.getValue(key); if (result && getUserInvalidationTime() > Date.now() - result.timeCached) { return result.results.map(userStr => JSON.parse(userStr)); } } let filter: string = ''; if (query) { filter = `startswith(displayName,'${query}') or startswith(givenName,'${query}') or startswith(surname,'${query}') or startswith(mail,'${query}') or startswith(userPrincipalName,'${query}')`; } let apiUrl: string = `/groups/${groupId}/${transitive ? 'transitiveMembers' : 'members'}`; if (personType === PersonType.person) { apiUrl += `/microsoft.graph.user`; } else if (personType === PersonType.group) { apiUrl += `/microsoft.graph.group`; if (query) { filter = `startswith(displayName,'${query}') or startswith(mail,'${query}')`; } } const graphResult = await graph .api(apiUrl) .count(true) .top(top) .filter(filter) .header('ConsistencyLevel', 'eventual') .middlewareOptions(prepScopes(...scopes)) .get(); if (getIsUsersCacheEnabled() && graphResult) { item.results = graphResult.value.map(userStr => JSON.stringify(userStr)); cache.putValue(key, item); } return graphResult ? graphResult.value : null; }
the_stack
import { useFruitManageHandler } from "../utils/useFruitManageHandler"; import { Fruit } from "./mocks/contentModels"; import { setupContentModelGroup, setupContentModels } from "../utils/setup"; import { useContentGqlHandler } from "../utils/useContentGqlHandler"; const appleData: Fruit = { name: "Apple", isSomething: false, rating: 400, numbers: [5, 6, 7.2, 10.18, 12.05], email: "john@doe.com", url: "https://apple.test", lowerCase: "apple", upperCase: "APPLE", date: "2020-12-15", dateTime: new Date("2020-12-15T12:12:21").toISOString(), dateTimeZ: "2020-12-15T14:52:41+01:00", time: "11:39:58", description: "fruit named apple cms" }; const strawberryData: Fruit = { name: "Strawberry", isSomething: true, rating: 500, numbers: [5, 6, 7.2, 10.18, 12.05], email: "john@doe.com", url: "https://strawberry.test", lowerCase: "strawberry", upperCase: "STRAWBERRY", date: "2020-12-18", dateTime: new Date("2020-12-19T12:12:21").toISOString(), dateTimeZ: "2020-12-25T14:52:41+01:00", time: "12:44:55", description: "strawberry named fruit webiny" }; const bananaData: Fruit = { name: "Banana", isSomething: false, rating: 450, numbers: [5, 6, 7.2, 10.18, 12.05], email: "john@doe.com", url: "https://banana.test", lowerCase: "banana", upperCase: "BANANA", date: "2020-12-03", dateTime: new Date("2020-12-03T12:12:21").toISOString(), dateTimeZ: "2020-12-03T14:52:41+01:00", time: "11:59:01", description: "fruit banana named cms webiny" }; type CmsEntry<T = Record<string, any>> = T & { name: string; meta: { status: string; modelId: string; }; }; interface FruitExpectancy { id: string; status: string; } describe("Content entries", () => { const manageOpts = { path: "manage/en-US" }; const mainManager = useContentGqlHandler(manageOpts); const { createFruit, publishFruit, listFruits, until, getContentEntries, getLatestContentEntries, getPublishedContentEntries, getContentEntry, getLatestContentEntry, getPublishedContentEntry, createFruitFrom, searchContentEntries } = useFruitManageHandler({ ...manageOpts }); const createAndPublishFruit = async (data: any): Promise<CmsEntry<Fruit>> => { const [response] = await createFruit({ data }); const createdFruit = response.data.createFruit.data; const [publish] = await publishFruit({ revision: createdFruit.id }); return publish.data.publishFruit.data; }; const createFruits = async () => { return { apple: await createAndPublishFruit(appleData), strawberry: await createAndPublishFruit(strawberryData), banana: await createAndPublishFruit(bananaData) }; }; const setupFruits = async () => { const group = await setupContentModelGroup(mainManager); await setupContentModels(mainManager, group, ["fruit"]); return createFruits(); }; const waitFruits = async (name: string, expectancy?: FruitExpectancy[]) => { // If this `until` resolves successfully, we know entry is accessible via the "read" API await until( () => listFruits({}).then(([data]) => data), ({ data }: any) => { const list: any[] = data.listFruits?.data || []; if (list.length !== 3) { return false; } if (!expectancy) { return true; } return expectancy.every(item => { return list.some(ls => { return ls.id === item.id && ls.meta.status === item.status; }); }); }, { name: `list all fruits - ${name}` } ); }; it("should get content entry by modelId and id", async () => { const { apple, banana, strawberry } = await setupFruits(); const [secondBananaResponse] = await createFruitFrom({ revision: banana.id }); expect(secondBananaResponse).toMatchObject({ data: { createFruitFrom: { data: { id: `${banana.entryId}#0002`, entryId: banana.entryId, meta: { version: 2, status: "draft" } }, error: null } } }); const secondBanana = secondBananaResponse.data.createFruitFrom.data; const [publishSecondBananaResponse] = await publishFruit({ revision: secondBanana.id }); expect(publishSecondBananaResponse).toMatchObject({ data: { publishFruit: { data: { id: secondBanana.id, entryId: banana.entryId, meta: { version: 2, status: "published" } } } } }); const [thirdBananaResponse] = await createFruitFrom({ revision: secondBanana.id }); expect(thirdBananaResponse).toMatchObject({ data: { createFruitFrom: { data: { id: (secondBanana.id || "").replace("0002", "0003"), entryId: banana.entryId, meta: { version: 3, status: "draft" } }, error: null } } }); const thirdBanana = thirdBananaResponse.data.createFruitFrom.data; await waitFruits("should filter fruits by date and sort asc", [ { id: apple.id, status: "published" }, { id: thirdBanana.id, status: "draft" }, { id: strawberry.id, status: "published" } ]); await new Promise(resolve => { setTimeout(resolve, 5000); }); /** * Exact entries queries. */ const [exactAppleResponse] = await getContentEntry({ entry: { id: apple.id, modelId: apple.meta.modelId } }); expect(exactAppleResponse).toEqual({ data: { getContentEntry: { data: { id: apple.id, entryId: apple.entryId, status: apple.meta.status, title: apple.name, model: { modelId: apple.meta.modelId, name: "Fruit" } }, error: null } } }); const [exactFruitsResponse] = await getContentEntries({ entries: [ { id: apple.id, modelId: apple.meta.modelId }, { id: banana.id, modelId: banana.meta.modelId }, { id: strawberry.id, modelId: strawberry.meta.modelId } ] }); expect(exactFruitsResponse).toEqual({ data: { getContentEntries: { data: [ { id: apple.id, entryId: apple.entryId, status: apple.meta.status, title: apple.name, model: { modelId: apple.meta.modelId, name: "Fruit" } }, { id: banana.id, entryId: banana.entryId, status: "unpublished", title: banana.name, model: { modelId: banana.meta.modelId, name: "Fruit" } }, { id: strawberry.id, entryId: strawberry.entryId, status: strawberry.meta.status, title: strawberry.name, model: { modelId: strawberry.meta.modelId, name: "Fruit" } } ], error: null } } }); /** * Latest entries queries. */ const [latestBananaResponse] = await getLatestContentEntry({ entry: { id: thirdBanana.id, modelId: thirdBanana.meta.modelId } }); expect(latestBananaResponse).toEqual({ data: { getLatestContentEntry: { data: { id: thirdBanana.id, entryId: thirdBanana.entryId, status: "draft", title: thirdBanana.name, model: { modelId: thirdBanana.meta.modelId, name: "Fruit" } }, error: null } } }); const [latestFruitsResponse] = await getLatestContentEntries({ entries: [ { id: apple.id, modelId: apple.meta.modelId }, { id: banana.id, modelId: banana.meta.modelId }, { id: strawberry.id, modelId: strawberry.meta.modelId } ] }); expect(latestFruitsResponse).toEqual({ data: { getLatestContentEntries: { data: [ { id: apple.id, entryId: apple.entryId, status: "published", title: apple.name, model: { modelId: apple.meta.modelId, name: "Fruit" } }, { id: thirdBanana.id, entryId: thirdBanana.entryId, status: "draft", title: thirdBanana.name, model: { modelId: thirdBanana.meta.modelId, name: "Fruit" } }, { id: strawberry.id, entryId: strawberry.entryId, status: "published", title: strawberry.name, model: { modelId: strawberry.meta.modelId, name: "Fruit" } } ], error: null } } }); /** * Published entries queries. */ const [publishedBananaResponse] = await getPublishedContentEntry({ entry: { id: thirdBanana.id, modelId: thirdBanana.meta.modelId } }); expect(publishedBananaResponse).toEqual({ data: { getPublishedContentEntry: { data: { id: secondBanana.id, entryId: secondBanana.entryId, status: "published", title: secondBanana.name, model: { modelId: secondBanana.meta.modelId, name: "Fruit" } }, error: null } } }); const [publishedFruitsResponse] = await getPublishedContentEntries({ entries: [ { id: apple.id, modelId: apple.meta.modelId }, { id: banana.id, modelId: banana.meta.modelId }, { id: strawberry.id, modelId: strawberry.meta.modelId } ] }); expect(publishedFruitsResponse).toEqual({ data: { getPublishedContentEntries: { data: [ { id: apple.id, entryId: apple.entryId, status: "published", title: apple.name, model: { modelId: apple.meta.modelId, name: "Fruit" } }, { id: secondBanana.id, entryId: secondBanana.entryId, status: "published", title: secondBanana.name, model: { modelId: secondBanana.meta.modelId, name: "Fruit" } }, { id: strawberry.id, entryId: strawberry.entryId, status: "published", title: strawberry.name, model: { modelId: strawberry.meta.modelId, name: "Fruit" } } ], error: null } } }); }); it("should search for latest entries in given models", async () => { const { apple, banana, strawberry } = await setupFruits(); const [secondBananaResponse] = await createFruitFrom({ revision: banana.id }); expect(secondBananaResponse).toMatchObject({ data: { createFruitFrom: { data: { id: `${banana.entryId}#0002`, entryId: banana.entryId, meta: { version: 2, status: "draft" } }, error: null } } }); const secondBanana = secondBananaResponse.data.createFruitFrom.data; await waitFruits("should be second banana as draft", [ { id: apple.id, status: "published" }, { id: secondBanana.id, status: "draft" }, { id: strawberry.id, status: "published" } ]); const [response] = await searchContentEntries({ modelsIds: ["fruit"] }); expect(response).toMatchObject({ data: { entries: { data: [ { id: secondBanana.id, entryId: secondBanana.entryId, title: secondBanana.name, status: secondBanana.meta.status, published: { id: banana.id, entryId: banana.entryId, title: banana.name } }, { id: strawberry.id, entryId: strawberry.entryId, title: strawberry.name, status: strawberry.meta.status, published: { id: strawberry.id, entryId: strawberry.entryId, title: strawberry.name } }, { id: apple.id, entryId: apple.entryId, title: apple.name, status: apple.meta.status, published: { id: apple.id, entryId: apple.entryId, title: apple.name } } ], error: null } } }); }); const searchQueries: [string, string[]][] = [ ["webiny", ["Banana", "Strawberry"]], ["cms", ["Banana", "Apple"]] ]; it.each(searchQueries)( `should search for latest entries containing "%s" in given models`, async (query, titles) => { const { apple, banana, strawberry } = await setupFruits(); await waitFruits("should be second banana as draft", [ { id: apple.id as string, status: "published" }, { id: banana.id as string, status: "published" }, { id: strawberry.id as string, status: "published" } ]); const [response] = await searchContentEntries({ modelsIds: ["fruit"], query }); expect(response).toMatchObject({ data: { entries: { data: titles.map(title => { return { title }; }), error: null } } }); } ); });
the_stack
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe'; import { MockPipe, MockProvider } from 'ng-mocks'; import { LearningGoalService } from 'app/course/learning-goals/learningGoal.service'; import { of } from 'rxjs'; import { LearningGoal } from 'app/entities/learningGoal.model'; import { ActivatedRoute } from '@angular/router'; import { AlertService } from 'app/core/util/alert.service'; import { IndividualLearningGoalProgress, IndividualLectureUnitProgress } from 'app/course/learning-goals/learning-goal-individual-progress-dtos.model'; import { Component, Input } from '@angular/core'; import { CourseLearningGoalsComponent } from 'app/overview/course-learning-goals/course-learning-goals.component'; import { HttpResponse } from '@angular/common/http'; import { By } from '@angular/platform-browser'; import { TextUnit } from 'app/entities/lecture-unit/textUnit.model'; import { AccountService } from 'app/core/auth/account.service'; import { User } from 'app/core/user/user.model'; import { cloneDeep } from 'lodash-es'; import * as Sentry from '@sentry/browser'; import { CourseScoreCalculationService } from 'app/overview/course-score-calculation.service'; import { Course } from 'app/entities/course.model'; @Component({ selector: 'jhi-learning-goal-card', template: '<div><ng-content></ng-content></div>' }) class LearningGoalCardStubComponent { @Input() learningGoal: LearningGoal; @Input() learningGoalProgress: IndividualLearningGoalProgress; @Input() isPrerequisite: Boolean; @Input() displayOnly: Boolean; } class MockActivatedRoute { parent: any; params: any; constructor(options: { parent?: any; params?: any }) { this.parent = options.parent; this.params = options.params; } } const mockActivatedRoute = new MockActivatedRoute({ parent: new MockActivatedRoute({ parent: new MockActivatedRoute({ params: of({ courseId: '1' }), }), }), }); describe('CourseLearningGoals', () => { let courseLearningGoalsComponentFixture: ComponentFixture<CourseLearningGoalsComponent>; let courseLearningGoalsComponent: CourseLearningGoalsComponent; let learningGoalService: LearningGoalService; beforeEach(() => { TestBed.configureTestingModule({ imports: [], declarations: [CourseLearningGoalsComponent, LearningGoalCardStubComponent, MockPipe(ArtemisTranslatePipe)], providers: [ MockProvider(AlertService), MockProvider(CourseScoreCalculationService), MockProvider(LearningGoalService), MockProvider(AccountService), { provide: ActivatedRoute, useValue: mockActivatedRoute, }, ], schemas: [], }) .compileComponents() .then(() => { courseLearningGoalsComponentFixture = TestBed.createComponent(CourseLearningGoalsComponent); courseLearningGoalsComponent = courseLearningGoalsComponentFixture.componentInstance; learningGoalService = TestBed.inject(LearningGoalService); const accountService = TestBed.inject(AccountService); const user = new User(); user.login = 'testUser'; jest.spyOn(accountService, 'userIdentity', 'get').mockReturnValue(user); }); }); afterEach(() => { jest.restoreAllMocks(); }); it('should initialize', () => { courseLearningGoalsComponentFixture.detectChanges(); expect(courseLearningGoalsComponent).toBeDefined(); expect(courseLearningGoalsComponent.courseId).toEqual(1); }); it('should load progress for each learning goal in a given course', () => { const courseCalculationService = TestBed.inject(CourseScoreCalculationService); const learningGoal = new LearningGoal(); const textUnit = new TextUnit(); learningGoal.id = 1; learningGoal.description = 'Petierunt uti sibi concilium totius'; learningGoal.lectureUnits = [textUnit]; // Mock a course that was already fetched in another component const course = new Course(); course.id = 1; course.learningGoals = [learningGoal]; course.prerequisites = [learningGoal]; courseCalculationService.setCourses([course]); const getCourseSpy = jest.spyOn(courseCalculationService, 'getCourse').mockReturnValue(course); const learningUnitProgress = new IndividualLectureUnitProgress(); learningUnitProgress.lectureUnitId = textUnit.id!; learningUnitProgress.totalPointsAchievableByStudentsInLectureUnit = 10; const learningGoalProgress = new IndividualLearningGoalProgress(); learningGoalProgress.learningGoalId = learningGoal.id!; learningGoalProgress.learningGoalTitle = learningGoal.title!; learningGoalProgress.pointsAchievedByStudentInLearningGoal = 5; learningGoalProgress.totalPointsAchievableByStudentsInLearningGoal = 10; learningGoalProgress.progressInLectureUnits = [learningUnitProgress]; const learningGoalProgressResponse: HttpResponse<IndividualLearningGoalProgress> = new HttpResponse({ body: learningGoalProgress, status: 200, }); const getAllForCourseSpy = jest.spyOn(learningGoalService, 'getAllForCourse'); const getProgressSpy = jest.spyOn(learningGoalService, 'getProgress'); getProgressSpy.mockReturnValueOnce(of(learningGoalProgressResponse)); // when useParticipantScoreTable = false getProgressSpy.mockReturnValueOnce(of(learningGoalProgressResponse)); // when useParticipantScoreTable = true courseLearningGoalsComponentFixture.detectChanges(); expect(getCourseSpy).toHaveBeenCalledOnce(); expect(getCourseSpy).toHaveBeenCalledWith(1); expect(courseLearningGoalsComponent.course).toEqual(course); expect(courseLearningGoalsComponent.learningGoals).toEqual([learningGoal]); expect(getAllForCourseSpy).not.toHaveBeenCalled(); // do not load learning goals again as already fetched expect(getProgressSpy).toHaveBeenCalledTimes(2); expect(getProgressSpy).toHaveBeenNthCalledWith(1, 1, 1, false); expect(getProgressSpy).toHaveBeenNthCalledWith(2, 1, 1, true); expect(courseLearningGoalsComponent.learningGoalIdToLearningGoalProgress.get(1)).toEqual(learningGoalProgress); }); it('should load prerequisites and learning goals (with associated progress) and display a card for each of them', () => { const learningGoal = new LearningGoal(); const textUnit = new TextUnit(); learningGoal.id = 1; learningGoal.description = 'test'; learningGoal.lectureUnits = [textUnit]; const learningUnitProgress = new IndividualLectureUnitProgress(); learningUnitProgress.lectureUnitId = 1; learningUnitProgress.totalPointsAchievableByStudentsInLectureUnit = 10; const learningGoalProgress = new IndividualLearningGoalProgress(); learningGoalProgress.learningGoalId = 1; learningGoalProgress.learningGoalTitle = 'test'; learningGoalProgress.pointsAchievedByStudentInLearningGoal = 5; learningGoalProgress.totalPointsAchievableByStudentsInLearningGoal = 10; learningGoalProgress.progressInLectureUnits = [learningUnitProgress]; const prerequisitesOfCourseResponse: HttpResponse<LearningGoal[]> = new HttpResponse({ body: [new LearningGoal()], status: 200, }); const learningGoalsOfCourseResponse: HttpResponse<LearningGoal[]> = new HttpResponse({ body: [learningGoal, new LearningGoal()], status: 200, }); const learningGoalProgressResponse: HttpResponse<IndividualLearningGoalProgress> = new HttpResponse({ body: learningGoalProgress, status: 200, }); const learningGoalProgressParticipantScores = cloneDeep(learningGoalProgress); learningGoalProgressParticipantScores.pointsAchievedByStudentInLearningGoal = 0; const learningGoalProgressParticipantScoreResponse: HttpResponse<IndividualLearningGoalProgress> = new HttpResponse({ body: learningGoalProgressParticipantScores, status: 200, }); const getAllPrerequisitesForCourseSpy = jest.spyOn(learningGoalService, 'getAllPrerequisitesForCourse').mockReturnValue(of(prerequisitesOfCourseResponse)); const getAllForCourseSpy = jest.spyOn(learningGoalService, 'getAllForCourse').mockReturnValue(of(learningGoalsOfCourseResponse)); const getProgressSpy = jest.spyOn(learningGoalService, 'getProgress'); getProgressSpy.mockReturnValueOnce(of(learningGoalProgressResponse)); // when useParticipantScoreTable = false getProgressSpy.mockReturnValueOnce(of(learningGoalProgressResponse)); // when useParticipantScoreTable = false getProgressSpy.mockReturnValueOnce(of(learningGoalProgressParticipantScoreResponse)); // when useParticipantScoreTable = true getProgressSpy.mockReturnValueOnce(of(learningGoalProgressParticipantScoreResponse)); // when useParticipantScoreTable = true const captureExceptionSpy = jest.spyOn(Sentry, 'captureException'); courseLearningGoalsComponentFixture.detectChanges(); const learningGoalCards = courseLearningGoalsComponentFixture.debugElement.queryAll(By.directive(LearningGoalCardStubComponent)); expect(learningGoalCards).toHaveLength(3); // 1 prerequisite and 2 learning goals expect(getAllPrerequisitesForCourseSpy).toHaveBeenCalledOnce(); expect(getAllForCourseSpy).toHaveBeenCalledOnce(); expect(getProgressSpy).toHaveBeenCalledTimes(4); expect(courseLearningGoalsComponent.learningGoals).toHaveLength(2); expect(courseLearningGoalsComponent.learningGoalIdToLearningGoalProgressUsingParticipantScoresTables.has(1)).toEqual(true); expect(courseLearningGoalsComponent.learningGoalIdToLearningGoalProgress.has(1)).toEqual(true); expect(captureExceptionSpy).toHaveBeenCalledOnce(); }); });
the_stack
'use strict'; import { ParseError } from '../../parser/cssErrors'; import { LESSParser } from '../../parser/lessParser'; import { assertNode, assertNoNode, assertError } from '../css/parser.test'; suite('LESS - Parser', () => { test('Variable', function () { let parser = new LESSParser(); assertNode('@color', parser, parser._parseVariable.bind(parser)); assertNode('$color', parser, parser._parseVariable.bind(parser)); assertNode('$$color', parser, parser._parseVariable.bind(parser)); assertNode('@$color', parser, parser._parseVariable.bind(parser)); assertNode('$@color', parser, parser._parseVariable.bind(parser)); assertNode('@co42lor', parser, parser._parseVariable.bind(parser)); assertNode('@-co42lor', parser, parser._parseVariable.bind(parser)); assertNode('@@foo', parser, parser._parseVariable.bind(parser)); assertNode('@@@foo', parser, parser._parseVariable.bind(parser)); assertNode('@12ooo', parser, parser._parseVariable.bind(parser)); assertNode('@foo[]', parser, parser._parseVariable.bind(parser)); assertNode('@foo[bar]', parser, parser._parseVariable.bind(parser)); assertNode('@foo[@bar]', parser, parser._parseVariable.bind(parser)); assertNode('@foo[$bar]', parser, parser._parseVariable.bind(parser)); assertNode('@foo[@@bar]', parser, parser._parseVariable.bind(parser)); assertNode('@foo[100]', parser, parser._parseVariable.bind(parser)); assertNode('@foo[1prop]', parser, parser._parseVariable.bind(parser)); assertNode('@foo[--prop]', parser, parser._parseVariable.bind(parser)); assertNoNode('@ @foo', parser, parser._parseFunction.bind(parser)); assertNoNode('@-@foo', parser, parser._parseFunction.bind(parser)); }); test('Media', function () { let parser = new LESSParser(); assertNode('@media @phone {}', parser, parser._parseMedia.bind(parser)); assertNode('@media(max-width: 767px) { .mixinRef() }', parser, parser._parseMedia.bind(parser)); assertNode('@media(max-width: 767px) { .mixinDec() {} }', parser, parser._parseMedia.bind(parser)); assertNode('.something { @media (max-width: 760px) { > div { display: block; } } }', parser, parser._parseStylesheet.bind(parser)); assertNode('@media (@var) {}', parser, parser._parseMedia.bind(parser)); assertNode('@media (@sizes[@large]) {}', parser, parser._parseMedia.bind(parser)); assertNode('@media screen and (@var) {}', parser, parser._parseMedia.bind(parser)); assertNode('@media (max-width: 760px) { + div { display: block; } }', parser, parser._parseStylesheet.bind(parser)); }); test('VariableDeclaration', function () { let parser = new LESSParser(); assertNode('@color: #F5F5F5', parser, parser._parseVariableDeclaration.bind(parser)); assertNode('@color: 0', parser, parser._parseVariableDeclaration.bind(parser)); assertNode('@color: 255', parser, parser._parseVariableDeclaration.bind(parser)); assertNode('@color: 25.5', parser, parser._parseVariableDeclaration.bind(parser)); assertNode('@color: 25px', parser, parser._parseVariableDeclaration.bind(parser)); assertNode('@color: 25.5px', parser, parser._parseVariableDeclaration.bind(parser)); assertNode('@primary-font: "wf_SegoeUI","Segoe UI","Segoe","Segoe WP"', parser, parser._parseVariableDeclaration.bind(parser)); assertNode('@greeting: `"hello".toUpperCase() + "!";`', parser, parser._parseVariableDeclaration.bind(parser)); assertNode('@greeting: { display: none; }', parser, parser._parseVariableDeclaration.bind(parser)); assertNode('@b: @a !important', parser, parser._parseVariableDeclaration.bind(parser)); assertNode('@rules: .mixin()', parser, parser._parseVariableDeclaration.bind(parser)); assertNode('@rules: .mixin()[]', parser, parser._parseVariableDeclaration.bind(parser)); assertNode('@rules: .mixin(@value)[@lookup][prop]', parser, parser._parseVariableDeclaration.bind(parser)); assertNode('@rules: .mixin[@lookup][prop]', parser, parser._parseVariableDeclaration.bind(parser)); assertNode('@expr: .mixin(@value)[] .mixin(@value2)[]', parser, parser._parseVariableDeclaration.bind(parser)); }); test('MixinDeclaration', function () { let parser = new LESSParser(); assertNode('.color (@color: 25.5px) { }', parser, parser._tryParseMixinDeclaration.bind(parser)); assertNode('.color(@color: 25.5px) { }', parser, parser._tryParseMixinDeclaration.bind(parser)); assertNode('.color(@color) { }', parser, parser._tryParseMixinDeclaration.bind(parser)); assertNode('.color(@color; @border) { }', parser, parser._tryParseMixinDeclaration.bind(parser)); assertNode('.color() { }', parser, parser._tryParseMixinDeclaration.bind(parser)); assertNode('.color( ) { }', parser, parser._tryParseMixinDeclaration.bind(parser)); assertNode('.mixin (@a) when (@a > 10), (@a < -10) { }', parser, parser._tryParseMixinDeclaration.bind(parser)); assertNode('.mixin (@a) when (isnumber(@a)) and (@a > 0) { }', parser, parser._tryParseMixinDeclaration.bind(parser)); assertNode('.mixin (@b) when not (@rules[@b] >= 0) { }', parser, parser._tryParseMixinDeclaration.bind(parser)); assertNode('.mixin (@b) when not (@b > 0) { }', parser, parser._tryParseMixinDeclaration.bind(parser)); assertNode('.mixin (@a, @rest...) { }', parser, parser._tryParseMixinDeclaration.bind(parser)); assertNode('.mixin (@a) when (lightness(@a) >= 50%) { }', parser, parser._tryParseMixinDeclaration.bind(parser)); assertNode('.class(@color-list, @i: 1) when (@i <= @list-length) and (@list-length > 1) { }', parser, parser._tryParseMixinDeclaration.bind(parser)); assertNode('#color() { }', parser, parser._tryParseMixinDeclaration.bind(parser)); assertNode('#truth (@a) when (@a = true) { }', parser, parser._tryParseMixinDeclaration.bind(parser)); assertNode('.color (@color; @padding: 2;) { }', parser, parser._tryParseMixinDeclaration.bind(parser)); assertNode('.font-face(@source, @target) { @font-face { font-family: @source; src: local(\'@{target}\');} }', parser, parser._tryParseMixinDeclaration.bind(parser)); assertError('.color (@color; @padding: 2;;) { }', parser, parser._tryParseMixinDeclaration.bind(parser), ParseError.IdentifierExpected); assertNode('.mixin-definition(@a: {}; @b: {default: works;};) { @a(); @b(); }', parser, parser._tryParseMixinDeclaration.bind(parser)); }); test('MixinReference', function () { let parser = new LESSParser(); assertNode('.box-shadow(0 0 5px, 30%)', parser, parser._tryParseMixinReference.bind(parser)); assertNode('.box-shadow', parser, parser._tryParseMixinReference.bind(parser)); assertNode('.mixin(10) !important', parser, parser._tryParseMixinReference.bind(parser)); assertNode('.mixin(@a: 2, @b: 1)', parser, parser._tryParseMixinReference.bind(parser)); assertNode('#mixin(@a: 2, @b: 1)', parser, parser._tryParseMixinReference.bind(parser)); assertNode('#bundle > .button', parser, parser._tryParseMixinReference.bind(parser)); assertNode('#bundle.button', parser, parser._tryParseMixinReference.bind(parser)); assertNode('#bundle #inner #button(1)', parser, parser._tryParseMixinReference.bind(parser)); assertNode('.mixin(#008000;)', parser, parser._tryParseMixinReference.bind(parser)); assertNode('.mixin ()', parser, parser._tryParseMixinReference.bind(parser)); assertError('.mixin(#008000;;)', parser, parser._tryParseMixinReference.bind(parser), ParseError.ExpressionExpected); }); test('DetachedRuleSet', function () { let parser = new LESSParser(); assertNode('.foo { @greeting(); }', parser, parser._parseStylesheet.bind(parser)); assertNode('.media-switch(@styles) { @media(orientation:landscape){ @styles(); @foo: 9; } }', parser, parser._parseStylesheet.bind(parser)); assertNode('.media-switch({ flex-direction: row; });', parser, parser._parseStylesheet.bind(parser)); assertNode('.keyframes(@name; @arguments) { @-moz-keyframes @name { @arguments(); } }', parser, parser._parseStylesheet.bind(parser)); assertNode('.keyframes(fade-in;{ 0%, 100% { opacity: 1; }});', parser, parser._parseStylesheet.bind(parser)); assertNode('.foo({ .bar { color: red; }})', parser, parser._parseStylesheet.bind(parser)); assertNode('.foo({ .bar { .baz { color: red; }}})', parser, parser._parseStylesheet.bind(parser)); assertNode('.foo(10px; { .bar { .baz { color: red; }}})', parser, parser._parseStylesheet.bind(parser)); assertNode('.foo(fade-in; { .bar { .baz { color: red; }}})', parser, parser._parseStylesheet.bind(parser)); assertNode('.mixin1({a:b; .mixin2({c: d})})', parser, parser._parseStylesheet.bind(parser)); }); test('MixinParameter', function () { let parser = new LESSParser(); assertNode('@_', parser, parser._parseMixinParameter.bind(parser)); assertNode('@let: value', parser, parser._parseMixinParameter.bind(parser)); assertNode('@let', parser, parser._parseMixinParameter.bind(parser)); assertNode('@rest...', parser, parser._parseMixinParameter.bind(parser)); assertNode('...', parser, parser._parseMixinParameter.bind(parser)); assertNode('value', parser, parser._parseMixinParameter.bind(parser)); assertNode('"string"', parser, parser._parseMixinParameter.bind(parser)); assertNode('50%', parser, parser._parseMixinParameter.bind(parser)); }); test('Function', function () { let parser = new LESSParser(); assertNode('%()', parser, parser._parseFunction.bind(parser)); assertNoNode('% ()', parser, parser._parseFunction.bind(parser)); assertNode('func(a, b; bar)', parser, parser._parseRuleSetDeclaration.bind(parser)); assertNode('func({a: b();}, bar)', parser, parser._parseRuleSetDeclaration.bind(parser)); assertNode('func(.(@val) {})', parser, parser._parseRuleSetDeclaration.bind(parser)); assertNode('each(@list, .(@v) { prop: @v });', parser, parser._parseStylesheet.bind(parser)); assertNode('each(@list, #(@v) { prop: @v });', parser, parser._parseStylesheet.bind(parser)); }); test('Expr', function () { let parser = new LESSParser(); assertNode('(@let + 20)', parser, parser._parseExpr.bind(parser)); assertNode('(@let - 20)', parser, parser._parseExpr.bind(parser)); assertNode('(@let * 20)', parser, parser._parseExpr.bind(parser)); assertNode('(@let / 20)', parser, parser._parseExpr.bind(parser)); assertNode('(20 + @let)', parser, parser._parseExpr.bind(parser)); assertNode('(20 - @let)', parser, parser._parseExpr.bind(parser)); assertNode('(20 * @let)', parser, parser._parseExpr.bind(parser)); assertNode('(20 / @let)', parser, parser._parseExpr.bind(parser)); assertNode('(20 / 20 + @let)', parser, parser._parseExpr.bind(parser)); assertNode('(20 + 20 + @let)', parser, parser._parseExpr.bind(parser)); assertNode('(20 + 20 + 20 + @let)', parser, parser._parseExpr.bind(parser)); assertNode('(20 + 20 + 20 + 20 + @let)', parser, parser._parseExpr.bind(parser)); assertNode('(20 + 20 + @let + 20 + 20 + @let)', parser, parser._parseExpr.bind(parser)); assertNode('(20 + 20)', parser, parser._parseExpr.bind(parser)); assertNode('(@var1 + @var2)', parser, parser._parseExpr.bind(parser)); assertNode('((@let + 5) * 2)', parser, parser._parseExpr.bind(parser)); assertNode('((@let + (5 + 2)) * 2)', parser, parser._parseExpr.bind(parser)); assertNode('(@let + ((5 + 2) * 2))', parser, parser._parseExpr.bind(parser)); assertNode('@color', parser, parser._parseExpr.bind(parser)); assertNode('@color, @color', parser, parser._parseExpr.bind(parser)); assertNode('@color, 42%', parser, parser._parseExpr.bind(parser)); assertNode('@color, 42%, @color', parser, parser._parseExpr.bind(parser)); assertNode('@color - (@color + 10%)', parser, parser._parseExpr.bind(parser)); assertNode('(@base + @filler)', parser, parser._parseExpr.bind(parser)); assertNode('(100% / 2 + @filler)', parser, parser._parseExpr.bind(parser)); assertNode('100% / 2 + @filler', parser, parser._parseExpr.bind(parser)); }); test('LessOperator', function () { let parser = new LESSParser(); assertNode('>=', parser, parser._parseOperator.bind(parser)); assertNode('>', parser, parser._parseOperator.bind(parser)); assertNode('<', parser, parser._parseOperator.bind(parser)); assertNode('=<', parser, parser._parseOperator.bind(parser)); }); test('Extend', function () { let parser = new LESSParser(); assertNode('nav { &:extend(.inline); }', parser, parser._parseRuleset.bind(parser)); assertNode('nav { &:extend(.test all); }', parser, parser._parseRuleset.bind(parser)); assertNode('.big-bucket:extend(.bucket all) { }', parser, parser._parseRuleset.bind(parser)); assertNode('.some-class:extend(tr .bucket) {}', parser, parser._parseRuleset.bind(parser)); assertNode('.c:extend(.a, .b) {}', parser, parser._parseRuleset.bind(parser)); assertNode('.d { &:extend(.a, .b); }', parser, parser._parseRuleset.bind(parser)); }); test('Declaration', function () { let parser = new LESSParser(); assertNode('border: thin solid 1px', parser, parser._parseDeclaration.bind(parser)); assertNode('dummy: @color', parser, parser._parseDeclaration.bind(parser)); assertNode('dummy: blue', parser, parser._parseDeclaration.bind(parser)); assertNode('dummy: (20 / @let)', parser, parser._parseDeclaration.bind(parser)); assertNode('dummy: (20 / 20 + @let)', parser, parser._parseDeclaration.bind(parser)); assertNode('dummy: func(@red)', parser, parser._parseDeclaration.bind(parser)); assertNode('dummy: desaturate(@red, 10%)', parser, parser._parseDeclaration.bind(parser)); assertNode('dummy: desaturate(16, 10%)', parser, parser._parseDeclaration.bind(parser)); assertNode('100: 100', parser, parser._parseDeclaration.bind(parser)); assertNode('1prop: 100', parser, parser._parseDeclaration.bind(parser)); assertNode('1@{var}prop: 100', parser, parser._parseDeclaration.bind(parser)); assertNode('--100: 100', parser, parser._parseDeclaration.bind(parser)); assertNode('--1prop: 100', parser, parser._parseDeclaration.bind(parser)); assertNode('color: @base-color + #111', parser, parser._parseDeclaration.bind(parser)); assertNode('color: 100% / 2 + @ref', parser, parser._parseDeclaration.bind(parser)); assertNode('border: (@width * 2) solid black', parser, parser._parseDeclaration.bind(parser)); assertNode('property: @class', parser, parser._parseDeclaration.bind(parser)); assertNode('prop-erty: fnc(@t, 10%)', parser, parser._parseDeclaration.bind(parser)); assertNode('background: url(//yourdomain/yourpath.png)', parser, parser._parseDeclaration.bind(parser)); }); test('Stylesheet', function () { let parser = new LESSParser(); assertNode('.color (@radius: 5px){ -border-radius: #F5F5F5 }', parser, parser._parseStylesheet.bind(parser)); assertNode('.color (@radius: 5px){ -border-radius: @radius }', parser, parser._parseStylesheet.bind(parser)); assertNode('.color (@radius: 5px){ -border-radius: #F5F5F5 } .color (@radius: 5px) { -border-radius: #F5F5F5 }', parser, parser._parseStylesheet.bind(parser)); assertNode('.color (@radius: 5px) { -border-radius: #F5F5F5 } .color (@radius: 5px) { -border-radius: #F5F5F5 } .color (@radius: 5px) { -border-radius: #F5F5F5 }', parser, parser._parseStylesheet.bind(parser)); assertNode('.color (@radius: 5px) { -border-radius: #F5F5F5 } .color (@radius: 5px) { -border-radius: #F5F5F5 } .color (@radius: 5px) { -border-radius: #F5F5F5 }', parser, parser._parseStylesheet.bind(parser)); assertNode('.mixin (@a, @rest...) {}', parser, parser._parseStylesheet.bind(parser)); assertNode('.mixin (@a) when (lightness(@a) >= 50%) { background-color: black;}', parser, parser._parseStylesheet.bind(parser)); assertNode('.some-mixin { font-weight:bold; } h1 { .some-mixin; font-size:40px; }', parser, parser._parseStylesheet.bind(parser)); assertNode('#namespace when (@mode=huge) { .mixin() { } }', parser, parser._parseStylesheet.bind(parser)); assertNode('.generate-columns(1);', parser, parser._parseStylesheet.bind(parser)); assertNode('@dr1: {f:b}\n@dr2: {f:b}', parser, parser._parseStylesheet.bind(parser)); assertNode('@color: #F5F5F5;', parser, parser._parseStylesheet.bind(parser)); assertNode('@color: #F5F5F5; @color: #F5F5F5;', parser, parser._parseStylesheet.bind(parser)); assertNode('@color: #F5F5F5; @color: #F5F5F5; @color: #F5F5F5;', parser, parser._parseStylesheet.bind(parser)); assertNode('@color: #F5F5F5; .color (@radius: 5px) { -border-radius: #F5F5F5 } @color: #F5F5F5;', parser, parser._parseStylesheet.bind(parser)); assertNode('@import-once "lib";', parser, parser._parseStylesheet.bind(parser)); assertNode('@import-once (css) "hello";', parser, parser._parseStylesheet.bind(parser)); assertError('@import-once () "hello";', parser, parser._parseStylesheet.bind(parser), ParseError.IdentifierExpected); assertError('@import-once (less);', parser, parser._parseStylesheet.bind(parser), ParseError.URIOrStringExpected); assertNode('@import (css) "lib";', parser, parser._parseStylesheet.bind(parser)); assertNode('@import (optional, reference) "foo.less";', parser, parser._parseStylesheet.bind(parser)); assertNode('@import (optional, reference,) "foo.less";', parser, parser._parseStylesheet.bind(parser)); assertError('@import (optional, reference,,) "foo.less";', parser, parser._parseStylesheet.bind(parser), ParseError.RightParenthesisExpected); }); test('Ruleset', function () { let parser = new LESSParser(); assertNode('.selector { prop: erty @let 1px; }', parser, parser._parseRuleset.bind(parser)); assertNode('selector { .mixin; }', parser, parser._parseRuleset.bind(parser)); assertNode('selector { .mixin(1px); .mixin(blue, 1px, \'farboo\') }', parser, parser._parseRuleset.bind(parser)); assertNode('selector { .mixin(blue; 1px;\'farboo\') }', parser, parser._parseRuleset.bind(parser)); assertNode('selector:active { property:value; nested:hover {}}', parser, parser._parseRuleset.bind(parser)); assertNode('selector {}', parser, parser._parseRuleset.bind(parser)); assertNode('selector { property: declaration }', parser, parser._parseRuleset.bind(parser)); assertNode('selector { @variable: declaration }', parser, parser._parseRuleset.bind(parser)); assertNode('selector { nested {}}', parser, parser._parseRuleset.bind(parser)); assertNode('selector { nested, a, b {}}', parser, parser._parseRuleset.bind(parser)); assertNode('selector { property: value; property: value; }', parser, parser._parseRuleset.bind(parser)); assertNode('selector { property: value; @keyframes foo {} @-moz-keyframes foo {}}', parser, parser._parseRuleset.bind(parser)); assertNode('selector { @import "bar"; }', parser, parser._parseRuleset.bind(parser)); }); test('term', function () { let parser = new LESSParser(); assertNode('%(\'repetitions: %S file: %S\', 1 + 2, "directory/file.less")', parser, parser._parseTerm.bind(parser)); assertNode('~"ms:alwaysHasItsOwnSyntax.For.Stuff()"', parser, parser._parseTerm.bind(parser)); // less syntax assertNode('~`colorPalette("@{blue}", 1)`', parser, parser._parseTerm.bind(parser)); // less syntax }); test('Nested Ruleset', function () { let parser = new LESSParser(); assertNode('.class1 { @let: 1; .class { @let: 2; three: @let; let: 3; } one: @let; }', parser, parser._parseRuleset.bind(parser)); assertNode('.class1 { @let: 1; > .class2 { display: none; } }', parser, parser._parseRuleset.bind(parser)); assertNode('.foo { @supports(display: grid) { .bar { display: none; }}}', parser, parser._parseRuleset.bind(parser)); assertNode('.foo { @supports(display: grid) { display: none; }}', parser, parser._parseRuleset.bind(parser)); assertNode('.parent { color:green; @document url-prefix() { .child { color:red; }}}', parser, parser._parseStylesheet.bind(parser)); assertNode('@supports (property: value) { .outOfMedia & { @media (max-size: 2px) { @supports (whatever: something) { property: value;}}}}', parser, parser._parseStylesheet.bind(parser)); }); test('Interpolation', function () { let parser = new LESSParser(); assertNode('.@{name} { }', parser, parser._parseRuleset.bind(parser)); assertNode('.${name} { }', parser, parser._parseRuleset.bind(parser)); assertNode('.my-element:not(.prefix-@{sub-element}) { }', parser, parser._parseStylesheet.bind(parser)); assertNode('.-@{color} { }', parser, parser._parseStylesheet.bind(parser)); assertNode('.--@{color} { }', parser, parser._parseStylesheet.bind(parser)); assertNoNode('@', parser, parser._parseInterpolation.bind(parser)); assertNode('.px2rem(@name, @px) { @{name}: @px / @basesize; }', parser, parser._parseStylesheet.bind(parser)); assertError('@{', parser, parser._parseInterpolation.bind(parser), ParseError.IdentifierExpected); assertError('@{dd', parser, parser._parseInterpolation.bind(parser), ParseError.RightCurlyExpected); }); test('Selector Combinator', function () { let parser = new LESSParser(); assertNode('&:hover', parser, parser._parseSimpleSelector.bind(parser)); assertNode('&.float', parser, parser._parseSimpleSelector.bind(parser)); assertNode('&-foo', parser, parser._parseSimpleSelector.bind(parser)); assertNode('&-1', parser, parser._parseSimpleSelector.bind(parser)); assertNode('&1', parser, parser._parseSimpleSelector.bind(parser)); assertNode('&-foo-1', parser, parser._parseSimpleSelector.bind(parser)); assertNode('&-foo-1-2', parser, parser._parseSimpleSelector.bind(parser)); assertNode('&--&', parser, parser._parseSimpleSelector.bind(parser)); assertNode('&-10-thing', parser, parser._parseSimpleSelector.bind(parser)); }); test('CSS Guards', function () { let parser = new LESSParser(); assertNode('button when (@my-option = true) { color: white; }', parser, parser._parseStylesheet.bind(parser)); assertNode('.something .other when (@my-option = true) { color: white; }', parser, parser._parseStylesheet.bind(parser)); assertNode('& when (@my-option = true) { button { color: white; } }', parser, parser._parseStylesheet.bind(parser)); }); test('Merge', function () { let parser = new LESSParser(); assertNode('.mixin() { transform+_: scale(2); }', parser, parser._parseStylesheet.bind(parser)); assertNode('.myclass { box-shadow+: inset 0 0 10px #555; }', parser, parser._parseStylesheet.bind(parser)); }); test('url', function () { let parser = new LESSParser(); assertNode('url(//yourdomain/yourpath.png)', parser, parser._parseURILiteral.bind(parser)); assertNode('url(\'http://msft.com\')', parser, parser._parseURILiteral.bind(parser)); assertNode('url("http://msft.com")', parser, parser._parseURILiteral.bind(parser)); assertNode('url( "http://msft.com")', parser, parser._parseURILiteral.bind(parser)); assertNode('url(\t"http://msft.com")', parser, parser._parseURILiteral.bind(parser)); assertNode('url(\n"http://msft.com")', parser, parser._parseURILiteral.bind(parser)); assertNode('url("http://msft.com"\n)', parser, parser._parseURILiteral.bind(parser)); assertNode('url("")', parser, parser._parseURILiteral.bind(parser)); assertNode('uRL("")', parser, parser._parseURILiteral.bind(parser)); assertNode('URL("")', parser, parser._parseURILiteral.bind(parser)); assertNode('url(http://msft.com)', parser, parser._parseURILiteral.bind(parser)); assertNode('url()', parser, parser._parseURILiteral.bind(parser)); assertNode('url(\'http://msft.com\n)', parser, parser._parseURILiteral.bind(parser)); assertError('url("http://msft.com"', parser, parser._parseURILiteral.bind(parser), ParseError.RightParenthesisExpected); assertError('url(http://msft.com\')', parser, parser._parseURILiteral.bind(parser), ParseError.RightParenthesisExpected); }); test('@plugin', function () { let parser = new LESSParser(); assertNode('@plugin "my-plugin";', parser, parser._parseStylesheet.bind(parser)); }); });
the_stack
import { GeoPackage } from '../../geoPackage'; import { BaseExtension } from '../baseExtension'; import { Extension } from '../extension'; import { RTreeIndexDao } from './rtreeIndexDao'; import { FeatureDao } from '../../features/user/featureDao'; import { EnvelopeBuilder } from '../../geom/envelopeBuilder'; import { GeometryData } from '../../geom/geometryData'; import { FeatureRow } from '../../features/user/featureRow'; import { FeatureTable } from '../../features/user/featureTable'; /** * RTreeIndex extension * @class RTreeIndex * @extends BaseExtension * @param {module:geoPackage~GeoPackage} geoPackage The GeoPackage object */ export class RTreeIndex extends BaseExtension { /** * Trigger Insert name */ static TRIGGER_INSERT_NAME = 'insert'; /** * Trigger update 1 name */ static TRIGGER_UPDATE1_NAME = 'update1'; /** * Trigger update 2 name */ static TRIGGER_UPDATE2_NAME = 'update2'; /** * Trigger update 3 name */ static TRIGGER_UPDATE3_NAME = 'update3'; /** * Trigger update 4 name */ static TRIGGER_UPDATE4_NAME = 'update4'; /** * Trigger delete name */ static TRIGGER_DELETE_NAME = 'delete'; tableName: string; primaryKeyColumn: string; columnName: string; featureCount: number; rtreeIndexDao: RTreeIndexDao; extensionExists: boolean; constructor(geoPackage: GeoPackage, featureDao: FeatureDao<FeatureRow>) { super(geoPackage); this.extensionName = Extension.buildExtensionName( RTreeIndexDao.EXTENSION_RTREE_INDEX_AUTHOR, RTreeIndexDao.EXTENSION_RTREE_INDEX_NAME_NO_AUTHOR, ); this.extensionDefinition = RTreeIndexDao.EXTENSION_RTREE_INDEX_DEFINITION; if (featureDao !== null && featureDao !== undefined) { this.tableName = featureDao.table_name; this.primaryKeyColumn = featureDao.idColumns[0]; this.columnName = featureDao.getGeometryColumnName(); this.featureCount = featureDao.count(); } this.rtreeIndexDao = new RTreeIndexDao(geoPackage, featureDao); this.extensionExists = this.hasExtension(this.extensionName, this.tableName, this.columnName); this.createAllFunctions(); } getRTreeIndexExtension(): Extension[] { return this.getExtension(this.extensionName, this.tableName, this.columnName); } getOrCreateExtension(): Extension { return this.getOrCreate( this.extensionName, this.tableName, this.columnName, this.extensionDefinition, Extension.WRITE_ONLY, ); } /** * Create the RTree Index extension for the feature table, geometry column, * and id column. Creates the SQL functions, loads the tree, and creates the * triggers. * @param tableName table name * @param geometryColumnName geometry column name * @param idColumnName id column name * @return extension */ createWithParameters(tableName: string, geometryColumnName: string, idColumnName: string): Extension[] { if (this.hasExtension(this.extensionName, tableName, geometryColumnName)) { return this.getRTreeIndexExtension(); } this.getOrCreate(this.extensionName, tableName, geometryColumnName, RTreeIndexDao.EXTENSION_RTREE_INDEX_DEFINITION, Extension.WRITE_ONLY); this.createRTreeIndex(tableName, geometryColumnName); this.loadRTreeIndex(tableName, geometryColumnName, idColumnName); this.createAllTriggers(tableName, geometryColumnName, idColumnName); return this.getRTreeIndexExtension(); } /** * Create the extension * @param {Function} [progress] progress function * @returns {Extension[]} */ create(progress?: Function): Extension[] { // eslint-disable-next-line @typescript-eslint/no-empty-function const safeProgress = progress || function(): void {}; if (this.extensionExists) { return this.getRTreeIndexExtension(); } this.getOrCreate( this.extensionName, this.tableName, this.columnName, RTreeIndexDao.EXTENSION_RTREE_INDEX_DEFINITION, Extension.WRITE_ONLY, ); this.createAllFunctions(); this.createRTreeIndex(this.tableName, this.columnName); safeProgress({ description: 'Creating Feature Index', count: 0, totalCount: this.featureCount, layer: this.tableName, }); try { this.loadRTreeIndex(this.tableName, this.columnName, this.primaryKeyColumn); } catch (e) { console.log('ERROR CREATING RTREE INDEX', e); } this.createAllTriggers(this.tableName, this.columnName, this.primaryKeyColumn); return this.getRTreeIndexExtension(); } createAllTriggers(tableName: string, geometryColumnName: string, idColumnName: string): boolean { const insertTrigger = 'CREATE TRIGGER "rtree_' + tableName + '_' + geometryColumnName + '_insert" AFTER INSERT ON "' + tableName + '" WHEN (new.' + geometryColumnName + ' NOT NULL AND NOT ST_IsEmpty(NEW.' + geometryColumnName + ')) ' + 'BEGIN ' + ' INSERT OR REPLACE INTO "rtree_' + tableName + '_' + geometryColumnName + '" VALUES (' + ' NEW.' + idColumnName + ',' + ' ST_MinX(NEW.' + geometryColumnName + '), ST_MaxX(NEW.' + geometryColumnName + '), ' + ' ST_MinY(NEW.' + geometryColumnName + '), ST_MaxY(NEW.' + geometryColumnName + ') ' + ' ); ' + 'END;'; const update1Trigger = 'CREATE TRIGGER "rtree_' + tableName + '_' + geometryColumnName + '_update1" AFTER UPDATE OF ' + geometryColumnName + ' ON "' + tableName + '" WHEN OLD.' + idColumnName + ' = NEW.' + idColumnName + ' AND ' + ' (NEW.' + geometryColumnName + ' NOTNULL AND NOT ST_IsEmpty(NEW.' + geometryColumnName + ')) ' + 'BEGIN ' + ' INSERT OR REPLACE INTO "rtree_' + tableName + '_' + geometryColumnName + '" VALUES (' + ' NEW.' + idColumnName + ',' + ' ST_MinX(NEW.' + geometryColumnName + '), ST_MaxX(NEW.' + geometryColumnName + '), ' + ' ST_MinY(NEW.' + geometryColumnName + '), ST_MaxY(NEW.' + geometryColumnName + ') ' + ' ); ' + 'END;'; const update2Trigger = 'CREATE TRIGGER "rtree_' + tableName + '_' + geometryColumnName + '_update2" AFTER UPDATE OF ' + geometryColumnName + ' ON "' + tableName + '" WHEN OLD.' + idColumnName + ' = NEW.' + idColumnName + ' AND ' + ' (NEW.' + geometryColumnName + ' ISNULL OR ST_IsEmpty(NEW.' + geometryColumnName + ')) ' + 'BEGIN ' + ' DELETE FROM "rtree_' + tableName + '_' + geometryColumnName + '" WHERE id = OLD.' + idColumnName + '; ' + 'END;'; const update3Trigger = 'CREATE TRIGGER "rtree_' + tableName + '_' + geometryColumnName + '_update3" AFTER UPDATE OF ' + geometryColumnName + ' ON "' + tableName + '" WHEN OLD.' + idColumnName + ' != NEW.' + idColumnName + ' AND ' + ' (NEW.' + geometryColumnName + ' NOTNULL AND NOT ST_IsEmpty(NEW.' + geometryColumnName + ')) ' + 'BEGIN ' + ' DELETE FROM "rtree_' + tableName + '_' + geometryColumnName + '" WHERE id = OLD.' + idColumnName + '; ' + ' INSERT OR REPLACE INTO "rtree_' + tableName + '_' + geometryColumnName + '" VALUES (' + ' NEW.' + idColumnName + ', ' + ' ST_MinX(NEW.' + geometryColumnName + '), ST_MaxX(NEW.' + geometryColumnName + '), ' + ' ST_MinY(NEW.' + geometryColumnName + '), ST_MaxY(NEW.' + geometryColumnName + ')' + ' ); ' + 'END;'; const update4Trigger = 'CREATE TRIGGER "rtree_' + tableName + '_' + geometryColumnName + '_update4" AFTER UPDATE ON "' + tableName + '" WHEN OLD.' + idColumnName + ' != NEW.' + idColumnName + ' AND ' + ' (NEW.' + geometryColumnName + ' ISNULL OR ST_IsEmpty(NEW.' + geometryColumnName + ')) ' + 'BEGIN ' + ' DELETE FROM "rtree_' + tableName + '_' + geometryColumnName + '" WHERE id IN (OLD.' + idColumnName + ', NEW.' + idColumnName + '); ' + 'END;'; const deleteTrigger = 'CREATE TRIGGER "rtree_' + tableName + '_' + geometryColumnName + '_delete" AFTER DELETE ON "' + tableName + '" WHEN old.' + geometryColumnName + ' NOT NULL ' + 'BEGIN' + ' DELETE FROM "rtree_' + tableName + '_' + geometryColumnName + '" WHERE id = OLD.' + idColumnName + '; ' + 'END;'; let changes = 0; changes += this.connection.run(insertTrigger).changes; changes += this.connection.run(update1Trigger).changes; changes += this.connection.run(update2Trigger).changes; changes += this.connection.run(update3Trigger).changes; changes += this.connection.run(update4Trigger).changes; changes += this.connection.run(deleteTrigger).changes; return changes === 6; } loadRTreeIndex(tableName: string, geometryColumnName: string, idColumnName: string): boolean { return ( this.connection.run( 'INSERT OR REPLACE INTO "rtree_' + tableName + '_' + geometryColumnName + '" SELECT ' + idColumnName + ', st_minx(' + geometryColumnName + '), st_maxx(' + geometryColumnName + '), st_miny(' + geometryColumnName + '), st_maxy(' + geometryColumnName + ') FROM "' + tableName + '"', ).changes === 1 ); } createRTreeIndex(tableName: string, columnName: string): boolean { return ( this.connection.run( 'CREATE VIRTUAL TABLE "rtree_' + tableName + '_' + columnName + '" USING rtree(id, minx, maxx, miny, maxy)', ).changes === 1 ); } createAllFunctions(): void { this.createMinXFunction(); this.createMaxXFunction(); this.createMinYFunction(); this.createMaxYFunction(); this.createIsEmptyFunction(); } createMinXFunction(): void { this.connection.registerFunction('ST_MinX', function(buffer: Buffer | Uint8Array) { const geom = new GeometryData(buffer); let envelope = geom.envelope; if (!envelope) { envelope = EnvelopeBuilder.buildEnvelopeWithGeometry(geom.geometry); } if (envelope.minX === Infinity) { return null; } return envelope.minX; }); } createMinYFunction(): void { this.connection.registerFunction('ST_MinY', function(buffer: Buffer | Uint8Array) { const geom = new GeometryData(buffer); let envelope = geom.envelope; if (!envelope) { envelope = EnvelopeBuilder.buildEnvelopeWithGeometry(geom.geometry); } if (envelope.minY === Infinity) { return null; } return envelope.minY; }); } createMaxXFunction(): void { this.connection.registerFunction('ST_MaxX', function(buffer: Buffer | Uint8Array) { const geom = new GeometryData(buffer); let envelope = geom.envelope; if (!envelope) { envelope = EnvelopeBuilder.buildEnvelopeWithGeometry(geom.geometry); } if (envelope.maxX === -Infinity) { return null; } return envelope.maxX; }); } createMaxYFunction(): void { this.connection.registerFunction('ST_MaxY', function(buffer: Buffer | Uint8Array) { const geom = new GeometryData(buffer); let envelope = geom.envelope; if (!envelope) { envelope = EnvelopeBuilder.buildEnvelopeWithGeometry(geom.geometry); } if (envelope.maxY === -Infinity) { return null; } return envelope.maxY; }); } createIsEmptyFunction(): void { this.connection.registerFunction('ST_IsEmpty', function(buffer: Buffer | Uint8Array): number { const geom = new GeometryData(buffer); const empty = !geom || geom.empty || !geom.geometry; return empty ? 1 : 0; }); } has(table?: string, column?: string) { return this.hasExtension(this.extensionName, table, column); } deleteTable(tableName: string) { try { if (this.extensionsDao.isTableExists()) { let extensions = this.extensionsDao.queryByExtensionAndTableName(this.extensionName, tableName); extensions.forEach(extension => { this.deleteTableAndColumn(extension.getTableName(), extension.column_name) }) } } catch (e) { throw new Error("Failed to delete RTree Index extensions for table. GeoPackage: " + this.geoPackage.name + ", Table: " + tableName); } } /** * Delete the RTree Index extension for the table and geometry column. Drops * the triggers, RTree table, and deletes the extension. * @param tableName table name * @param geometryColumnName geometry column name */ deleteTableAndColumn(tableName: string, geometryColumnName: string) { if (this.has(tableName, geometryColumnName)) { this.dropTableAndColumn(tableName, geometryColumnName); try { this.extensionsDao.deleteByExtensionAndTableNameAndColumnName(this.extensionName, tableName, geometryColumnName); } catch (e) { throw new Error( "Failed to delete RTree Index extension. GeoPackage: " + this.geoPackage.name + ", Table: " + tableName + ", Geometry Column: " + geometryColumnName); } } } deleteAll() { try { if (this.extensionsDao.isTableExists()) { let extensions = this.extensionsDao.queryByExtensionAndTableName(this.extensionName, this.tableName); extensions.forEach(extension => { this.deleteTableAndColumn(extension.getTableName(), extension.column_name) }) } } catch (e) { throw new Error("Failed to delete RTree Index extensions for table. GeoPackage: " + this.geoPackage.name + ", Table: " + this.tableName); } } /** * Drop the the triggers and RTree table for the feature table * @param featureTable feature table */ dropByFeatureTable(featureTable: FeatureTable) { this.dropTableAndColumn(featureTable.getTableName(), featureTable.getGeometryColumnName()); } /** * Drop the the triggers and RTree table for the table and geometry column * * @param tableName table name * @param geometryColumnName geometry column name */ dropTableAndColumn(tableName: string, geometryColumnName: string) { this.dropAllTriggers(tableName, geometryColumnName); this.dropRTreeIndex(tableName, geometryColumnName); } /** * Drop the RTree Index Virtual Table * @param featureTable feature table */ dropRTreeIndexByFeatureTable(featureTable: FeatureTable) { this.dropRTreeIndex(featureTable.getTableName(), featureTable.getGeometryColumnName()); } /** * Drop the RTree Index Virtual Table * @param tableName table name * @param geometryColumnName geometry column name */ dropRTreeIndex(tableName: string, geometryColumnName: string) { try { this.geoPackage.connection.run('DROP TABLE "rtree_' + tableName + '_' + geometryColumnName + '"'); } catch (e) { // If no rtree module, try to delete manually if (e.getMessage().indexOf("no such module: rtree") > -1) { this.geoPackage.connection.run('DROP TABLE IF EXISTS "rtree_' + tableName + '_' + geometryColumnName + '_node"'); this.geoPackage.connection.run('DROP TABLE IF EXISTS "rtree_' + tableName + '_' + geometryColumnName + '_parent"'); this.geoPackage.connection.run('DROP TABLE IF EXISTS "rtree_' + tableName + '_' + geometryColumnName + '_rowid"'); this.geoPackage.connection.run('PRAGMA writable_schema = ON'); this.geoPackage.connection.run('DELETE FROM sqlite_master WHERE type = "table" AND name = "rtree_' + tableName + '_' + geometryColumnName + '"'); this.geoPackage.connection.run('PRAGMA writable_schema = OFF'); } else { throw e; } } } /** * Check if the feature table has the RTree extension and if found, drop the * triggers * @param featureTable feature table */ dropTriggersByFeatureTable(featureTable: FeatureTable) { this.dropTriggers(featureTable.getTableName(), featureTable.getGeometryColumnName()); } /** * Check if the table and column has the RTree extension and if found, drop * the triggers * @param tableName table name * @param columnName column name * @return true if dropped */ dropTriggers(tableName: string, columnName: string): boolean { let dropped = this.has(tableName, columnName); if (dropped) { this.dropAllTriggers(tableName, columnName); } return dropped; } /** * Drop Triggers that Maintain Spatial Index Values * @param featureTable feature table */ dropAllTriggersByFeatureTable(featureTable: FeatureTable) { this.dropAllTriggers(featureTable.getTableName(), featureTable.getGeometryColumnName()); } /** * Drop Triggers that Maintain Spatial Index Values * * @param tableName table name * @param geometryColumnName geometry column name */ dropAllTriggers(tableName: string, geometryColumnName: string) { this.dropInsertTrigger(tableName, geometryColumnName); this.dropUpdate1Trigger(tableName, geometryColumnName); this.dropUpdate2Trigger(tableName, geometryColumnName); this.dropUpdate3Trigger(tableName, geometryColumnName); this.dropUpdate4Trigger(tableName, geometryColumnName); this.dropDeleteTrigger(tableName, geometryColumnName); } /** * Drop insert trigger * * @param tableName * table name * @param geometryColumnName * geometry column name */ dropInsertTrigger(tableName: string, geometryColumnName: string) { this.dropTrigger(tableName, geometryColumnName, RTreeIndex.TRIGGER_INSERT_NAME); } /** * Drop update 1 trigger * * @param tableName table name * @param geometryColumnName geometry column name */ dropUpdate1Trigger(tableName: string, geometryColumnName: string) { this.dropTrigger(tableName, geometryColumnName, RTreeIndex.TRIGGER_UPDATE1_NAME); } /** * Drop update 2 trigger * * @param tableName * table name * @param geometryColumnName * geometry column name */ dropUpdate2Trigger(tableName: string, geometryColumnName: string) { this.dropTrigger(tableName, geometryColumnName, RTreeIndex.TRIGGER_UPDATE2_NAME); } /** * Drop update 3 trigger * * @param tableName * table name * @param geometryColumnName * geometry column name */ dropUpdate3Trigger(tableName: string, geometryColumnName: string) { this.dropTrigger(tableName, geometryColumnName, RTreeIndex.TRIGGER_UPDATE3_NAME); } /** * Drop update 4 trigger * * @param tableName * table name * @param geometryColumnName * geometry column name */ dropUpdate4Trigger(tableName: string, geometryColumnName: string) { this.dropTrigger(tableName, geometryColumnName, RTreeIndex.TRIGGER_UPDATE4_NAME); } /** * Drop delete trigger * * @param tableName * table name * @param geometryColumnName * geometry column name */ dropDeleteTrigger(tableName: string, geometryColumnName: string) { this.dropTrigger(tableName, geometryColumnName, RTreeIndex.TRIGGER_DELETE_NAME); } /** * Drop the trigger for the table, geometry column, and trigger name * @param tableName table name * @param geometryColumnName geometry column name * @param triggerName trigger name */ dropTrigger(tableName: string, geometryColumnName: string, triggerName: string) { this.geoPackage.connection.run('DROP TRIGGER IF EXISTS "rtree_' + tableName + '_' + geometryColumnName + '_' + triggerName + '"'); } }
the_stack
import * as fs from 'fs'; import * as path from 'path'; import { IDotnetInstallationContext } from '../Acquisition/IDotnetInstallationContext'; import { EventType } from './EventType'; import { IEvent } from './IEvent'; // tslint:disable max-classes-per-file export class DotnetAcquisitionStarted extends IEvent { public readonly eventName = 'DotnetAcquisitionStarted'; public readonly type = EventType.DotnetAcquisitionStart; constructor(public readonly version: string) { super(); } public getProperties() { return {AcquisitionStartVersion : this.version}; } } export class DotnetRuntimeAcquisitionStarted extends IEvent { public readonly eventName = 'DotnetRuntimeAcquisitionStarted'; public readonly type = EventType.DotnetRuntimeAcquisitionStart; public getProperties() { return undefined; } } export class DotnetSDKAcquisitionStarted extends IEvent { public readonly eventName = 'DotnetSDKAcquisitionStarted'; public readonly type = EventType.DotnetSDKAcquisitionStart; public getProperties() { return undefined; } } export class DotnetAcquisitionCompleted extends IEvent { public readonly eventName = 'DotnetAcquisitionCompleted'; public readonly type = EventType.DotnetAcquisitionCompleted; constructor(public readonly version: string, public readonly dotnetPath: string) { super(); } public getProperties(telemetry = false): { [key: string]: string } | undefined { if (telemetry) { return {AcquisitionCompletedVersion : this.version}; } else { return {AcquisitionCompletedVersion : this.version, AcquisitionCompletedDotnetPath : this.dotnetPath}; } } } export abstract class DotnetAcquisitionError extends IEvent { public readonly type = EventType.DotnetAcquisitionError; public isError = true; constructor(public readonly error: Error) { super(); } public getProperties(telemetry = false): { [key: string]: string } | undefined { return {ErrorName : this.error.name, ErrorMessage : this.error.message, StackTrace : this.error.stack ? this.error.stack : ''}; } } export class DotnetInstallScriptAcquisitionError extends DotnetAcquisitionError { public readonly eventName = 'DotnetInstallScriptAcquisitionError'; } export class WebRequestError extends DotnetAcquisitionError { public readonly eventName = 'WebRequestError'; } export class DotnetPreinstallDetectionError extends DotnetAcquisitionError { public readonly eventName = 'DotnetPreinstallDetectionError'; } export class DotnetCommandFailed extends DotnetAcquisitionError { public readonly eventName = 'DotnetCommandFailed'; constructor(error: Error, public readonly command: string) { super(error); } public getProperties(telemetry = false): { [key: string]: string } | undefined { return {ErrorMessage : this.error.message, CommandName : this.command, ErrorName : this.error.name, StackTrace : this.error.stack ? this.error.stack : ''}; } } export abstract class DotnetAcquisitionVersionError extends DotnetAcquisitionError { constructor(error: Error, public readonly version: string) { super(error); } public getProperties(telemetry = false): { [key: string]: string } | undefined { return {ErrorMessage : this.error.message, AcquisitionErrorVersion : this.version, ErrorName : this.error.name, StackTrace : this.error.stack ? this.error.stack : ''}; } } export class DotnetAcquisitionUnexpectedError extends DotnetAcquisitionVersionError { public readonly eventName = 'DotnetAcquisitionUnexpectedError'; } export class DotnetAcquisitionInstallError extends DotnetAcquisitionVersionError { public readonly eventName = 'DotnetAcquisitionInstallError'; } export class DotnetAcquisitionScriptError extends DotnetAcquisitionVersionError { public readonly eventName = 'DotnetAcquisitionScriptError'; } export class DotnetOfflineFailure extends DotnetAcquisitionVersionError { public readonly eventName = 'DotnetOfflineFailure'; } export class DotnetAcquisitionTimeoutError extends DotnetAcquisitionVersionError { public readonly eventName = 'DotnetAcquisitionTimeoutError'; constructor(error: Error, version: string, public readonly timeoutValue: number) { super(error, version); } public getProperties(telemetry = false): { [key: string]: string } | undefined { return {ErrorMessage : this.error.message, TimeoutValue : this.timeoutValue.toString(), Version : this.version, ErrorName : this.error.name, StackTrace : this.error.stack ? this.error.stack : ''}; } } export class DotnetVersionResolutionError extends DotnetAcquisitionVersionError { public readonly eventName = 'DotnetVersionResolutionError'; } export class DotnetInstallationValidationError extends DotnetAcquisitionVersionError { public readonly eventName = 'DotnetInstallationValidationError'; public readonly fileStructure: string; constructor(error: Error, version: string, public readonly dotnetPath: string) { super(error, version); this.fileStructure = this.getFileStructure(); } public getProperties(telemetry = false): { [key: string]: string } | undefined { return {ErrorMessage : this.error.message, AcquisitionErrorVersion : this.version, ErrorName : this.error.name, StackTrace : this.error.stack ? this.error.stack : '', FileStructure : this.fileStructure}; } private getFileStructure(): string { const folderPath = path.dirname(this.dotnetPath); if (!fs.existsSync(folderPath)) { return `Dotnet Path (${ path.basename(folderPath) }) does not exist`; } // Get 2 levels worth of content of the folder let files = fs.readdirSync(folderPath).map(file => path.join(folderPath, file)); for (const file of files) { if (fs.statSync(file).isDirectory()) { files = files.concat(fs.readdirSync(file).map(fileName => path.join(file, fileName))); } } const relativeFiles: string[] = []; for (const file of files) { relativeFiles.push(path.relative(path.dirname(folderPath), file)); } return relativeFiles.join('\n'); } } export abstract class DotnetAcquisitionSuccessEvent extends IEvent { public readonly type = EventType.DotnetAcquisitionSuccessEvent; public getProperties(): { [key: string]: string } | undefined { return undefined; } } export class DotnetCommandSucceeded extends DotnetAcquisitionSuccessEvent { public readonly eventName = 'DotnetCommandSucceeded'; constructor(public readonly commandName: string) { super(); } public getProperties() { return {CommandName : this.commandName}; } } export class DotnetUninstallAllStarted extends DotnetAcquisitionSuccessEvent { public readonly eventName = 'DotnetUninstallAllStarted'; } export class DotnetUninstallAllCompleted extends DotnetAcquisitionSuccessEvent { public readonly eventName = 'DotnetUninstallAllCompleted'; } export class DotnetVersionResolutionCompleted extends DotnetAcquisitionSuccessEvent { public readonly eventName = 'DotnetVersionResolutionCompleted'; constructor(public readonly requestedVerion: string, public readonly resolvedVersion: string) { super(); } public getProperties() { return {RequestedVersion : this.requestedVerion, ResolvedVersion : this.resolvedVersion}; } } export class DotnetInstallScriptAcquisitionCompleted extends DotnetAcquisitionSuccessEvent { public readonly eventName = 'DotnetInstallScriptAcquisitionCompleted'; } export class DotnetExistingPathResolutionCompleted extends DotnetAcquisitionSuccessEvent { public readonly eventName = 'DotnetExistingPathResolutionCompleted'; constructor(public readonly resolvedPath: string) { super(); } public getProperties(telemetry = false) { return telemetry ? undefined : { ConfiguredPath : this.resolvedPath}; } } export abstract class DotnetAcquisitionMessage extends IEvent { public readonly type = EventType.DotnetAcquisitionMessage; public getProperties(): { [key: string]: string } | undefined { return undefined; } } export class DotnetAcquisitionDeletion extends DotnetAcquisitionMessage { public readonly eventName = 'DotnetAcquisitionDeletion'; constructor(public readonly folderPath: string) { super(); } public getProperties(telemetry = false) { return telemetry ? undefined : {DeletedFolderPath : this.folderPath}; } } export class DotnetFallbackInstallScriptUsed extends DotnetAcquisitionMessage { public readonly eventName = 'DotnetFallbackInstallScriptUsed'; } export class DotnetAcquisitionPartialInstallation extends DotnetAcquisitionMessage { public readonly eventName = 'DotnetAcquisitionPartialInstallation'; constructor(public readonly version: string) { super(); } public getProperties() { return {PartialInstallationVersion: this.version}; } } export class DotnetAcquisitionInProgress extends DotnetAcquisitionMessage { public readonly eventName = 'DotnetAcquisitionInProgress'; constructor(public readonly version: string) { super(); } public getProperties() { return {InProgressInstallationVersion : this.version}; } } export class DotnetAcquisitionAlreadyInstalled extends DotnetAcquisitionMessage { public readonly eventName = 'DotnetAcquisitionAlreadyInstalled'; constructor(public readonly version: string) { super(); } public getProperties() { return {AlreadyInstalledVersion : this.version}; } } export class DotnetAcquisitionMissingLinuxDependencies extends DotnetAcquisitionMessage { public readonly eventName = 'DotnetAcquisitionMissingLinuxDependencies'; } export class DotnetAcquisitionScriptOuput extends DotnetAcquisitionMessage { public readonly eventName = 'DotnetAcquisitionScriptOuput'; public isError = true; constructor(public readonly version: string, public readonly output: string) { super(); } public getProperties(telemetry = false): { [key: string]: string } | undefined { return {AcquisitionVersion : this.version, ScriptOutput: this.output}; } } export class DotnetInstallationValidated extends DotnetAcquisitionMessage { public readonly eventName = 'DotnetInstallationValidated'; constructor(public readonly version: string) { super(); } public getProperties(telemetry = false): { [key: string]: string } | undefined { return {ValidatedVersion : this.version}; } } export class DotnetAcquisitionRequested extends DotnetAcquisitionMessage { public readonly eventName = 'DotnetAcquisitionRequested'; constructor(public readonly version: string, public readonly requestingId = '') { super(); } public getProperties() { return {AcquisitionStartVersion : this.version, RequestingExtensionId: this.requestingId}; } } export class DotnetAcquisitionStatusRequested extends DotnetAcquisitionMessage { public readonly eventName = 'DotnetAcquisitionStatusRequested'; constructor(public readonly version: string, public readonly requestingId = '') { super(); } public getProperties() { return {AcquisitionStartVersion : this.version, RequestingExtensionId: this.requestingId}; } } export class DotnetAcquisitionStatusUndefined extends DotnetAcquisitionMessage { public readonly eventName = 'DotnetAcquisitionStatusUndefined'; constructor(public readonly version: string) { super(); } public getProperties() { return {AcquisitionStatusVersion : this.version}; } } export class DotnetAcquisitionStatusResolved extends DotnetAcquisitionMessage { public readonly eventName = 'DotnetAcquisitionStatusResolved'; constructor(public readonly version: string) { super(); } public getProperties() { return {AcquisitionStatusVersion : this.version}; } } export class WebRequestSent extends DotnetAcquisitionMessage { public readonly eventName = 'WebRequestSent'; constructor(public readonly url: string) { super(); } public getProperties() { return {WebRequestUri : this.url}; } } export class DotnetPreinstallDetected extends DotnetAcquisitionMessage { public readonly eventName = 'DotnetPreinstallDetected'; constructor(public readonly version: string) { super(); } public getProperties() { return {PreinstalledVersion : this.version}; } } export class TestAcquireCalled extends IEvent { public readonly eventName = 'TestAcquireCalled'; public readonly type = EventType.DotnetAcquisitionTest; constructor(public readonly context: IDotnetInstallationContext) { super(); } public getProperties() { return undefined; } }
the_stack
import net from "net"; import { TextEncoder } from "util"; import { IBApiCreationOptions, MAX_SUPPORTED_SERVER_VERSION, MIN_SERVER_VER_SUPPORTED, } from "../../api/api"; import { EventName } from "../../api/data/enum/event-name"; import MIN_SERVER_VER from "../../api/data/enum/min-server-version"; import configuration from "../../common/configuration"; import { ErrorCode } from "../../common/errorCode"; import { Controller } from "./controller"; import { OUT_MSG_ID } from "./encoder"; /** * @hidden * envelope encoding, applicable to useV100Plus mode only */ const MIN_VERSION_V100 = 100; /** * @hidden * max message size, taken from Java client, applicable to useV100Plus mode only */ const MAX_V100_MESSAGE_LENGTH = 0xffffff; /** @hidden */ const EOL = "\0"; /** * @internal * * This class implements low-level details on the communication protocol of the * TWS/IB Gateway API server. */ export class Socket { /** * Create a new [[Socket]] object. * * @param controller The parent [[Controller]] object. * @param options The API creation options. */ constructor( private controller: Controller, private options: IBApiCreationOptions = {} ) { this._clientId = this.options.clientId ?? configuration.default_client_id; this.options.host = this.options.host; this.options.port = this.options.port; } /** The TCP client socket. */ private client?: net.Socket; /** `true` if the TCP socket is connected and [[OUT_MSG_ID.START_API]] has been sent, `false` otherwise. */ private _connected = false; /** The IB API Server version, or 0 if not connected yet. */ private _serverVersion = 0; /** The server connection time. */ private _serverConnectionTime = ""; /** Data fragment accumulation buffer. */ private dataFragment = ""; /** `true` if no message from server has been received yet, `false` otherwise. */ private neverReceived = true; /** `true` if waiting for completion of an async operation, `false` otherwise. */ private waitingAsync = false; /** `true` if V!00Pls protocol shall be used, `false` otherwise. */ private useV100Plus = true; /** Accumulation buffer for fragmented V100 messages */ private _v100MessageBuffer: Buffer = Buffer.alloc(0); /** The current client id. */ private _clientId: number; /** Returns `true` if connected to TWS/IB Gateway, `false` otherwise. */ get connected(): boolean { return this._connected; } /** Returns the IB API Server version. */ get serverVersion(): number { return this._serverVersion; } /** The server connection time. */ get serverConnectionTime(): string { return this._serverConnectionTime; } /** Get the current client id. */ get clientId(): number { return this._clientId; } /** * Disable usage of V100Plus protocol. */ disableUseV100Plus(): void { this.useV100Plus = false; } /** * Connect to the API server. * * @param clientId A unique client id (per TWS or IB Gateway instance). * When not specified, the client from [[IBApiCreationOptions]] or the * default client id (0) will used. */ connect(clientId?: number): void { // update client id if (clientId !== undefined) { this._clientId = clientId; } // pause controller while API startup sequence this.controller.pause(); // reset state this.dataFragment = ""; this.neverReceived = true; this.waitingAsync = false; this._v100MessageBuffer = Buffer.alloc(0); // create and connect TCP socket this.client = net .connect( { host: this.options.host ?? configuration.ib_host, port: this.options.port ?? configuration.ib_port, }, () => this.onConnect() ) .on("data", (data) => this.onData(data)) .on("close", () => this.onEnd()) .on("end", () => this.onEnd()) .on("error", (error) => this.onError(error)); } /** * Disconnect from API server. */ disconnect(): void { // pause controller while connection is down. this.controller.pause(); // disconnect TCP socket. this.client?.end(); } /** * Send tokens to API server. */ send(tokens: unknown[]): void { // flatten arrays and convert boolean types to 0/1 tokens = this.flattenDeep(tokens); tokens.forEach((value, i) => { if (value === true || value === false || value instanceof Boolean) { tokens[i] = value ? 1 : 0; } }); let stringData = tokens.join(EOL); if (this.useV100Plus) { let utf8Data; if (tokens[0] === "API\0") { // this is the initial API version message, which is special: // length is encoded after the 'API\0', followed by the actual tokens. const skip = 5; // 1 x 'API\0' token + 4 x length tokens stringData = tokens.slice(skip)[0] as string; utf8Data = [ ...this.stringToUTF8Array(tokens[0]), ...tokens.slice(1, skip), ...this.stringToUTF8Array(stringData), ]; } else { utf8Data = this.stringToUTF8Array(stringData); } // add length prefix only if not a string (strings use pre-V100 style) if (typeof tokens[0] !== "string") { utf8Data = [ ...this.numberTo32BitBigEndian(utf8Data.length + 1), ...utf8Data, 0, ]; } this.client?.write(Buffer.from(new Uint8Array(utf8Data))); } else { this.client?.write(stringData + EOL); } this.controller.emitEvent(EventName.sent, tokens, stringData); } /** * Called when data on the TCP socket has been arrived. */ private onData(data: Buffer): void { if (this.useV100Plus) { let dataToParse = data; if (this._v100MessageBuffer.length > 0) { dataToParse = Buffer.concat([this._v100MessageBuffer, data]); } if (dataToParse.length > MAX_V100_MESSAGE_LENGTH) { // At this point we have buffered enough data that we have exceeded the max known message length, // at which point this is likely an unrecoverable state and we should discard all prior data, // and disconnect the socket this._v100MessageBuffer = Buffer.alloc(0); this.onError( new Error( `Message of size ${dataToParse.length} exceeded max message length ${MAX_V100_MESSAGE_LENGTH}` ) ); this.disconnect(); return; } let messageBufferOffset = 0; while (messageBufferOffset + 4 < dataToParse.length) { let currentMessageOffset = messageBufferOffset; const msgSize = dataToParse.readInt32BE(currentMessageOffset); currentMessageOffset += 4; if (currentMessageOffset + msgSize <= dataToParse.length) { const segment = dataToParse.slice( currentMessageOffset, currentMessageOffset + msgSize ); currentMessageOffset += msgSize; this.onMessage(segment.toString("utf8")); messageBufferOffset = currentMessageOffset; } else { // We can't parse further, the message is incomplete break; } } if (messageBufferOffset != dataToParse.length) { // There is data left in the buffer, save it for the next data packet this._v100MessageBuffer = dataToParse.slice(messageBufferOffset); } else { this._v100MessageBuffer = Buffer.alloc(0); } } else { this.onMessage(data.toString()); } } /** * Called when new tokens have been received from server. */ private onMessage(data: string): void { // tokenize const dataWithFragment = this.dataFragment + data; let tokens = dataWithFragment.split(EOL); if (tokens[tokens.length - 1] !== "") { this.dataFragment = tokens[tokens.length - 1]; } else { this.dataFragment = ""; } tokens = tokens.slice(0, -1); this.controller.emitEvent(EventName.received, tokens.slice(0), data); // handle message data if (this.neverReceived) { // first message this.neverReceived = false; this.onServerVersion(tokens); } else { // post to queue if (this.useV100Plus) { this.controller.onMessage(tokens); } else { this.controller.onTokens(tokens); } // process queue this.controller.processIngressQueue(); } // resume from async state if (this.waitingAsync) { this.waitingAsync = false; this.controller.resume(); } } /** * Called when first data has arrived on the connection. */ private onServerVersion(tokens: string[]): void { this._connected = true; this._serverVersion = parseInt(tokens[0], 10); this._serverConnectionTime = tokens[1]; if ( this.useV100Plus && (this._serverVersion < MIN_VERSION_V100 || this._serverVersion > MAX_SUPPORTED_SERVER_VERSION) ) { this.disconnect(); this.controller.emitError( "Unsupported Version", ErrorCode.UNSUPPORTED_VERSION, -1 ); return; } if (this._serverVersion < MIN_SERVER_VER_SUPPORTED) { this.disconnect(); this.controller.emitError( "The TWS is out of date and must be upgraded.", ErrorCode.UPDATE_TWS, -1 ); return; } this.startAPI(); this.controller.emitEvent(EventName.connected); this.controller.emitEvent( EventName.server, this.serverVersion, this.serverConnectionTime ); } /** * Start the TWS/IB Gateway API. */ private startAPI(): void { // start API const VERSION = 2; if (this.serverVersion >= 3) { if (this.serverVersion < MIN_SERVER_VER.LINKING) { this.send([this._clientId]); } else { if (this.serverVersion >= MIN_SERVER_VER.OPTIONAL_CAPABILITIES) { this.send([OUT_MSG_ID.START_API, VERSION, this._clientId, ""]); } else { this.send([OUT_MSG_ID.START_API, VERSION, this._clientId]); } } } // resume controller this.controller.resume(); } /** * Called when TCP socket has been connected. */ private onConnect(): void { // send client version (unless Version > 100) if (!this.useV100Plus) { this.send([configuration.client_version]); this.send([this._clientId]); } else { // Switch to GW API (Version 100+ requires length prefix) const config = this.buildVersionString( MIN_VERSION_V100, MAX_SUPPORTED_SERVER_VERSION ); // config = config + connectOptions --- connectOptions are for IB internal use only: not supported this.send([ "API\0", ...this.numberTo32BitBigEndian(config.length), config, ]); } } /** * Called when TCP socket connection has been closed. */ private onEnd(): void { const wasConnected = this._connected; this._connected = false; if (wasConnected) { this.controller.emitEvent(EventName.disconnected); } this.controller.resume(); } /** * Called when an error occurred on the TCP socket connection. */ private onError(err: Error): void { this.controller.emitError(err.message, ErrorCode.CONNECT_FAIL, -1); } /** * Build a V100Plus API version string. */ private buildVersionString(minVersion: number, maxVersion: number): string { return ( "v" + (minVersion < maxVersion ? minVersion + ".." + maxVersion : minVersion) ); } /** * Convert a (integer) number to a 4-byte big endian byte array. */ private numberTo32BitBigEndian(val: number): number[] { const result: number[] = new Array(4); let pos = 0; result[pos++] = 0xff & (val >> 24); result[pos++] = 0xff & (val >> 16); result[pos++] = 0xff & (val >> 8); result[pos++] = 0xff & val; return result; } /** * Encode a string to a UTF8 byte array. */ private stringToUTF8Array(val: string): number[] { return Array.from(new TextEncoder().encode(val)); } /** * Flatten an array. * * Also works for nested arrays (i.e. arrays inside arrays inside arrays) */ private flattenDeep(arr: unknown[], result: unknown[] = []): unknown[] { for (let i = 0, length = arr.length; i < length; i++) { const value = arr[i]; if (Array.isArray(value)) { this.flattenDeep(value, result); } else { result.push(value); } } return result; } }
the_stack
import { Schema, Definition, Field } from "./schema"; import { error, quote } from "./util"; function cppType(definitions: {[name: string]: Definition}, field: Field, isArray: boolean): string { let type; switch (field.type) { case 'bool': type = 'bool'; break; case 'byte': type = 'uint8_t'; break; case 'int': type = 'int32_t'; break; case 'uint': type = 'uint32_t'; break; case 'float': type = 'float'; break; case 'string': type = 'kiwi::String'; break; default: { let definition = definitions[field.type!]; if (!definition) { error('Invalid type ' + quote(field.type!) + ' for field ' + quote(field.name), field.line, field.column); } type = definition.name; break; } } if (isArray) { type = 'kiwi::Array<' + type + '>'; } return type; } function cppFieldName(field: Field): string { return '_data_' + field.name; } function cppFlagIndex(i: number): number { return i >> 5; } function cppFlagMask(i: number): number { return 1 << (i % 32) >>> 0; } function cppIsFieldPointer(definitions: {[name: string]: Definition}, field: Field): boolean { return !field.isArray && field.type! in definitions && definitions[field.type!].kind !== 'ENUM'; } export function compileSchemaCPP(schema: Schema): string { let definitions: {[name: string]: Definition} = {}; let cpp: string[] = []; cpp.push('#include "kiwi.h"'); cpp.push(''); if (schema.package !== null) { cpp.push('namespace ' + schema.package + ' {'); cpp.push(''); cpp.push('#ifndef INCLUDE_' + schema.package.toUpperCase() + '_H'); cpp.push('#define INCLUDE_' + schema.package.toUpperCase() + '_H'); cpp.push(''); } for (let i = 0; i < schema.definitions.length; i++) { let definition = schema.definitions[i]; definitions[definition.name] = definition; } cpp.push('class BinarySchema {'); cpp.push('public:'); cpp.push(' bool parse(kiwi::ByteBuffer &bb);'); cpp.push(' const kiwi::BinarySchema &underlyingSchema() const { return _schema; }'); for (let i = 0; i < schema.definitions.length; i++) { let definition = schema.definitions[i]; if (definition.kind === 'MESSAGE') { cpp.push(' bool skip' + definition.name + 'Field(kiwi::ByteBuffer &bb, uint32_t id) const;'); } } cpp.push(''); cpp.push('private:'); cpp.push(' kiwi::BinarySchema _schema;'); for (let i = 0; i < schema.definitions.length; i++) { let definition = schema.definitions[i]; if (definition.kind === 'MESSAGE') { cpp.push(' uint32_t _index' + definition.name + ' = 0;'); } } cpp.push('};'); cpp.push(''); for (let i = 0; i < schema.definitions.length; i++) { let definition = schema.definitions[i]; if (definition.kind === 'ENUM') { cpp.push('enum class ' + definition.name + ' : uint32_t {'); for (let j = 0; j < definition.fields.length; j++) { let field = definition.fields[j]; cpp.push(' ' + field.name + ' = ' + field.value + ','); } cpp.push('};'); cpp.push(''); } else if (definition.kind !== 'STRUCT' && definition.kind !== 'MESSAGE') { error('Invalid definition kind ' + quote(definition.kind), definition.line, definition.column); } } for (let pass = 0; pass < 3; pass++) { let newline = false; if (pass === 2) { if (schema.package !== null) { cpp.push('#endif'); } cpp.push('#ifdef IMPLEMENT_SCHEMA_H'); cpp.push(''); cpp.push('bool BinarySchema::parse(kiwi::ByteBuffer &bb) {'); cpp.push(' if (!_schema.parse(bb)) return false;'); for (let i = 0; i < schema.definitions.length; i++) { let definition = schema.definitions[i]; if (definition.kind === 'MESSAGE') { cpp.push(' _schema.findDefinition("' + definition.name + '", _index' + definition.name + ');'); } } cpp.push(' return true;'); cpp.push('}'); cpp.push(''); for (let i = 0; i < schema.definitions.length; i++) { let definition = schema.definitions[i]; if (definition.kind === 'MESSAGE') { cpp.push('bool BinarySchema::skip' + definition.name + 'Field(kiwi::ByteBuffer &bb, uint32_t id) const {'); cpp.push(' return _schema.skipField(bb, _index' + definition.name + ', id);'); cpp.push('}'); cpp.push(''); } } } for (let i = 0; i < schema.definitions.length; i++) { let definition = schema.definitions[i]; if (definition.kind === 'ENUM') { continue; } let fields = definition.fields; if (pass === 0) { cpp.push('class ' + definition.name + ';'); newline = true; } else if (pass === 1) { cpp.push('class ' + definition.name + ' {'); cpp.push('public:'); // This may not actually be used, so silence warnings about "Private fields '_flags' is not used" cpp.push(' ' + definition.name + '() { (void)_flags; }'); cpp.push(''); for (let j = 0; j < fields.length; j++) { let field = fields[j]; if (field.isDeprecated) { continue; } let name = cppFieldName(field); let type = cppType(definitions, field, field.isArray); let flagIndex = cppFlagIndex(j); let flagMask = cppFlagMask(j); if (cppIsFieldPointer(definitions, field)) { cpp.push(' ' + type + ' *' + field.name + '();'); cpp.push(' const ' + type + ' *' + field.name + '() const;'); cpp.push(' void set_' + field.name + '(' + type + ' *value);'); } else if (field.isArray) { cpp.push(' ' + type + ' *' + field.name + '();'); cpp.push(' const ' + type + ' *' + field.name + '() const;'); cpp.push(' ' + type + ' &set_' + field.name + '(kiwi::MemoryPool &pool, uint32_t count);'); } else { cpp.push(' ' + type + ' *' + field.name + '();'); cpp.push(' const ' + type + ' *' + field.name + '() const;'); cpp.push(' void set_' + field.name + '(const ' + type + ' &value);'); } cpp.push(''); } cpp.push(' bool encode(kiwi::ByteBuffer &bb);'); cpp.push(' bool decode(kiwi::ByteBuffer &bb, kiwi::MemoryPool &pool, const BinarySchema *schema = nullptr);'); cpp.push(''); cpp.push('private:'); cpp.push(' uint32_t _flags[' + (fields.length + 31 >> 5) + '] = {};'); // Sort fields by size since that makes the resulting struct smaller let sizes: {[type: string]: number} = {'bool': 1, 'byte': 1, 'int': 4, 'uint': 4, 'float': 4}; let sortedFields = fields.slice().sort(function(a, b) { let sizeA = !a.isArray && sizes[a.type!] || 8; let sizeB = !b.isArray && sizes[b.type!] || 8; if (sizeA !== sizeB) return sizeB - sizeA; return fields.indexOf(a) - fields.indexOf(b); // Make sure the sort is stable }); for (let j = 0; j < sortedFields.length; j++) { let field = sortedFields[j]; if (field.isDeprecated) { continue; } let name = cppFieldName(field); let type = cppType(definitions, field, field.isArray); if (cppIsFieldPointer(definitions, field)) { cpp.push(' ' + type + ' *' + name + ' = {};'); } else { cpp.push(' ' + type + ' ' + name + ' = {};'); } } cpp.push('};'); cpp.push(''); } else { for (let j = 0; j < fields.length; j++) { let field = fields[j]; let name = cppFieldName(field); let type = cppType(definitions, field, field.isArray); let flagIndex = cppFlagIndex(j); let flagMask = cppFlagMask(j); if (field.isDeprecated) { continue; } if (cppIsFieldPointer(definitions, field)) { cpp.push(type + ' *' + definition.name + '::' + field.name + '() {'); cpp.push(' return ' + name + ';'); cpp.push('}'); cpp.push(''); cpp.push('const ' + type + ' *' + definition.name + '::' + field.name + '() const {'); cpp.push(' return ' + name + ';'); cpp.push('}'); cpp.push(''); cpp.push('void ' + definition.name + '::set_' + field.name + '(' + type + ' *value) {'); cpp.push(' ' + name + ' = value;'); cpp.push('}'); cpp.push(''); } else if (field.isArray) { cpp.push(type + ' *' + definition.name + '::' + field.name + '() {'); cpp.push(' return _flags[' + flagIndex + '] & ' + flagMask + ' ? &' + name + ' : nullptr;'); cpp.push('}'); cpp.push(''); cpp.push('const ' + type + ' *' + definition.name + '::' + field.name + '() const {'); cpp.push(' return _flags[' + flagIndex + '] & ' + flagMask + ' ? &' + name + ' : nullptr;'); cpp.push('}'); cpp.push(''); cpp.push(type + ' &' + definition.name + '::set_' + field.name + '(kiwi::MemoryPool &pool, uint32_t count) {'); cpp.push(' _flags[' + flagIndex + '] |= ' + flagMask + '; return ' + name + ' = pool.array<' + cppType(definitions, field, false) + '>(count);'); cpp.push('}'); cpp.push(''); } else { cpp.push(type + ' *' + definition.name + '::' + field.name + '() {'); cpp.push(' return _flags[' + flagIndex + '] & ' + flagMask + ' ? &' + name + ' : nullptr;'); cpp.push('}'); cpp.push(''); cpp.push('const ' + type + ' *' + definition.name + '::' + field.name + '() const {'); cpp.push(' return _flags[' + flagIndex + '] & ' + flagMask + ' ? &' + name + ' : nullptr;'); cpp.push('}'); cpp.push(''); cpp.push('void ' + definition.name + '::set_' + field.name + '(const ' + type + ' &value) {'); cpp.push(' _flags[' + flagIndex + '] |= ' + flagMask + '; ' + name + ' = value;'); cpp.push('}'); cpp.push(''); } } cpp.push('bool ' + definition.name + '::encode(kiwi::ByteBuffer &_bb) {'); for (let j = 0; j < fields.length; j++) { let field = fields[j]; if (field.isDeprecated) { continue; } let name = cppFieldName(field); let value = field.isArray ? '_it' : name; let flagIndex = cppFlagIndex(j); let flagMask = cppFlagMask(j); let code; switch (field.type) { case 'bool': { code = '_bb.writeByte(' + value + ');'; break; } case 'byte': { code = '_bb.writeByte(' + value + ');'; break; } case 'int': { code = '_bb.writeVarInt(' + value + ');'; break; } case 'uint': { code = '_bb.writeVarUint(' + value + ');'; break; } case 'float': { code = '_bb.writeVarFloat(' + value + ');'; break; } case 'string': { code = '_bb.writeString(' + value + '.c_str());'; break; } default: { let type = definitions[field.type!]; if (!type) { error('Invalid type ' + quote(field.type!) + ' for field ' + quote(field.name), field.line, field.column); } else if (type.kind === 'ENUM') { code = '_bb.writeVarUint(static_cast<uint32_t>(' + value + '));'; } else { code = 'if (!' + value + (cppIsFieldPointer(definitions, field) ? '->' : '.') + 'encode(_bb)) return false;'; } } } let indent = ' '; if (definition.kind === 'STRUCT') { cpp.push(' if (' + field.name + '() == nullptr) return false;'); } else { cpp.push(' if (' + field.name + '() != nullptr) {'); indent = ' '; } if (definition.kind === 'MESSAGE') { cpp.push(indent + '_bb.writeVarUint(' + field.value + ');'); } if (field.isArray) { cpp.push(indent + '_bb.writeVarUint(' + name + '.size());'); cpp.push(indent + 'for (' + cppType(definitions, field, false) + ' &_it : ' + name + ') ' + code); } else { cpp.push(indent + code); } if (definition.kind !== 'STRUCT') { cpp.push(' }'); } } if (definition.kind === 'MESSAGE') { cpp.push(' _bb.writeVarUint(0);'); } cpp.push(' return true;'); cpp.push('}'); cpp.push(''); cpp.push('bool ' + definition.name + '::decode(kiwi::ByteBuffer &_bb, kiwi::MemoryPool &_pool, const BinarySchema *_schema) {'); for (let j = 0; j < fields.length; j++) { if (fields[j].isArray) { cpp.push(' uint32_t _count;'); break; } } if (definition.kind === 'MESSAGE') { cpp.push(' while (true) {'); cpp.push(' uint32_t _type;'); cpp.push(' if (!_bb.readVarUint(_type)) return false;'); cpp.push(' switch (_type) {'); cpp.push(' case 0:'); cpp.push(' return true;'); } for (let j = 0; j < fields.length; j++) { let field = fields[j]; let name = cppFieldName(field); let value = field.isArray ? '_it' : name; let isPointer = cppIsFieldPointer(definitions, field); let code; switch (field.type) { case 'bool': { code = '_bb.readByte(' + value + ')'; break; } case 'byte': { code = '_bb.readByte(' + value + ')'; break; } case 'int': { code = '_bb.readVarInt(' + value + ')'; break; } case 'uint': { code = '_bb.readVarUint(' + value + ')'; break; } case 'float': { code = '_bb.readVarFloat(' + value + ')'; break; } case 'string': { code = '_bb.readString(' + value + ', _pool)'; break; } default: { let type = definitions[field.type!]; if (!type) { error('Invalid type ' + quote(field.type!) + ' for field ' + quote(field.name), field.line, field.column); } else if (type.kind === 'ENUM') { code = '_bb.readVarUint(reinterpret_cast<uint32_t &>(' + value + '))'; } else { code = value + (isPointer ? '->' : '.') + 'decode(_bb, _pool, _schema)'; } } } let type = cppType(definitions, field, false); let indent = ' '; if (definition.kind === 'MESSAGE') { cpp.push(' case ' + field.value + ': {'); indent = ' '; } if (field.isArray) { cpp.push(indent + 'if (!_bb.readVarUint(_count)) return false;'); if (field.isDeprecated) { cpp.push(indent + 'for (' + type + ' &_it : _pool.array<' + cppType(definitions, field, false) + '>(_count)) if (!' + code + ') return false;'); } else { cpp.push(indent + 'for (' + type + ' &_it : set_' + field.name + '(_pool, _count)) if (!' + code + ') return false;'); } } else { if (field.isDeprecated) { if (isPointer) { cpp.push(indent + type + ' *' + name + ' = _pool.allocate<' + type + '>();'); } else { cpp.push(indent + type + ' ' + name + ' = {};'); } cpp.push(indent + 'if (!' + code + ') return false;'); } else { if (isPointer) { cpp.push(indent + name + ' = _pool.allocate<' + type + '>();'); } cpp.push(indent + 'if (!' + code + ') return false;'); if (!isPointer) { cpp.push(indent + 'set_' + field.name + '(' + name + ');'); } } } if (definition.kind === 'MESSAGE') { cpp.push(' break;'); cpp.push(' }'); } } if (definition.kind === 'MESSAGE') { cpp.push(' default: {'); cpp.push(' if (!_schema || !_schema->skip' + definition.name + 'Field(_bb, _type)) return false;'); cpp.push(' break;'); cpp.push(' }'); cpp.push(' }'); cpp.push(' }'); } else { cpp.push(' return true;'); } cpp.push('}'); cpp.push(''); } } if (pass === 2) { cpp.push('#endif'); cpp.push(''); } else if (newline) cpp.push(''); } if (schema.package !== null) { cpp.push('}'); cpp.push(''); } return cpp.join('\n'); }
the_stack
import * as qpschema from './QuickPulseSchema'; import { QPSchemaConfigurationMetric, QPSchemaDocumentStreamInfo, RequestFieldsEnum, DependencyFieldsEnum } from './QuickPulseSchema'; import axios, { AxiosRequestConfig } from 'axios'; // tslint:disable: max-classes-per-file export function makeQuickPulseId() { let text = ''; let possible = 'abcdefghijklmnopqrstuvwxyz0123456789'; for (let i = 0; i < 32; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; } class QuickPulseSessionInfo { public queryNumber: number; public lastResponse: number; public sessionHeader: string; public seqNumber: number; public aggregatorId: string; public instanceSeqNumber: number; constructor() { this.queryNumber = 0; this.lastResponse = 0; this.sessionHeader = ''; this.seqNumber = 0; this.aggregatorId = ''; this.instanceSeqNumber = 0; } } type WebRequest = { type: 'GET' | 'POST'; url: string; timeout: number; // timeout after 10 seconds - don't need this request anymore headers: { [id: string]: string }; data: any; }; export type QueryResponse = { data: any; status: number; request: any; }; export class QuickPulseQueryLayer { // Indicates that all subsequent request via QuickPulseQueryLayer for this app will fail. public static UNRECOVERABLE_ERROR = 'QuickPulseQueryLayer_UNRECOVERABLE_ERROR'; private _detailedSessionInfo: QuickPulseSessionInfo; private _debugIkey: string; private _endpoint: string; private _queryServersInfo: boolean; private _instanceId: string; private _uniqueId: number; private _client: string; private _id: string; private _configuration: string; private _configurationVersion: number; constructor(endpoint: string, client: string, quickPulseId?: string) { this._endpoint = endpoint; this._detailedSessionInfo = new QuickPulseSessionInfo(); this._debugIkey = ''; this._uniqueId = 0; this._client = client; this._id = quickPulseId || makeQuickPulseId(); this._configurationVersion = 0; } public setDebugIkey(ikey: string) { this._debugIkey = ikey; } // Sets metrics configuration public setConfiguration( metrics: qpschema.QPSchemaConfigurationMetric[], documentStreams: QPSchemaDocumentStreamInfo[], trustedAuthorizedAgents: string[] ) { this._configurationVersion++; let configuration: qpschema.QPSchemaConfigurationSession = { Id: this._id, Version: this._configurationVersion, Metrics: metrics, DocumentStreams: documentStreams, TrustedUnauthorizedAgents: trustedAuthorizedAgents, }; // copy the object for post-processing configuration = JSON.parse(JSON.stringify(configuration)); this.postProcessConfiguration(configuration); this._configuration = JSON.stringify(configuration); } public queryDetails(authorizationHeader: string, querySessionInfo: boolean, instanceId: string) { this._queryServersInfo = querySessionInfo; // If we changed instance view then we need to query all instance documents again. if (instanceId !== this._instanceId) { this._detailedSessionInfo.instanceSeqNumber = 0; this._instanceId = instanceId; } return this.excuteQueryWithSessionTracking(authorizationHeader, this.getDetailedRequest.bind(this), this._detailedSessionInfo); } private async excuteQueryWithSessionTracking( authorizationHeader: string, getRequestFunc: (header1: string, header2: string) => WebRequest, sessionInfo: QuickPulseSessionInfo ): Promise<qpschema.SchemaResponseV2 | null> { let self = this; let queryNumber = ++sessionInfo.queryNumber; let ajaxResult = await this.executeQuery(authorizationHeader, sessionInfo.sessionHeader, getRequestFunc); // Ignore out-of-order responses if (queryNumber <= sessionInfo.lastResponse) { return null; } sessionInfo.lastResponse = queryNumber; sessionInfo.sessionHeader = ajaxResult.request.getResponseHeader('x-ms-qps-query-session'); let dataV2: qpschema.SchemaResponseV2 = ajaxResult.data; // Ignore responses when front end wasn't able to contact backend. // We should switch to different backend soon. if (!dataV2 || !dataV2.DataRanges || dataV2.DataRanges.length === 0 || !dataV2.DataRanges[0].AggregatorId) { return null; } let aggregatorId = dataV2.DataRanges[0].AggregatorId; // Check whether we're still communicating with the same Aggregator instance if (sessionInfo.aggregatorId !== aggregatorId) { // Reset seq number, so we would count all documents sessionInfo.seqNumber = 0; sessionInfo.instanceSeqNumber = 0; // Remember the new aggregator sessionInfo.aggregatorId = aggregatorId; } // Remove extra data ranges if (dataV2.DataRanges.length > 2) { dataV2.DataRanges.splice(2, dataV2.DataRanges.length - 2); } // Remove all documents which we've already seen sessionInfo.seqNumber = self.processDocuments(dataV2.DataRanges[0].Documents, sessionInfo.seqNumber, aggregatorId); if (dataV2.DataRanges.length > 1) { // Check whether we're already looking at different instance if (self._instanceId !== dataV2.DataRanges[1].Instance) { dataV2.DataRanges.splice(1, 1); sessionInfo.instanceSeqNumber = 0; } else { sessionInfo.instanceSeqNumber = self.processDocuments(dataV2.DataRanges[1].Documents, sessionInfo.instanceSeqNumber, aggregatorId); } } return dataV2; } private processDocuments(documents: qpschema.SchemaDocument[], seqNumber: number, aggregatorId: string): number { if (documents && documents.length > 0) { // Find the first one we don't need let index = 0; for (; index < documents.length; ++index) { if (documents[index].SequenceNumber <= seqNumber) { break; } // Assign unique key documents[index].UniqueKey = '' + this._uniqueId; this._uniqueId++; } // Remove already received items if (index < documents.length) { documents.splice(index, documents.length - index + 1); } // Update seqNumber from the first element (first is the latest element) if (index > 0) { seqNumber = documents[0].SequenceNumber; } } return seqNumber; } private async executeQuery( authorizationHeader: string, sessionHeader: string, getRequestFunc: (header1: string, header2: string) => WebRequest ): Promise<QueryResponse> { let request = getRequestFunc(authorizationHeader, sessionHeader); let options: AxiosRequestConfig = { timeout: request.timeout, headers: request.headers, data: request.data, url: request.url, method: request.type, }; let response = await axios.request(options); if (response.headers['x-ms-qps-environment-redirect'] === 'PPE') { throw new Error(QuickPulseQueryLayer.UNRECOVERABLE_ERROR); } else { return { data: response.data, status: response.status, request: response.request }; } } private getDetailedRequest(authorizationHeader: string, sessionHeader: string): WebRequest { let quickPulseEndpointUrl = `${this._endpoint}/query/${this._client}?api-version=2019-11&type=detailed`; if (this._queryServersInfo) { quickPulseEndpointUrl = quickPulseEndpointUrl + '&includeserversinfo=true'; } quickPulseEndpointUrl = quickPulseEndpointUrl + '&SeqNumber=' + this._detailedSessionInfo.seqNumber; if (this._instanceId) { quickPulseEndpointUrl = quickPulseEndpointUrl + '&instanceviewdata=' + this._instanceId; quickPulseEndpointUrl = quickPulseEndpointUrl + '&instanceviewseqnumber=' + this._detailedSessionInfo.instanceSeqNumber; } if (this._debugIkey) { quickPulseEndpointUrl = quickPulseEndpointUrl + '&ikey=' + this._debugIkey; } return { type: 'POST', url: quickPulseEndpointUrl, timeout: 10000, // timeout after 10 seconds - don't need this request anymore headers: { Authorization: authorizationHeader, 'x-ms-qps-query-session': sessionHeader, }, data: this._configuration, }; } private postProcessConfiguration(configuration: qpschema.QPSchemaConfigurationSession): void { if (configuration) { // process metrics for (let metricIndex = 0; metricIndex < configuration.Metrics.length; ++metricIndex) { let metric: QPSchemaConfigurationMetric = configuration.Metrics[metricIndex]; if (metric.FilterGroups) { for (let i = 0; i < metric.FilterGroups.length; ++i) { let filterGroup = metric.FilterGroups[i]; if (filterGroup.Filters) { for (let j = 0; j < filterGroup.Filters.length; ++j) { let filter = filterGroup.Filters[j]; // convert ms -> timespan for durations if (filter.FieldName === RequestFieldsEnum.Duration || filter.FieldName === DependencyFieldsEnum.Duration) { filter.Comparand = QuickPulseQueryLayer.ConvertMillisecondsToTimestamp(filter.Comparand); } } } } } } // process document streams for (let documentStreamIndex = 0; documentStreamIndex < configuration.DocumentStreams.length; ++documentStreamIndex) { let documentStream: QPSchemaDocumentStreamInfo = configuration.DocumentStreams[documentStreamIndex]; if (documentStream.DocumentFilterGroups) { for (let i = 0; i < documentStream.DocumentFilterGroups.length; ++i) { let filterGroup = documentStream.DocumentFilterGroups[i]; if (filterGroup.Filters && filterGroup.Filters.Filters) { for (let j = 0; j < filterGroup.Filters.Filters.length; ++j) { let filter = filterGroup.Filters.Filters[j]; // convert ms -> timespan for durations if (filter.FieldName === RequestFieldsEnum.Duration || filter.FieldName === DependencyFieldsEnum.Duration) { filter.Comparand = QuickPulseQueryLayer.ConvertMillisecondsToTimestamp(filter.Comparand); } } } } } } } } public static ConvertMillisecondsToTimestamp(milliseconds: string): string { let ms: number = parseInt(milliseconds, 10) || 0; let msInADay: number = 86400000; let msInAnHour: number = 3600000; let msInAMinute: number = 60000; let msInASecond: number = 1000; let days: number = Math.floor(ms / msInADay); let hours = Math.floor((ms % msInADay) / msInAnHour); let minutes = Math.floor(((ms % msInADay) % msInAnHour) / msInAMinute); let totalSeconds = (((ms % msInADay) % msInAnHour) % msInAMinute) / msInASecond; return days + '.' + hours + ':' + minutes + ':' + totalSeconds; } }
the_stack
import { Component, ModuleDeclaration, L10n, EmitType, Browser, addClass, removeClass, KeyboardEventArgs } from '@syncfusion/ej2-base'; import { createElement, compile as templateCompiler, EventHandler, extend } from '@syncfusion/ej2-base'; import { isNullOrUndefined } from '@syncfusion/ej2-base'; import { Property, Event, NotifyPropertyChanges, INotifyPropertyChanged } from '@syncfusion/ej2-base'; import { PagerModel } from './pager-model'; import { PagerDropDown } from './pager-dropdown'; import { NumericContainer } from './numeric-container'; import { PagerMessage } from './pager-message'; import { ExternalMessage } from './external-message'; import { appendChildren } from '../grid/base/util'; import * as events from '../grid/base/constant'; /** @hidden */ export interface IRender { render(): void; refresh(): void; } /** * @hidden */ export interface keyPressHandlerKeyboardEventArgs extends KeyboardEvent { cancel?: boolean; } /** * Represents the `Pager` component. * ```html * <div id="pager"/> * ``` * ```typescript * <script> * var pagerObj = new Pager({ totalRecordsCount: 50, pageSize:10 }); * pagerObj.appendTo("#pager"); * </script> * ``` */ @NotifyPropertyChanges export class Pager extends Component<HTMLElement> implements INotifyPropertyChanged { //Internal variables /*** @hidden */ public totalPages: number; /** @hidden */ public templateFn: Function; /** @hidden */ public hasParent: boolean = false; /*** @hidden */ public previousPageNo: number; /** @hidden */ public isAllPage: boolean; private defaultConstants: Object; private pageRefresh: string = 'pager-refresh'; private parent: object; private firstPagerFocus: boolean = false; //Module declarations /*** @hidden */ public localeObj: L10n; /** * `containerModule` is used to manipulate numeric container behavior of Pager. */ public containerModule: NumericContainer; /** * `pagerMessageModule` is used to manipulate pager message of Pager. */ public pagerMessageModule: PagerMessage; /** * `externalMessageModule` is used to manipulate external message of Pager. */ public externalMessageModule: ExternalMessage; /** * @hidden * `pagerdropdownModule` is used to manipulate pageSizes of Pager. */ public pagerdropdownModule: PagerDropDown; //Pager Options /** * If `enableQueryString` set to true, * then it pass current page information as a query string along with the URL while navigating to other page. * * @default false */ @Property(false) public enableQueryString: boolean; /** * If `enableExternalMessage` set to true, then it adds the message to Pager. * * @default false */ @Property(false) public enableExternalMessage: boolean; /** * If `enablePagerMessage` set to true, then it adds the pager information. * * @default true */ @Property(true) public enablePagerMessage: boolean; /** * Defines the records count of visible page. * * @default 12 */ @Property(12) public pageSize: number; /** * Defines the number of pages to display in pager container. * * @default 10 */ @Property(10) public pageCount: number; /** * Defines the current page number of pager. * * @default 1 */ @Property(1) public currentPage: number; /** * Gets or Sets the total records count which is used to render numeric container. * * @default null */ @Property() public totalRecordsCount: number; /** * Defines the external message of Pager. * * @default null */ @Property() public externalMessage: string; /** * If `pageSizes` set to true or Array of values, * It renders DropDownList in the pager which allow us to select pageSize from DropDownList. * * @default false */ @Property(false) public pageSizes: boolean | (number | string)[]; /** * Defines the template as string or HTML element ID which renders customized elements in pager instead of default elements. * * @default null */ @Property() public template: string; /** * Defines the customized text to append with numeric items. * * @default null */ @Property('') public customText: string; /** * Triggers when click on the numeric items. * * @default null */ @Event() public click: EmitType<Object>; /** * Triggers after pageSize is selected in DropDownList. * * @default null */ @Event() public dropDownChanged: EmitType<Object>; /** * Triggers when Pager is created. * * @default null */ @Event() public created: EmitType<Object>; /** * @hidden */ public isReact: boolean; /** * @hidden */ public isVue: boolean; /** * Constructor for creating the component. * * @param {PagerModel} options - specifies the options * @param {string} element - specifies the element * @param {string} parent - specifies the pager parent * @hidden */ constructor(options?: PagerModel, element?: string | HTMLElement, parent?: object) { super(options, <HTMLElement | string>element); this.parent = parent; } /** * To provide the array of modules needed for component rendering * * @returns {ModuleDeclaration[]} returns the modules declaration * @hidden */ protected requiredModules(): ModuleDeclaration[] { const modules: ModuleDeclaration[] = []; if (this.enableExternalMessage) { modules.push({ member: 'externalMessage', args: [this] }); } if (this.checkpagesizes()) { modules.push({ member: 'pagerdropdown', args: [this] }); } return modules; } /** * Initialize the event handler * * @returns {void} * @hidden */ protected preRender(): void { //preRender this.defaultConstants = { currentPageInfo: '{0} of {1} pages', totalItemsInfo: '({0} items)', totalItemInfo: '({0} item)', firstPageTooltip: 'Go to first page', lastPageTooltip: 'Go to last page', nextPageTooltip: 'Go to next page', previousPageTooltip: 'Go to previous page', nextPagerTooltip: 'Go to next pager', previousPagerTooltip: 'Go to previous pager', pagerDropDown: 'Items per page', pagerAllDropDown: 'Items', CurrentPageInfo: '{0} of {1} pages', TotalItemsInfo: '({0} items)', FirstPageTooltip: 'Go to first page', LastPageTooltip: 'Go to last page', NextPageTooltip: 'Go to next page', PreviousPageTooltip: 'Go to previous page', NextPagerTooltip: 'Go to next pager', PreviousPagerTooltip: 'Go to previous pager', PagerDropDown: 'Items per page', PagerAllDropDown: 'Items', All: 'All' }; this.containerModule = new NumericContainer(this); this.pagerMessageModule = new PagerMessage(this); } /** * To Initialize the component rendering * * @returns {void} */ protected render(): void { this.element.setAttribute('data-role', 'pager'); this.element.setAttribute('aria-label', 'Pager Container'); this.element.setAttribute('tabindex', '-1'); if (!this.hasParent) { this.element.setAttribute('tabindex', '0'); } if (this.template) { if (this.isReactTemplate()) { this.on(this.pageRefresh, this.pagerTemplate, this); this.notify(this.pageRefresh, {}); } else { this.pagerTemplate(); } } else { this.initLocalization(); this.updateRTL(); this.totalRecordsCount = this.totalRecordsCount || 0; this.renderFirstPrevDivForDevice(); this.containerModule.render(); if (this.enablePagerMessage) { this.pagerMessageModule.render(); } this.renderNextLastDivForDevice(); if (this.checkpagesizes() && this.pagerdropdownModule) { this.pagerdropdownModule.render(); } this.addAriaLabel(); if (this.enableExternalMessage && this.externalMessageModule) { this.externalMessageModule.render(); } this.refresh(); this.trigger('created', { 'currentPage': this.currentPage, 'totalRecordsCount': this.totalRecordsCount }); } this.wireEvents(); this.addListener(); } /** * Get the properties to be maintained in the persisted state. * * @returns {string} returns the persist data * @hidden */ public getPersistData(): string { const keyEntity: string[] = ['currentPage', 'pageSize']; return this.addOnPersist(keyEntity); } /** * To destroy the Pager component. * * @method destroy * @returns {void} */ public destroy(): void { if (this.isDestroyed) { return; } if (this.isReactTemplate()) { this.off(this.pageRefresh, this.pagerTemplate); if (!this.hasParent) { this.destroyTemplate(['template']); } } this.removeListener(); this.unwireEvents(); super.destroy(); this.containerModule.destroy(); this.pagerMessageModule.destroy(); if (!this.isReactTemplate()) { this.element.innerHTML = ''; } } /** * Destroys the given template reference. * * @param {string[]} propertyNames - Defines the collection of template name. * @param {any} index - Defines the index */ // eslint-disable-next-line public destroyTemplate(propertyNames?: string[], index?: any): void { this.clearTemplate(propertyNames, index); } /** * For internal use only - Get the module name. * * @returns {string} returns the module name * @private */ protected getModuleName(): string { return 'pager'; } /** * Called internally if any of the property value changed. * * @param {PagerModel} newProp - specifies the new property * @param {PagerModel} oldProp - specifies the old propety * @returns {void} * @hidden */ public onPropertyChanged(newProp: PagerModel, oldProp: PagerModel): void { if (this.isDestroyed) { return; } if (newProp.pageCount !== oldProp.pageCount) { this.containerModule.refreshNumericLinks(); this.containerModule.refresh(); } for (const prop of Object.keys(newProp)) { switch (prop) { case 'currentPage': if (this.checkGoToPage(newProp.currentPage, oldProp.currentPage)) { this.currentPageChanged(newProp, oldProp); } break; case 'pageSize': case 'totalRecordsCount': case 'customText': if (this.checkpagesizes() && this.pagerdropdownModule) { if (oldProp.pageSize !== newProp.pageSize) { this.currentPage = 1; } this.pagerdropdownModule.setDropDownValue('value', this.pageSize); } if (newProp.pageSize !== oldProp.pageSize) { this.pageSize = newProp.pageSize; this.currentPageChanged(newProp, oldProp); } else { this.refresh(); } break; case 'pageSizes': if (this.checkpagesizes() && this.pagerdropdownModule) { this.pagerdropdownModule.destroy(); this.pagerdropdownModule.render(); } this.refresh(); break; case 'template': this.templateFn = this.compile(this.template); this.refresh(); break; case 'locale': this.initLocalization(); this.refresh(); break; case 'enableExternalMessage': if (this.enableExternalMessage && this.externalMessageModule) { this.externalMessageModule.render(); } break; case 'externalMessage': if (this.externalMessageModule) { this.externalMessageModule.refresh(); } break; case 'enableRtl': this.updateRTL(); break; case 'enablePagerMessage': if (this.enablePagerMessage) { this.pagerMessageModule.showMessage(); } else { this.pagerMessageModule.hideMessage(); } break; } } } private wireEvents(): void { if (!this.hasParent) { EventHandler.add(this.element, 'keydown', this.keyPressHandler, this); EventHandler.add(document.body, 'keydown', this.keyDownHandler, this); } EventHandler.add(this.element, 'focusin', this.onFocusIn, this); EventHandler.add(this.element, 'focusout', this.onFocusOut, this); } private unwireEvents(): void { if (!this.hasParent) { EventHandler.remove(this.element, 'keydown', this.keyPressHandler); EventHandler.remove(document.body, 'keydown', this.keyDownHandler); } EventHandler.remove(this.element, 'focusin', this.onFocusIn); EventHandler.remove(this.element, 'focusout', this.onFocusOut); } private onFocusIn(e: FocusEvent): void { const focusedTabIndexElement: Element = this.getFocusedTabindexElement(); if (isNullOrUndefined(focusedTabIndexElement)) { const target: Element = e.target as Element; const dropDownPage: Element = this.getDropDownPage(); if (!this.hasParent) { this.element.tabIndex = -1; } if (target === this.element && !this.hasParent) { const focusablePagerElements: Element[] = this.getFocusablePagerElements(this.element, []); this.addFocus(focusablePagerElements[0], true); return; } if (target === this.element) { this.element.tabIndex = 0; return; } if (target !== dropDownPage && !target.classList.contains('e-disable')) { this.addFocus(target, true); } } } private onFocusOut(e: FocusEvent): void { const focusedElement: Element = this.getFocusedElement(); const dropDownPage: Element = this.getDropDownPage(); if (!isNullOrUndefined(focusedElement)) { this.removeFocus(focusedElement, true); } if (this.pageSizes && dropDownPage && dropDownPage.classList.contains('e-input-focus')) { this.removeFocus(dropDownPage, true); } this.setTabIndexForFocusLastElement(); if (!this.hasParent) { this.element.tabIndex = 0; } if (this.hasParent) { this.element.tabIndex = -1; } } private keyDownHandler(e: KeyboardEventArgs): void { if (e.altKey) { if (e.keyCode === 74) { const focusablePagerElements: Element[] = this.getFocusablePagerElements(this.element, []); if (focusablePagerElements.length > 0) { (focusablePagerElements[0] as HTMLElement).focus(); } } } } private keyPressHandler(e: keyPressHandlerKeyboardEventArgs): void { const presskey: keyPressHandlerKeyboardEventArgs = <keyPressHandlerKeyboardEventArgs>extend(e, { cancel: false }); this.notify(events.keyPressed, presskey); if (presskey.cancel === true) { e.stopImmediatePropagation(); } } private addListener(): void { if (this.isDestroyed) { return; } if (!this.hasParent) { this.on(events.keyPressed, this.onKeyPress, this); } } private removeListener(): void { if (this.isDestroyed) { return; } if (!this.hasParent) { this.off(events.keyPressed, this.onKeyPress); } } private onKeyPress(e: KeyboardEventArgs): void { if (!this.hasParent) { if (this.checkPagerHasFocus()) { this.changePagerFocus(e); } else { e.preventDefault(); this.setPagerFocus(); } } } /** * @returns {boolean} - Return the true value if pager has focus * @hidden */ public checkPagerHasFocus(): boolean { return this.getFocusedTabindexElement() ? true : false; } /** * @returns {void} * @hidden */ public setPagerContainerFocus(): void { (this.element as HTMLElement).focus(); } /** * @returns {void} * @hidden */ public setPagerFocus(): void { const focusablePagerElements: Element[] = this.getFocusablePagerElements(this.element, []); if (focusablePagerElements.length > 0) { (focusablePagerElements[0] as HTMLElement).focus(); } } private setPagerFocusForActiveElement(): void { const currentActivePage: Element = this.getActiveElement(); if (currentActivePage) { (currentActivePage as HTMLElement).focus(); } } private setTabIndexForFocusLastElement(): void { const focusablePagerElements: Element[] = this.getFocusablePagerElements(this.element, []); const dropDownPage: Element = this.getDropDownPage(); if (this.pageSizes && dropDownPage && !isNullOrUndefined((dropDownPage as HTMLElement).offsetParent)) { (dropDownPage as HTMLElement).tabIndex = 0; } else if (focusablePagerElements.length > 0) { (focusablePagerElements[focusablePagerElements.length - 1] as HTMLElement).tabIndex = 0; } } /** * @param {KeyboardEventArgs} e - Keyboard Event Args * @returns {void} * @hidden */ public changePagerFocus(e: KeyboardEventArgs): void { if (e.shiftKey && e.keyCode === 9) { this.changeFocusByShiftTab(e); } else if (e.keyCode === 9) { this.changeFocusByTab(e); } else if (e.keyCode === 13 || e.keyCode === 32) { this.navigateToPageByEnterOrSpace(e); } else if (e.keyCode === 37 || e.keyCode === 39 || e.keyCode === 35 || e.keyCode === 36) { this.navigateToPageByKey(e); } } private getFocusedTabindexElement(): Element { let focusedTabIndexElement: Element; const tabindexElements: NodeListOf<Element> = this.element.querySelectorAll('[tabindex]:not([tabindex="-1"])'); for ( let i: number = 0; i < tabindexElements.length; i++) { const element: Element = tabindexElements[i]; if (element && (element.classList.contains('e-focused') || element.classList.contains('e-input-focus'))) { focusedTabIndexElement = element; break; } } return focusedTabIndexElement; } private changeFocusByTab(e: KeyboardEventArgs): void { const currentItemPagerFocus: Element = this.getFocusedTabindexElement(); const focusablePagerElements: Element[] = this.getFocusablePagerElements(this.element, []); const dropDownPage: Element = this.getDropDownPage(); if (focusablePagerElements.length > 0) { if (this.pageSizes && dropDownPage && currentItemPagerFocus === focusablePagerElements[focusablePagerElements.length - 1]) { (dropDownPage as HTMLElement).tabIndex = 0; } else { for (let i: number = 0; i < focusablePagerElements.length; i++) { if (currentItemPagerFocus === focusablePagerElements[i]) { const incrementNumber: number = i + 1; if (incrementNumber < focusablePagerElements.length) { e.preventDefault(); (focusablePagerElements[incrementNumber] as HTMLElement).focus(); } break; } } } } } private changeFocusByShiftTab(e: KeyboardEventArgs): void { const currentItemPagerFocus: Element = this.getFocusedTabindexElement(); const focusablePagerElements: Element[] = this.getFocusablePagerElements(this.element, []); const dropDownPage: Element = this.getDropDownPage(); if (this.pageSizes && dropDownPage && dropDownPage.classList.contains('e-input-focus')) { (dropDownPage as HTMLElement).tabIndex = -1; this.addFocus(focusablePagerElements[focusablePagerElements.length - 1], true); } else if (focusablePagerElements.length > 0) { for (let i: number = 0; i < focusablePagerElements.length; i++) { if (currentItemPagerFocus === focusablePagerElements[i]) { const decrementNumber: number = i - 1; if (decrementNumber >= 0) { e.preventDefault(); (focusablePagerElements[decrementNumber] as HTMLElement).focus(); } else if (this.hasParent) { const rows: Element[] = (this.parent as {getRows(): Element[]}).getRows(); const lastRow: Element = rows[rows.length - 1]; const lastCell: Element = lastRow.lastChild as Element; e.preventDefault(); (lastCell as HTMLElement).focus(); this.firstPagerFocus = true; } break; } } } } /** * @returns {void} * @hidden */ public checkFirstPagerFocus(): boolean { if (this.firstPagerFocus) { this.firstPagerFocus = false; return true; } return false; } private navigateToPageByEnterOrSpace(e: KeyboardEventArgs): void { const currentItemPagerFocus: Element = this.getFocusedElement(); if (currentItemPagerFocus) { this.goToPage(parseInt(currentItemPagerFocus.getAttribute('index'), 10)); const currentActivePage: Element = this.getActiveElement(); const selectedClass: string = this.getClass(currentItemPagerFocus); const classElement: Element = this.getElementByClass(selectedClass); if ((selectedClass === 'e-first' || selectedClass === 'e-prev' || selectedClass === 'e-next' || selectedClass === 'e-last' || selectedClass === 'e-pp' || selectedClass === 'e-np') && classElement && !classElement.classList.contains('e-disable')) { (classElement as HTMLElement).focus(); } else if (this.checkFocusInAdaptiveMode(currentItemPagerFocus)) { this.changeFocusInAdaptiveMode(currentItemPagerFocus); } else { if (currentActivePage) { (currentActivePage as HTMLElement).focus(); } } } } private navigateToPageByKey(e: KeyboardEventArgs): void { const actionClass: string = e.keyCode === 37 ? '.e-prev' : e.keyCode === 39 ? '.e-next' : e.keyCode === 35 ? '.e-last' : e.keyCode === 36 ? '.e-first' : ''; const pagingItem: Element = this.element.querySelector(actionClass); const currentItemPagerFocus: Element = this.getFocusedElement(); if (!isNullOrUndefined(pagingItem) && pagingItem.hasAttribute('index') && !isNaN(parseInt(pagingItem.getAttribute('index'), 10))) { this.goToPage(parseInt(pagingItem.getAttribute('index'), 10)); const currentActivePage: Element = this.getActiveElement(); if (this.checkFocusInAdaptiveMode(currentItemPagerFocus)) { this.changeFocusInAdaptiveMode(currentItemPagerFocus); } else { if (currentActivePage) { (currentActivePage as HTMLElement).focus(); } } } } private checkFocusInAdaptiveMode(element: Element): boolean { const selectedClass: string = this.getClass(element); return selectedClass === 'e-mfirst' || selectedClass === 'e-mprev' || selectedClass === 'e-mnext' || selectedClass === 'e-mlast' ? true : false; } private changeFocusInAdaptiveMode(element: Element): void { const selectedClass: string = this.getClass(element); const classElement: Element = this.getElementByClass(selectedClass); if (classElement && classElement.classList.contains('e-disable')) { if (selectedClass === 'e-mnext' || selectedClass === 'e-mlast') { const mPrev: Element = this.element.querySelector('.e-mprev'); (mPrev as HTMLElement).focus(); } else { this.setPagerFocus(); } } } private removeTabindexLastElements(): void { const tabIndexElements: NodeListOf<Element> = this.element.querySelectorAll('[tabindex]:not([tabindex="-1"])'); if (tabIndexElements.length > 1) { for ( let i: number = 1; i < tabIndexElements.length; i++) { const element: Element = tabIndexElements[i]; if (element) { (element as HTMLElement).tabIndex = -1; } } } } private getActiveElement(): Element { return this.element.querySelector('.e-active'); } private getDropDownPage(): Element { const dropDownPageHolder: Element = this.element.querySelector('.e-pagerdropdown'); let dropDownPage: Element; if (dropDownPageHolder) { dropDownPage = dropDownPageHolder.children[0]; } return dropDownPage; } private getFocusedElement(): Element { return this.element.querySelector('.e-focused'); } private getClass(element: Element): string { let currentClass: string; const classList: string[] = ['e-mfirst', 'e-mprev', 'e-first', 'e-prev', 'e-pp', 'e-np', 'e-next', 'e-last', 'e-mnext', 'e-mlast']; for ( let i: number = 0; i < classList.length; i++) { if (element && element.classList.contains(classList[i])) { currentClass = classList[i]; return currentClass; } } return currentClass; } private getElementByClass(className: string): Element { return this.element.querySelector('.' + className); } private getFocusablePagerElements(element: Element, previousElements: Element[]): Element[] { const target: Element = element; const targetChildrens: HTMLCollection = target.children; let pagerElements: Element[] = previousElements; for (let i: number = 0; i < targetChildrens.length; i++) { const element: Element = targetChildrens[i]; if (element.children.length > 0 && !element.classList.contains('e-pagesizes')) { pagerElements = this.getFocusablePagerElements(element, pagerElements); } else { const tabindexElement: Element = targetChildrens[i]; if (tabindexElement.hasAttribute('tabindex') && !element.classList.contains('e-disable') && (element as HTMLElement).style.display !== 'none' && !isNullOrUndefined((element as HTMLElement).offsetParent)){ pagerElements.push(tabindexElement); } } } return pagerElements; } private addFocus(element: Element, addFocusClass: boolean): void { if (addFocusClass) { addClass([element], ['e-focused', 'e-focus']); } (element as HTMLElement).tabIndex = 0; } private removeFocus(element: Element, removeFocusClass: boolean): void { if (removeFocusClass) { removeClass([element], ['e-focused', 'e-focus']); } (element as HTMLElement).tabIndex = -1; } /** * Gets the localized label by locale keyword. * * @param {string} key - specifies the key * @returns {string} returns the localized label */ public getLocalizedLabel(key: string): string { return this.localeObj.getConstant(key); } /** * Navigate to target page by given number. * * @param {number} pageNo - Defines page number. * @returns {void} */ public goToPage(pageNo: number): void { if (this.checkGoToPage(pageNo)) { this.currentPage = pageNo; this.dataBind(); } } /** * @param {number} pageSize - specifies the pagesize * @returns {void} * @hidden */ public setPageSize(pageSize: number): void { this.pageSize = pageSize; this.dataBind(); } private checkpagesizes(): boolean { if (this.pageSizes === true || (<number[]>this.pageSizes).length) { return true; } return false; } private checkGoToPage(newPageNo: number, oldPageNo?: number): boolean { if (newPageNo !== this.currentPage) { this.previousPageNo = this.currentPage; } if (!isNullOrUndefined(oldPageNo)) { this.previousPageNo = oldPageNo; } if (this.previousPageNo !== newPageNo && (newPageNo >= 1 && newPageNo <= this.totalPages)) { return true; } return false; } private currentPageChanged(newProp: PagerModel, oldProp: PagerModel): void { if (this.enableQueryString) { this.updateQueryString(this.currentPage); } if (newProp.currentPage !== oldProp.currentPage || newProp.pageSize !== oldProp.pageSize) { const args: { currentPage: number, newProp: PagerModel, oldProp: PagerModel, cancel: boolean } = { currentPage: this.currentPage, newProp: newProp, oldProp: oldProp, cancel: false }; this.trigger('click', args); if (!args.cancel) { this.refresh(); } } } private pagerTemplate(): void { if (this.isReactTemplate() && this.hasParent) { return; } let result: Element[]; this.element.classList.add('e-pagertemplate'); this.compile(this.template); const data: object = { currentPage: this.currentPage, pageSize: this.pageSize, pageCount: this.pageCount, totalRecordsCount: this.totalRecordsCount, totalPages: this.totalPages }; const tempId: string = this.element.parentElement.id + '_template'; if (this.isReactTemplate() && !this.isVue) { this.getPagerTemplate()(data, this, 'template', tempId, null, null, this.element); this.renderReactTemplates(); } else { result = this.isVue ? this.getPagerTemplate()(data, this, 'template') as Element[] : this.getPagerTemplate()(data); appendChildren(this.element, result); } } /** * @returns {void} * @hidden */ public updateTotalPages(): void { this.totalPages = this.isAllPage ? 1 : (this.totalRecordsCount % this.pageSize === 0) ? (this.totalRecordsCount / this.pageSize) : (parseInt((this.totalRecordsCount / this.pageSize).toString(), 10) + 1); } /** * @returns {Function} returns the function * @hidden */ public getPagerTemplate(): Function { return this.templateFn; } /** * @param {string} template - specifies the template * @returns {Function} returns the function * @hidden */ public compile(template: string): Function { if (template) { try { if (document.querySelectorAll(template).length) { this.templateFn = templateCompiler(document.querySelector(template).innerHTML.trim()); } } catch (e) { this.templateFn = templateCompiler(template); } } return undefined; } /** * Refreshes page count, pager information and external message. * * @returns {void} */ public refresh(): void { if (this.template) { if (this.isReactTemplate()) { this.updateTotalPages(); this.notify(this.pageRefresh, {}); } else { this.element.innerHTML = ''; this.updateTotalPages(); this.pagerTemplate(); } } else { this.updateRTL(); const focusedTabIndexElement: Element = this.getFocusedTabindexElement(); this.containerModule.refresh(); this.removeTabindexLastElements(); if (focusedTabIndexElement && focusedTabIndexElement.classList.contains('e-disable')) { if (this.checkFocusInAdaptiveMode(focusedTabIndexElement)) { this.changeFocusInAdaptiveMode(focusedTabIndexElement); } else { this.setPagerFocusForActiveElement(); } } if (this.enablePagerMessage) { this.pagerMessageModule.refresh(); } if (this.pagerdropdownModule) { this.pagerdropdownModule.refresh(); } if (this.enableExternalMessage && this.externalMessageModule) { this.externalMessageModule.refresh(); } this.setTabIndexForFocusLastElement(); } } private updateRTL(): void { if (this.enableRtl) { this.element.classList.add('e-rtl'); } else { this.element.classList.remove('e-rtl'); } } private initLocalization(): void { this.localeObj = new L10n(this.getModuleName(), this.defaultConstants, this.locale); } private updateQueryString(value: number): void { const updatedUrl: string = this.getUpdatedURL(window.location.href, 'page', value.toString()); window.history.pushState({ path: updatedUrl }, '', updatedUrl); } private getUpdatedURL(uri: string, key: string, value: string): string { const regx: RegExp = new RegExp('([?|&])' + key + '=.*?(&|#|$)', 'i'); if (uri.match(regx)) { return uri.replace(regx, '$1' + key + '=' + value + '$2'); } else { let hash: string = ''; if (uri.indexOf('#') !== -1) { hash = uri.replace(/.*#/, '#'); uri = uri.replace(/#.*/, ''); } return uri + (uri.indexOf('?') !== -1 ? '&' : '?') + key + '=' + value + hash; } } private renderFirstPrevDivForDevice(): void { this.element.appendChild(createElement( 'div', { className: 'e-mfirst e-icons e-icon-first', attrs: { title: this.getLocalizedLabel('firstPageTooltip'), tabindex: '-1' } })); this.element.appendChild(createElement( 'div', { className: 'e-mprev e-icons e-icon-prev', attrs: { title: this.getLocalizedLabel('previousPageTooltip'), tabindex: '-1' } })); } private renderNextLastDivForDevice(): void { this.element.appendChild(createElement( 'div', { className: 'e-mnext e-icons e-icon-next', attrs: { title: this.getLocalizedLabel('nextPageTooltip'), tabindex: '-1' } })); this.element.appendChild(createElement( 'div', { className: 'e-mlast e-icons e-icon-last', attrs: { title: this.getLocalizedLabel('lastPageTooltip'), tabindex: '-1' } })); } private addAriaLabel(): void { const classList: string[] = ['.e-mfirst', '.e-mprev', '.e-mnext', '.e-mlast']; if (!Browser.isDevice) { for (let i: number = 0; i < classList.length; i++) { const element: Element = this.element.querySelector(classList[i]); element.setAttribute('aria-label', element.getAttribute('title')); } } } private isReactTemplate(): boolean { return (this.isReact || this.isVue) && this.template && typeof (this.template) !== 'string'; } }
the_stack
import { randomBytes, createHash } from "crypto"; import { EventEmitter } from "events"; // AbortController became available as a global in node version 16. Once version // 14 reaches its end-of-life, this can be removed. import PolyfillAbortController from "node-abort-controller"; import { Redis as IORedisClient } from "ioredis"; type Client = IORedisClient; // Define script constants. const ACQUIRE_SCRIPT = ` -- Return 0 if an entry already exists. for i, key in ipairs(KEYS) do if redis.call("exists", key) == 1 then return 0 end end -- Create an entry for each provided key. for i, key in ipairs(KEYS) do redis.call("set", key, ARGV[1], "PX", ARGV[2]) end -- Return the number of entries added. return #KEYS `; const EXTEND_SCRIPT = ` -- Return 0 if an entry exists with a *different* lock value. for i, key in ipairs(KEYS) do if redis.call("get", key) ~= ARGV[1] then return 0 end end -- Update the entry for each provided key. for i, key in ipairs(KEYS) do redis.call("set", key, ARGV[1], "PX", ARGV[2]) end -- Return the number of entries updated. return #KEYS `; const RELEASE_SCRIPT = ` local count = 0 for i, key in ipairs(KEYS) do -- Only remove entries for *this* lock value. if redis.call("get", key) == ARGV[1] then redis.pcall("del", key) count = count + 1 end end -- Return the number of entries removed. return count `; export type ClientExecutionResult = | { client: Client; vote: "for"; value: number; } | { client: Client; vote: "against"; error: Error; }; /* * This object contains a summary of results. */ export type ExecutionStats = { readonly membershipSize: number; readonly quorumSize: number; readonly votesFor: Set<Client>; readonly votesAgainst: Map<Client, Error>; }; /* * This object contains a summary of results. Because the result of an attempt * can sometimes be determined before all requests are finished, each attempt * contains a Promise that will resolve ExecutionStats once all requests are * finished. A rejection of these promises should be considered undefined * behavior and should cause a crash. */ export type ExecutionResult = { attempts: ReadonlyArray<Promise<ExecutionStats>>; }; /** * */ export interface Settings { readonly driftFactor: number; readonly retryCount: number; readonly retryDelay: number; readonly retryJitter: number; readonly automaticExtensionThreshold: number; } // Define default settings. const defaultSettings: Readonly<Settings> = { driftFactor: 0.01, retryCount: 10, retryDelay: 200, retryJitter: 100, automaticExtensionThreshold: 500, }; // Modifyng this object is forbidden. Object.freeze(defaultSettings); /* * This error indicates a failure due to the existence of another lock for one * or more of the requested resources. */ export class ResourceLockedError extends Error { constructor(public readonly message: string) { super(); this.name = "ResourceLockedError"; } } /* * This error indicates a failure of an operation to pass with a quorum. */ export class ExecutionError extends Error { constructor( public readonly message: string, public readonly attempts: ReadonlyArray<Promise<ExecutionStats>> ) { super(); this.name = "ExecutionError"; } } /* * An object of this type is returned when a resource is successfully locked. It * contains convenience methods `release` and `extend` which perform the * associated Redlock method on itself. */ export class Lock { constructor( public readonly redlock: Redlock, public readonly resources: string[], public readonly value: string, public readonly attempts: ReadonlyArray<Promise<ExecutionStats>>, public expiration: number ) {} async release(): Promise<ExecutionResult> { return this.redlock.release(this); } async extend(duration: number): Promise<Lock> { return this.redlock.extend(this, duration); } } type RedlockAbortSignal = AbortSignal & { error?: Error }; /** * A redlock object is instantiated with an array of at least one redis client * and an optional `options` object. Properties of the Redlock object should NOT * be changed after it is first used, as doing so could have unintended * consequences for live locks. */ export default class Redlock extends EventEmitter { public readonly clients: Set<Client>; public readonly settings: Settings; public readonly scripts: { readonly acquireScript: { value: string; hash: string }; readonly extendScript: { value: string; hash: string }; readonly releaseScript: { value: string; hash: string }; }; public constructor( clients: Iterable<Client>, settings: Partial<Settings> = {}, scripts: { readonly acquireScript?: string | ((script: string) => string); readonly extendScript?: string | ((script: string) => string); readonly releaseScript?: string | ((script: string) => string); } = {} ) { super(); // Prevent crashes on error events. this.on("error", () => { // Because redlock is designed for high availability, it does not care if // a minority of redis instances/clusters fail at an operation. // // However, it can be helpful to monitor and log such cases. Redlock emits // an "error" event whenever it encounters an error, even if the error is // ignored in its normal operation. // // This function serves to prevent node's default behavior of crashing // when an "error" event is emitted in the absence of listeners. }); // Create a new array of client, to ensure no accidental mutation. this.clients = new Set(clients); if (this.clients.size === 0) { throw new Error( "Redlock must be instantiated with at least one redis client." ); } // Customize the settings for this instance. this.settings = { driftFactor: typeof settings.driftFactor === "number" ? settings.driftFactor : defaultSettings.driftFactor, retryCount: typeof settings.retryCount === "number" ? settings.retryCount : defaultSettings.retryCount, retryDelay: typeof settings.retryDelay === "number" ? settings.retryDelay : defaultSettings.retryDelay, retryJitter: typeof settings.retryJitter === "number" ? settings.retryJitter : defaultSettings.retryJitter, automaticExtensionThreshold: typeof settings.automaticExtensionThreshold === "number" ? settings.automaticExtensionThreshold : defaultSettings.automaticExtensionThreshold, }; // Use custom scripts and script modifiers. const acquireScript = typeof scripts.acquireScript === "function" ? scripts.acquireScript(ACQUIRE_SCRIPT) : ACQUIRE_SCRIPT; const extendScript = typeof scripts.extendScript === "function" ? scripts.extendScript(EXTEND_SCRIPT) : EXTEND_SCRIPT; const releaseScript = typeof scripts.releaseScript === "function" ? scripts.releaseScript(RELEASE_SCRIPT) : RELEASE_SCRIPT; this.scripts = { acquireScript: { value: acquireScript, hash: this._hash(acquireScript), }, extendScript: { value: extendScript, hash: this._hash(extendScript), }, releaseScript: { value: releaseScript, hash: this._hash(releaseScript), }, }; } /** * Generate a sha1 hash compatible with redis evalsha. */ private _hash(value: string): string { return createHash("sha1").update(value).digest("hex"); } /** * Generate a cryptographically random string. */ private _random(): string { return randomBytes(16).toString("hex"); } /** * This method runs `.quit()` on all client connections. */ public async quit(): Promise<void> { const results = []; for (const client of this.clients) { results.push(client.quit()); } await Promise.all(results); } /** * This method acquires a locks on the resources for the duration specified by * the `duration`. */ public async acquire( resources: string[], duration: number, settings?: Settings ): Promise<Lock> { const start = Date.now(); const value = this._random(); try { const { attempts } = await this._execute( this.scripts.acquireScript, resources, [value, duration], settings ); // Add 2 milliseconds to the drift to account for Redis expires precision, // which is 1 ms, plus the configured allowable drift factor. const drift = Math.round( (settings?.driftFactor ?? this.settings.driftFactor) * duration ) + 2; return new Lock( this, resources, value, attempts, start + duration - drift ); } catch (error) { // If there was an error acquiring the lock, release any partial lock // state that may exist on a minority of clients. await this._execute(this.scripts.releaseScript, resources, [value], { retryCount: 0, }).catch(() => { // Any error here will be ignored. }); throw error; } } /** * This method unlocks the provided lock from all servers still persisting it. * It will fail with an error if it is unable to release the lock on a quorum * of nodes, but will make no attempt to restore the lock in the case of a * failure to release. It is safe to re-attempt a release or to ignore the * error, as the lock will automatically expire after its timeout. */ public async release( lock: Lock, settings?: Partial<Settings> ): Promise<ExecutionResult> { // Immediately invalidate the lock. lock.expiration = 0; // Attempt to release the lock. return this._execute( this.scripts.releaseScript, lock.resources, [lock.value], settings ); } /** * This method extends a valid lock by the provided `duration`. */ public async extend( existing: Lock, duration: number, settings?: Partial<Settings> ): Promise<Lock> { const start = Date.now(); // The lock has already expired. if (existing.expiration < Date.now()) { throw new ExecutionError("Cannot extend an already-expired lock.", []); } const { attempts } = await this._execute( this.scripts.extendScript, existing.resources, [existing.value, duration], settings ); // Invalidate the existing lock. existing.expiration = 0; // Add 2 milliseconds to the drift to account for Redis expires precision, // which is 1 ms, plus the configured allowable drift factor. const drift = Math.round( (settings?.driftFactor ?? this.settings.driftFactor) * duration ) + 2; const replacement = new Lock( this, existing.resources, existing.value, attempts, start + duration - drift ); return replacement; } /** * Execute a script on all clients. The resulting promise is resolved or * rejected as soon as this quorum is reached; the resolution or rejection * will contains a `stats` property that is resolved once all votes are in. */ private async _execute( script: { value: string; hash: string }, keys: string[], args: (string | number)[], _settings?: Partial<Settings> ): Promise<ExecutionResult> { const settings = _settings ? { ...this.settings, ..._settings, } : this.settings; const maxAttempts = settings.retryCount + 1; const attempts: Promise<ExecutionStats>[] = []; while (true) { const { vote, stats } = await this._attemptOperation(script, keys, args); attempts.push(stats); // The operation acheived a quorum in favor. if (vote === "for") { return { attempts }; } // Wait before reattempting. if (attempts.length < maxAttempts) { await new Promise((resolve) => { setTimeout( resolve, Math.max( 0, settings.retryDelay + Math.floor((Math.random() * 2 - 1) * settings.retryJitter) ), undefined ); }); } else { throw new ExecutionError( "The operation was unable to acheive a quorum during its retry window.", attempts ); } } } private async _attemptOperation( script: { value: string; hash: string }, keys: string[], args: (string | number)[] ): Promise< | { vote: "for"; stats: Promise<ExecutionStats> } | { vote: "against"; stats: Promise<ExecutionStats> } > { return await new Promise((resolve) => { const clientResults = []; for (const client of this.clients) { clientResults.push( this._attemptOperationOnClient(client, script, keys, args) ); } const stats: ExecutionStats = { membershipSize: clientResults.length, quorumSize: Math.floor(clientResults.length / 2) + 1, votesFor: new Set<Client>(), votesAgainst: new Map<Client, Error>(), }; let done: () => void; const statsPromise = new Promise<typeof stats>((resolve) => { done = () => resolve(stats); }); // This is the expected flow for all successful and unsuccessful requests. const onResultResolve = (clientResult: ClientExecutionResult): void => { switch (clientResult.vote) { case "for": stats.votesFor.add(clientResult.client); break; case "against": stats.votesAgainst.set(clientResult.client, clientResult.error); break; } // A quorum has determined a success. if (stats.votesFor.size === stats.quorumSize) { resolve({ vote: "for", stats: statsPromise, }); } // A quorum has determined a failure. if (stats.votesAgainst.size === stats.quorumSize) { resolve({ vote: "against", stats: statsPromise, }); } // All votes are in. if ( stats.votesFor.size + stats.votesAgainst.size === stats.membershipSize ) { done(); } }; // This is unexpected and should crash to prevent undefined behavior. const onResultReject = (error: Error): void => { throw error; }; for (const result of clientResults) { result.then(onResultResolve, onResultReject); } }); } private async _attemptOperationOnClient( client: Client, script: { value: string; hash: string }, keys: string[], args: (string | number)[] ): Promise<ClientExecutionResult> { try { let result: number; try { // Attempt to evaluate the script by its hash. const shaResult = (await client.evalsha(script.hash, keys.length, [ ...keys, ...args, ])) as unknown; if (typeof shaResult !== "number") { throw new Error( `Unexpected result of type ${typeof shaResult} returned from redis.` ); } result = shaResult; } catch (error) { // If the redis server does not already have the script cached, // reattempt the request with the script's raw text. if ( !(error instanceof Error) || !error.message.startsWith("NOSCRIPT") ) { throw error; } const rawResult = (await client.eval(script.value, keys.length, [ ...keys, ...args, ])) as unknown; if (typeof rawResult !== "number") { throw new Error( `Unexpected result of type ${typeof rawResult} returned from redis.` ); } result = rawResult; } // One or more of the resources was already locked. if (result !== keys.length) { throw new ResourceLockedError( `The operation was applied to: ${result} of the ${keys.length} requested resources.` ); } return { vote: "for", client, value: result, }; } catch (error) { if (!(error instanceof Error)) { throw new Error( `Unexpected type ${typeof error} thrown with value: ${error}` ); } // Emit the error on the redlock instance for observability. this.emit("error", error); return { vote: "against", client, error, }; } } /** * Wrap and execute a routine in the context of an auto-extending lock, * returning a promise of the routine's value. In the case that auto-extension * fails, an AbortSignal will be updated to indicate that abortion of the * routine is in order, and to pass along the encountered error. * * @example * ```ts * await redlock.using([senderId, recipientId], 5000, { retryCount: 5 }, async (signal) => { * const senderBalance = await getBalance(senderId); * const recipientBalance = await getBalance(recipientId); * * if (senderBalance < amountToSend) { * throw new Error("Insufficient balance."); * } * * // The abort signal will be true if: * // 1. the above took long enough that the lock needed to be extended * // 2. redlock was unable to extend the lock * // * // In such a case, exclusivity can no longer be guaranteed for further * // operations, and should be handled as an exceptional case. * if (signal.aborted) { * throw signal.error; * } * * await setBalances([ * {id: senderId, balance: senderBalance - amountToSend}, * {id: recipientId, balance: recipientBalance + amountToSend}, * ]); * }); * ``` */ public async using<T>( resources: string[], duration: number, settings: Partial<Settings>, routine?: (signal: RedlockAbortSignal) => T ): Promise<T>; public async using<T>( resources: string[], duration: number, routine: (signal: RedlockAbortSignal) => T ): Promise<T>; public async using<T>( resources: string[], duration: number, settingsOrRoutine: | undefined | Partial<Settings> | ((signal: RedlockAbortSignal) => T), optionalRoutine?: (signal: RedlockAbortSignal) => T ): Promise<T> { const settings = settingsOrRoutine && typeof settingsOrRoutine !== "function" ? { ...this.settings, ...settingsOrRoutine, } : this.settings; const routine = optionalRoutine ?? settingsOrRoutine; if (typeof routine !== "function") { throw new Error("INVARIANT: routine is not a function."); } if (settings.automaticExtensionThreshold > duration - 100) { throw new Error( "A lock `duration` must be at least 100ms greater than the `automaticExtensionThreshold` setting." ); } // The AbortController/AbortSignal pattern allows the routine to be notified // of a failure to extend the lock, and subsequent expiration. In the event // of an abort, the error object will be made available at `signal.error`. const controller = typeof AbortController === "undefined" ? new PolyfillAbortController() : new AbortController(); const signal = controller.signal as RedlockAbortSignal; function queue(): void { timeout = setTimeout( () => (extension = extend()), lock.expiration - Date.now() - settings.automaticExtensionThreshold ); } async function extend(): Promise<void> { timeout = undefined; try { lock = await lock.extend(duration); queue(); } catch (error) { if (lock.expiration > Date.now()) { return (extension = extend()); } signal.error = error instanceof Error ? error : new Error(`${error}`); controller.abort(); } } let timeout: undefined | NodeJS.Timeout; let extension: undefined | Promise<void>; let lock = await this.acquire(resources, duration, settings); queue(); try { return await routine(signal); } finally { // Clean up the timer. if (timeout) { clearTimeout(timeout); timeout = undefined; } // Wait for an in-flight extension to finish. if (extension) { await extension.catch(() => { // An error here doesn't matter at all, because the routine has // already completed, and a release will be attempted regardless. The // only reason for waiting here is to prevent possible contention // between the extension and release. }); } await lock.release(); } } }
the_stack
import Grid from "../Grid"; import { PROPERTY_TYPE } from "../consts"; import { GridOptions, Properties, GridOutlines, GridRect } from "../types"; import { GetterSetter, range } from "../utils"; import { GridItem } from "../GridItem"; function getMaxPoint(outline: number[]) { let maxPoint = -Infinity; outline.forEach((point) => { if (isFinite(point)) { maxPoint = Math.max(maxPoint, point); } }); return isFinite(maxPoint) ? maxPoint : 0; } function getMinPoint(outline: number[]) { let minPoint = Infinity; outline.forEach((point) => { if (isFinite(point)) { minPoint = Math.min(minPoint, point); } }); return isFinite(minPoint) ? minPoint : 0; } function getOutlinePoint(startOutline: number[], frameOutline: number[], useFrameFill: boolean) { return getMaxPoint(startOutline) + getOutlineDist(startOutline, frameOutline, useFrameFill); } function getOutlineDist(startOutline: number[], endOutline: number[], useFrameFill: boolean) { const length = startOutline.length; if (!length) { return 0; } const minEndPoint = getMinPoint(endOutline); const maxStartPoint = getMaxPoint(startOutline); let frameDist = 0; if (!useFrameFill) { return 0; } for (let outlineIndex = 0; outlineIndex < length; ++outlineIndex) { const startPoint = startOutline[outlineIndex]; const endPoint = endOutline[outlineIndex]; if (!isFinite(startPoint) || !isFinite(endPoint)) { continue; } const startPos = startPoint - maxStartPoint; const endPos = endPoint - minEndPoint; // Fill empty block. frameDist = outlineIndex ? Math.max(frameDist, frameDist + startPos - endPos) : startPos - endPos; } return frameDist; } function fillOutlines(startOutline: number[], endOutline: number[], rect: { inlinePos: number; inlineSize: number; contentPos: number; contentSize: number; }) { const { inlinePos, inlineSize, contentPos, contentSize, } = rect; for ( let outlineIndex = inlinePos; outlineIndex < inlinePos + inlineSize; ++outlineIndex ) { startOutline[outlineIndex] = Math.min(startOutline[outlineIndex], contentPos); endOutline[outlineIndex] = Math.max(endOutline[outlineIndex], contentPos + contentSize); } } export interface FrameRect extends Required<GridRect> { type: any; } /** * @typedef * @memberof Grid.FrameGrid * @extends Grid.GridOptions * @property - The shape of the grid. You can set the shape and order of items with a 2d array ([contentPos][inlinePos]). You can place items as many times as you fill the array with numbers, and zeros and spaces are empty spaces. The order of the items is arranged in ascending order of the numeric values that fill the array. (default: []) * <ko>Grid의 모양. 2d 배열([contentPos][inlinePos])로 아이템의 모양과 순서를 설정할 수 있다. 숫자로 배열을 채운만큼 아이템을 배치할 수 있으며 0과 공백은 빈 공간이다. 아이템들의 순서는 배열을 채운 숫자값의 오름차순대로 배치가 된다. (default: [])</ko> * @property - Make sure that the frame can be attached after the previous frame. (default: true) <ko> 다음 프레임이 전 프레임에 이어 붙일 수 있는지 있는지 확인한다.</ko> * @property - 1x1 rect size. If it is 0, it is determined by the number of columns in the frame. (default: 0) <ko>1x1 직사각형 크기. 0이면 frame의 column의 개수에 의해 결정된다. (default: 0)</ko> */ export interface FrameGridOptions extends GridOptions { frame?: number[][]; useFrameFill?: boolean; rectSize?: number | { inlineSize: number, contentSize: number }; } /** * 'Frame' is a printing term with the meaning that 'it fits in one row wide'. FrameGrid is a grid that the item is filled up on the basis of a line given a size. * @ko 'Frame'는 '1행의 너비에 맞게 꼭 들어찬'이라는 의미를 가진 인쇄 용어다. FrameGrid는 용어의 의미대로 너비가 주어진 사이즈를 기준으로 아이템이 가득 차도록 배치하는 Grid다. * @memberof Grid * @param {HTMLElement | string} container - A base element for a module <ko>모듈을 적용할 기준 엘리먼트</ko> * @param {Grid.FrameGrid.FrameGridOptions} options - The option object of the FrameGrid module <ko>FrameGrid 모듈의 옵션 객체</ko> */ @GetterSetter export class FrameGrid extends Grid<FrameGridOptions> { public static propertyTypes = { ...Grid.propertyTypes, frame: PROPERTY_TYPE.RENDER_PROPERTY, useFrameFill: PROPERTY_TYPE.RENDER_PROPERTY, rectSize: PROPERTY_TYPE.RENDER_PROPERTY, }; public static defaultOptions: Required<FrameGridOptions> = { ...Grid.defaultOptions, frame: [], rectSize: 0, useFrameFill: true, }; public applyGrid(items: GridItem[], direction: "start" | "end", outline: number[]): GridOutlines { const frame = this._getFrame(); const { inlineSize: frameInlineSize, contentSize: frameContentSize, rects: frameRects, } = frame; const { gap, useFrameFill, } = this.options; const { inlineSize: rectInlineSize, contentSize: rectContentSize, } = this.getRectSize(frameInlineSize); const itemsLength = items.length; if (!itemsLength || !frameInlineSize || !frameContentSize) { return { start: outline, end: outline }; } const rectsLength = frameRects.length; let startOutline = range(frameInlineSize).map(() => Infinity); let endOutline = range(frameInlineSize).map(() => -Infinity); const frameOutline = frame.outline.map((point) => point * (rectContentSize + gap)); for (let startIndex = 0; startIndex < itemsLength; startIndex += rectsLength) { // Compare group's startOutline and startOutline of rect const startPoint = getOutlinePoint(endOutline, frameOutline, useFrameFill); for (let rectIndex = 0; rectIndex < rectsLength && startIndex + rectIndex < itemsLength; ++rectIndex) { const item = items[startIndex + rectIndex]; const { contentPos: frameRectContentPos, inlinePos: frameRectInlinePos, contentSize: frameRectContentSize, inlineSize: frameRectInlineSize, } = frameRects[rectIndex]; const contentPos = startPoint + frameRectContentPos * (rectContentSize + gap); const inlinePos = frameRectInlinePos * (rectInlineSize + gap); const contentSize = frameRectContentSize * (rectContentSize + gap) - gap; const inlineSize = frameRectInlineSize * (rectInlineSize + gap) - gap; fillOutlines(startOutline, endOutline, { inlinePos: frameRectInlinePos, inlineSize: frameRectInlineSize, contentPos: contentPos, contentSize: contentSize + gap, }); item.setCSSGridRect({ inlinePos, contentPos, inlineSize, contentSize, }); } } const isDirectionEnd = direction === "end"; let gridOutline = outline.length ? outline : [0]; if (gridOutline.length !== frameInlineSize) { const point = isDirectionEnd ? Math.max(...gridOutline) : Math.min(...gridOutline); gridOutline = range(frameInlineSize).map(() => point); } startOutline = startOutline.map((point) => isFinite(point) ? point : 0); endOutline = endOutline.map((point) => isFinite(point) ? point : 0); const outlineDist = isDirectionEnd ? getOutlinePoint(gridOutline, startOutline, useFrameFill) : getOutlinePoint(endOutline, gridOutline, useFrameFill); items.forEach((item) => { item.cssContentPos! += outlineDist; }); return { start: startOutline.map((point) => point + outlineDist), end: endOutline.map((point) => point + outlineDist), }; } public getComputedOutlineLength() { const frame = this.options.frame; return frame.length ? frame[0].length : 0; } public getComputedOutlineSize() { const { gap, rectSize: rectSizeOption, } = this.options; if (typeof rectSizeOption === "object") { return rectSizeOption.inlineSize; } return rectSizeOption || ((this.getContainerInlineSize()! + gap) / this.getComputedOutlineLength() - gap); } protected getRectSize(frameInlineSize: number) { const { gap, rectSize: rectSizeOption, } = this.options; if (typeof rectSizeOption === "object") { return rectSizeOption; } const rectSizeValue = rectSizeOption ? rectSizeOption : (this.getContainerInlineSize()! + gap) / frameInlineSize - gap; return { inlineSize: rectSizeValue, contentSize: rectSizeValue }; } private _getFrame() { const frame = this.options.frame; const frameContentSize = frame.length; const frameInlineSize = frameContentSize ? frame[0].length : 0; const rects: FrameRect[] = []; const passMap: Record<string, boolean> = {}; const startOutline = range(frameInlineSize).map(() => Infinity); const endOutline = range(frameInlineSize).map(() => -Infinity); for (let y1 = 0; y1 < frameContentSize; ++y1) { for (let x1 = 0; x1 < frameInlineSize; ++x1) { const type = frame[y1][x1]; if (!type) { continue; } if (passMap[`${y1},${x1}`]) { continue; } const rect = this._findRect(passMap, type, y1, x1, frameInlineSize, frameContentSize); fillOutlines(startOutline, endOutline, rect); rects.push(rect); } } rects.sort((a, b) => (a.type < b.type ? -1 : 1)); return { rects, inlineSize: frameInlineSize, contentSize: frameContentSize, outline: startOutline, }; } private _findRect( passMap: Record<string, boolean>, type: number, y1: number, x1: number, frameInlineSize: number, frameContentSize: number, ) { const frame = this.options.frame; let contentSize = 1; let inlineSize = 1; // find rect for (let x2 = x1; x2 < frameInlineSize; ++x2) { if (frame[y1][x2] === type) { inlineSize = x2 - x1 + 1; continue; } break; } for (let y2 = y1; y2 < frameContentSize; ++y2) { if (frame[y2][x1] === type) { contentSize = y2 - y1 + 1; continue; } break; } // pass rect for (let y = y1; y < y1 + contentSize; ++y) { for (let x = x1; x < x1 + inlineSize; ++x) { passMap[`${y},${x}`] = true; } } const rect: FrameRect = { type, inlinePos: x1, contentPos: y1, inlineSize, contentSize, }; return rect; } } export interface FrameGrid extends Properties<typeof FrameGrid> { } /** * The shape of the grid. You can set the shape and order of items with a 2d array ([contentPos][inlinePos]). You can place items as many times as you fill the array with numbers, and zeros and spaces are empty spaces. The order of the items is arranged in ascending order of the numeric values that fill the array. * @ko Grid의 모양. 2d 배열([contentPos][inlinePos])로 아이템의 모양과 순서를 설정할 수 있다. 숫자로 배열을 채운만큼 아이템을 배치할 수 있으며 0과 공백은 빈 공간이다. 아이템들의 순서는 배열을 채운 숫자값의 오름차순대로 배치가 된다. * @name Grid.FrameGrid#frame * @type {$ts:Grid.FrameGrid.FrameGridOptions["frame"]} * @default [] * @example * ```js * import { FrameGrid } from "@egjs/grid"; * * // Item 1 : 2 x 2 * // Item 2 : 1 x 1 * // Item 3 : 1 x 2 * // Item 4 : 1 x 1 * // Item 5 : 2 x 1 * const grid = new FrameGrid(container, { * frame: [ * [1, 1, 0, 0, 2, 3], * [1, 1, 0, 4, 5, 5], * ], * }); * * // Item 1 : 2 x 2 * // Item 2 : 2 x 2 * grid.frame = [ * [1, 1, 0, 0, 2, 2], * [1, 1, 0, 0, 2, 2], * ]; * ``` */ /** * Make sure that the frame can be attached after the previous frame. * @ko 다음 프레임이 전 프레임에 이어 붙일 수 있는지 있는지 확인한다. * @name Grid.FrameGrid#useFrameFill * @type {$ts:Grid.FrameGrid.FrameGridOptions["useFrameFill"]} * @default true * @example * ```js * import { FrameGrid } from "@egjs/grid"; * * const grid = new FrameGrid(container, { * useFrameFill: true, * }); * * grid.useFrameFill = false; * ``` */ /** * 1x1 rect size. If it is 0, it is determined by the number of columns in the frame. (default: 0) * @ko 1x1 직사각형 크기. 0이면 frame의 column의 개수에 의해 결정된다. (default: 0) * @name Grid.FrameGrid#rectSize * @type {$ts:Grid.FrameGrid.FrameGridOptions["rectSize"]} * @example * ```js * import { FrameGrid } from "@egjs/grid"; * * const grid = new FrameGrid(container, { * rectSize: 0, * }); * * grid.rectSize = { inlineSize: 100, contentSize: 150 }; * ``` */
the_stack
// tslint:disable:max-classes-per-file import { PathLike } from "fs"; import { FileAudioSource, MicAudioSource, PcmRecorder, } from "../../common.browser/Exports"; import { ISpeechConfigAudioDevice } from "../../common.speech/Exports"; import { AudioSourceEvent, Deferred, EventSource, IAudioDestination, IAudioSource, IAudioStreamNode } from "../../common/Exports"; import { Contracts } from "../Contracts"; import { AudioInputStream, AudioOutputStream, AudioStreamFormat, IPlayer, PropertyCollection, PropertyId, PullAudioInputStreamCallback, PullAudioOutputStream, PushAudioOutputStream, PushAudioOutputStreamCallback, SpeakerAudioDestination } from "../Exports"; import { AudioFileWriter } from "./AudioFileWriter"; import { PullAudioInputStreamImpl, PushAudioInputStreamImpl } from "./AudioInputStream"; import { PullAudioOutputStreamImpl, PushAudioOutputStreamImpl } from "./AudioOutputStream"; import { AudioStreamFormatImpl } from "./AudioStreamFormat"; /** * Represents audio input configuration used for specifying what type of input to use (microphone, file, stream). * @class AudioConfig * Updated in version 1.11.0 */ export abstract class AudioConfig { /** * Creates an AudioConfig object representing the default microphone on the system. * @member AudioConfig.fromDefaultMicrophoneInput * @function * @public * @returns {AudioConfig} The audio input configuration being created. */ public static fromDefaultMicrophoneInput(): AudioConfig { const pcmRecorder = new PcmRecorder(true); return new AudioConfigImpl(new MicAudioSource(pcmRecorder)); } /** * Creates an AudioConfig object representing a microphone with the specified device ID. * @member AudioConfig.fromMicrophoneInput * @function * @public * @param {string | undefined} deviceId - Specifies the device ID of the microphone to be used. * Default microphone is used the value is omitted. * @returns {AudioConfig} The audio input configuration being created. */ public static fromMicrophoneInput(deviceId?: string): AudioConfig { const pcmRecorder = new PcmRecorder(true); return new AudioConfigImpl(new MicAudioSource(pcmRecorder, deviceId)); } /** * Creates an AudioConfig object representing the specified file. * @member AudioConfig.fromWavFileInput * @function * @public * @param {File} fileName - Specifies the audio input file. Currently, only WAV / PCM is supported. * @returns {AudioConfig} The audio input configuration being created. */ public static fromWavFileInput(file: File | Buffer, name: string = "unnamedBuffer.wav"): AudioConfig { return new AudioConfigImpl(new FileAudioSource(file, name)); } /** * Creates an AudioConfig object representing the specified stream. * @member AudioConfig.fromStreamInput * @function * @public * @param {AudioInputStream | PullAudioInputStreamCallback | MediaStream} audioStream - Specifies the custom audio input * stream. Currently, only WAV / PCM is supported. * @returns {AudioConfig} The audio input configuration being created. */ public static fromStreamInput(audioStream: AudioInputStream | PullAudioInputStreamCallback | MediaStream): AudioConfig { if (audioStream instanceof PullAudioInputStreamCallback) { return new AudioConfigImpl(new PullAudioInputStreamImpl(audioStream as PullAudioInputStreamCallback)); } if (audioStream instanceof AudioInputStream) { return new AudioConfigImpl(audioStream as PushAudioInputStreamImpl); } if (typeof MediaStream !== "undefined" && audioStream instanceof MediaStream) { const pcmRecorder = new PcmRecorder(false); return new AudioConfigImpl(new MicAudioSource(pcmRecorder, null, null, audioStream)); } throw new Error("Not Supported Type"); } /** * Creates an AudioConfig object representing the default speaker. * @member AudioConfig.fromDefaultSpeakerOutput * @function * @public * @returns {AudioConfig} The audio output configuration being created. * Added in version 1.11.0 */ public static fromDefaultSpeakerOutput(): AudioConfig { return new AudioOutputConfigImpl(new SpeakerAudioDestination()); } /** * Creates an AudioConfig object representing the custom IPlayer object. * You can use the IPlayer object to control pause, resume, etc. * @member AudioConfig.fromSpeakerOutput * @function * @public * @param {IPlayer} player - the IPlayer object for playback. * @returns {AudioConfig} The audio output configuration being created. * Added in version 1.12.0 */ public static fromSpeakerOutput(player?: IPlayer): AudioConfig { if (player === undefined) { return AudioConfig.fromDefaultSpeakerOutput(); } if (player instanceof SpeakerAudioDestination) { return new AudioOutputConfigImpl(player as SpeakerAudioDestination); } throw new Error("Not Supported Type"); } /** * Creates an AudioConfig object representing a specified output audio file * @member AudioConfig.fromAudioFileOutput * @function * @public * @param {PathLike} filename - the filename of the output audio file * @returns {AudioConfig} The audio output configuration being created. * Added in version 1.11.0 */ public static fromAudioFileOutput(filename: PathLike): AudioConfig { return new AudioOutputConfigImpl(new AudioFileWriter(filename)); } /** * Creates an AudioConfig object representing a specified audio output stream * @member AudioConfig.fromStreamOutput * @function * @public * @param {AudioOutputStream | PushAudioOutputStreamCallback} audioStream - Specifies the custom audio output * stream. * @returns {AudioConfig} The audio output configuration being created. * Added in version 1.11.0 */ public static fromStreamOutput(audioStream: AudioOutputStream | PushAudioOutputStreamCallback): AudioConfig { if (audioStream instanceof PushAudioOutputStreamCallback) { return new AudioOutputConfigImpl(new PushAudioOutputStreamImpl(audioStream as PushAudioOutputStreamCallback)); } if (audioStream instanceof PushAudioOutputStream) { return new AudioOutputConfigImpl(audioStream as PushAudioOutputStreamImpl); } if (audioStream instanceof PullAudioOutputStream) { return new AudioOutputConfigImpl(audioStream as PullAudioOutputStreamImpl); } throw new Error("Not Supported Type"); } /** * Explicitly frees any external resource attached to the object * @member AudioConfig.prototype.close * @function * @public */ public abstract close(): void; /** * Sets an arbitrary property. * @member SpeechConfig.prototype.setProperty * @function * @public * @param {string} name - The name of the property to set. * @param {string} value - The new value of the property. */ public abstract setProperty(name: string, value: string): void; /** * Returns the current value of an arbitrary property. * @member SpeechConfig.prototype.getProperty * @function * @public * @param {string} name - The name of the property to query. * @param {string} def - The value to return in case the property is not known. * @returns {string} The current value, or provided default, of the given property. */ public abstract getProperty(name: string, def?: string): string; } /** * Represents audio input stream used for custom audio input configurations. * @private * @class AudioConfigImpl */ export class AudioConfigImpl extends AudioConfig implements IAudioSource { private privSource: IAudioSource; /** * Creates and initializes an instance of this class. * @constructor * @param {IAudioSource} source - An audio source. */ public constructor(source: IAudioSource) { super(); this.privSource = source; } /** * Format information for the audio */ public get format(): Promise<AudioStreamFormatImpl> { return this.privSource.format; } /** * @member AudioConfigImpl.prototype.close * @function * @public */ public close(cb?: () => void, err?: (error: string) => void): void { this.privSource.turnOff().then(() => { if (!!cb) { cb(); } }, (error: string) => { if (!!err) { err(error); } }); } /** * @member AudioConfigImpl.prototype.id * @function * @public */ public id(): string { return this.privSource.id(); } /** * @member AudioConfigImpl.prototype.blob * @function * @public */ public get blob(): Promise<Blob | Buffer> { return this.privSource.blob; } /** * @member AudioConfigImpl.prototype.turnOn * @function * @public * @returns {Promise<void>} A promise. */ public turnOn(): Promise<void> { return this.privSource.turnOn(); } /** * @member AudioConfigImpl.prototype.attach * @function * @public * @param {string} audioNodeId - The audio node id. * @returns {Promise<IAudioStreamNode>} A promise. */ public attach(audioNodeId: string): Promise<IAudioStreamNode> { return this.privSource.attach(audioNodeId); } /** * @member AudioConfigImpl.prototype.detach * @function * @public * @param {string} audioNodeId - The audio node id. */ public detach(audioNodeId: string): void { return this.privSource.detach(audioNodeId); } /** * @member AudioConfigImpl.prototype.turnOff * @function * @public * @returns {Promise<void>} A promise. */ public turnOff(): Promise<void> { return this.privSource.turnOff(); } /** * @member AudioConfigImpl.prototype.events * @function * @public * @returns {EventSource<AudioSourceEvent>} An event source for audio events. */ public get events(): EventSource<AudioSourceEvent> { return this.privSource.events; } public setProperty(name: string, value: string): void { Contracts.throwIfNull(value, "value"); if (undefined !== this.privSource.setProperty) { this.privSource.setProperty(name, value); } else { throw new Error("This AudioConfig instance does not support setting properties."); } } public getProperty(name: string, def?: string): string { if (undefined !== this.privSource.getProperty) { return this.privSource.getProperty(name, def); } else { throw new Error("This AudioConfig instance does not support getting properties."); } return def; } public get deviceInfo(): Promise<ISpeechConfigAudioDevice> { return this.privSource.deviceInfo; } } export class AudioOutputConfigImpl extends AudioConfig implements IAudioDestination { private privDestination: IAudioDestination; /** * Creates and initializes an instance of this class. * @constructor * @param {IAudioDestination} destination - An audio destination. */ public constructor(destination: IAudioDestination) { super(); this.privDestination = destination; } public set format(format: AudioStreamFormat) { this.privDestination.format = format; } public write(buffer: ArrayBuffer): void { this.privDestination.write(buffer); } public close(): void { this.privDestination.close(); } public id(): string { return this.privDestination.id(); } public setProperty(name: string, value: string): void { throw new Error("This AudioConfig instance does not support setting properties."); } public getProperty(name: string, def?: string): string { throw new Error("This AudioConfig instance does not support getting properties."); } }
the_stack
import type { Faker } from '../../faker'; /** * Color space names supported by CSS. */ export const CSS_SPACES = [ 'sRGB', 'display-p3', 'rec2020', 'a98-rgb', 'prophoto-rgb', 'rec2020', ] as const; /** * Functions supported by CSS to produce color. */ export const CSS_FUNCTIONS = [ 'rgb', 'rgba', 'hsl', 'hsla', 'hwb', 'cmyk', 'lab', 'lch', 'color', ] as const; export type CSSFunction = typeof CSS_FUNCTIONS[number]; export type CSSSpace = typeof CSS_SPACES[number]; export type StringColorFormat = 'css' | 'binary'; export type NumberColorFormat = 'decimal'; export type ColorFormat = StringColorFormat | NumberColorFormat; export type Casing = 'lower' | 'upper' | 'mixed'; /** * Formats the hex format of a generated color string according * to options specified by user. * * @param hexColor Hex color string to be formatted. * @param options Options object. * @param options.prefix Prefix of the generated hex color. Defaults to `'0x'`. * @param options.casing Letter type case of the generated hex color. Defaults to `'mixed'`. */ function formatHexColor( hexColor: string, options?: { prefix?: string; casing?: Casing; } ): string { switch (options?.casing) { case 'upper': hexColor = hexColor.toUpperCase(); break; case 'lower': hexColor = hexColor.toLowerCase(); break; } if (options?.prefix) { hexColor = options.prefix + hexColor; } return hexColor; } /** * Converts an array of numbers into binary string format. * * @param values Array of values to be converted. */ function toBinary(values: number[]): string { const binary: string[] = values.map((value) => { const isFloat = value % 1 !== 0; if (isFloat) { const buffer = new ArrayBuffer(4); new DataView(buffer).setFloat32(0, value); const bytes = new Uint8Array(buffer); return toBinary(Array.from(bytes)).split(' ').join(''); } return (value >>> 0).toString(2).padStart(8, '0'); }); return binary.join(' '); } /** * Converts an array of numbers into CSS accepted format. * * @param values Array of values to be converted. * @param cssFunction CSS function to be generated for the color. Defaults to `'rgb'`. * @param space Color space to format CSS color function with. Defaults to `'sRGB'`. */ function toCSS( values: number[], cssFunction: CSSFunction = 'rgb', space: CSSSpace = 'sRGB' ): string { const percentage = (value: number) => Math.round(value * 100); switch (cssFunction) { case 'rgba': return `rgba(${values[0]}, ${values[1]}, ${values[2]}, ${values[3]})`; case 'color': return `color(${space} ${values[0]} ${values[1]} ${values[2]})`; case 'cmyk': return `cmyk(${percentage(values[0])}%, ${percentage( values[1] )}%, ${percentage(values[2])}%, ${percentage(values[3])}%)`; case 'hsl': return `hsl(${values[0]}deg ${percentage(values[1])}% ${percentage( values[2] )}%)`; case 'hsla': return `hsl(${values[0]}deg ${percentage(values[1])}% ${percentage( values[2] )}% / ${percentage(values[3])})`; case 'hwb': return `hwb(${values[0]} ${percentage(values[1])}% ${percentage( values[2] )}%)`; case 'lab': return `lab(${percentage(values[0])}% ${values[1]} ${values[2]})`; case 'lch': return `lch(${percentage(values[0])}% ${values[1]} ${values[2]})`; case 'rgb': default: return `rgb(${values[0]}, ${values[1]}, ${values[2]})`; } } /** * Converts an array of color values to the specified color format. * * @param values Array of color values to be converted. * @param format Format of generated RGB color. * @param cssFunction CSS function to be generated for the color. Defaults to `'rgb'`. * @param space Color space to format CSS color function with. Defaults to `'sRGB'`. */ function toColorFormat( values: number[], format: ColorFormat, cssFunction: CSSFunction = 'rgb', space: CSSSpace = 'sRGB' ): string | number[] { switch (format) { case 'css': return toCSS(values, cssFunction, space); case 'binary': return toBinary(values); default: return values; } } /** * Module to generate colors. */ export class Color { constructor(private readonly faker: Faker) { // Bind `this` so namespaced is working correctly for (const name of Object.getOwnPropertyNames(Color.prototype)) { if (name === 'constructor' || typeof this[name] !== 'function') { continue; } this[name] = this[name].bind(this); } } /** * Returns a random human readable color name. * * @example * faker.color.human() // 'red' */ human(): string { return this.faker.helpers.arrayElement(this.faker.definitions.color.human); } /** * Returns a random color space name from the worldwide accepted color spaces. * Source: https://en.wikipedia.org/wiki/List_of_color_spaces_and_their_uses * * @example * faker.color.space() // 'sRGB' */ space(): string { return this.faker.helpers.arrayElement(this.faker.definitions.color.space); } /** * Returns a random css supported color function name. * * @example * faker.color.cssSupportedFunction() // 'rgb' */ cssSupportedFunction(): string { return this.faker.helpers.arrayElement(CSS_FUNCTIONS); } /** * Returns a random css supported color space name. * * @example * faker.color.cssSupportedSpace() // 'display-p3' */ cssSupportedSpace(): string { return this.faker.helpers.arrayElement(CSS_SPACES); } /** * Returns an RGB color. * * @example * faker.color.rgb() // '0xffffFF' */ rgb(): string; /** * Returns an RGB color. * * @param options Options object. * @param options.prefix Prefix of the generated hex color. Only applied when 'hex' format is used. Defaults to `'0x'`. * @param options.casing Letter type case of the generated hex color. Only applied when `'hex'` format is used. Defaults to `'mixed'`. * @param options.format Format of generated RGB color. Defaults to `hex`. * @param options.includeAlpha Adds an alpha value to the color (RGBA). Defaults to `false`. * * @example * faker.color.rgb() // '0xffffFF' * faker.color.rgb({ prefix: '#' }) // '#ffffFF' * faker.color.rgb({ casing: 'upper' }) // '0xFFFFFF' * faker.color.rgb({ casing: 'lower' }) // '0xffffff' * faker.color.rgb({ prefix: '#', casing: 'lower' }) // '#ffffff' * faker.color.rgb({ format: 'hex', casing: 'lower' }) // '#ffffff' * faker.color.rgb({ format: 'css' }) // 'rgb(255, 0, 0)' * faker.color.rgb({ format: 'binary' }) // '10000000 00000000 11111111' */ rgb(options?: { prefix?: string; casing?: Casing; format?: 'hex' | StringColorFormat; includeAlpha?: boolean; }): string; /** * Returns an RGB color. * * @param options Options object. * @param options.format Format of generated RGB color. Defaults to `'hex'`. * @param options.includeAlpha Adds an alpha value to the color (RGBA). Defaults to `false`. * * @example * faker.color.rgb() // '0xffffFF' * faker.color.rgb({ format: 'decimal' }) // [255, 255, 255] * faker.color.rgb({ format: 'decimal', includeAlpha: true }) // [255, 255, 255, 0.4] */ rgb(options?: { format?: NumberColorFormat; includeAlpha?: boolean; }): number[]; /** * Returns an RGB color. * * @param options Options object. * @param options.prefix Prefix of the generated hex color. Only applied when `'hex'` format is used. Defaults to `'0x'`. * @param options.casing Letter type case of the generated hex color. Only applied when `'hex'` format is used. Defaults to `'mixed'`. * @param options.format Format of generated RGB color. Defaults to `'hex'`. * @param options.includeAlpha Adds an alpha value to the color (RGBA). Defaults to `false`. * * @example * faker.color.rgb() // '0xffffFF' * faker.color.rgb({ prefix: '#' }) // '#ffffFF' * faker.color.rgb({ casing: 'upper' }) // '0xFFFFFF' * faker.color.rgb({ casing: 'lower' }) // '0xffffff' * faker.color.rgb({ prefix: '#', casing: 'lower' }) // '#ffffff' * faker.color.rgb({ format: 'hex', casing: 'lower' }) // '#ffffff' * faker.color.rgb({ format: 'decimal' }) // [255, 255, 255] * faker.color.rgb({ format: 'css' }) // 'rgb(255, 0, 0)' * faker.color.rgb({ format: 'binary' }) // '10000000 00000000 11111111' * faker.color.rgb({ format: 'decimal', includeAlpha: true }) // [255, 255, 255, 0.4] */ rgb(options?: { prefix?: string; casing?: Casing; format?: 'hex' | ColorFormat; includeAlpha?: boolean; }): string | number[]; rgb(options?: { prefix?: string; casing?: Casing; format?: 'hex' | ColorFormat; includeAlpha?: boolean; }): string | number[] { const { format = 'hex', includeAlpha = false, prefix = '#', casing = 'lower', } = options || {}; options = { format, includeAlpha, prefix, casing }; let color: string | number[]; let cssFunction: CSSFunction = 'rgb'; if (format === 'hex') { color = this.faker.datatype.hexadecimal(includeAlpha ? 8 : 6).slice(2); color = formatHexColor(color, options); return color; } color = Array.from({ length: 3 }).map(() => this.faker.datatype.number({ min: 0, max: 255 }) ); if (includeAlpha) { color.push( this.faker.datatype.float({ min: 0, max: 1, precision: 0.01 }) ); cssFunction = 'rgba'; } return toColorFormat(color, format, cssFunction); } /** * Returns a CMYK color. * * @example * faker.color.cmyk() // [0.31, 0.52, 0.32, 0.43] */ cmyk(): number[]; /** * Returns a CMYK color. * * @param options Options object. * @param options.format Format of generated CMYK color. Defaults to `'decimal'`. * * @example * faker.color.cmyk() // [0.31, 0.52, 0.32, 0.43] * faker.color.cmyk({ format: 'css' }) // cmyk(100%, 0%, 0%, 0%) * faker.color.cmyk({ format: 'binary' }) // (8-32 bits) x 4 */ cmyk(options?: { format?: StringColorFormat }): string; /** * Returns a CMYK color. * * @param options Options object. * @param options.format Format of generated CMYK color. Defaults to `'decimal'`. * * @example * faker.color.cmyk() // [0.31, 0.52, 0.32, 0.43] * faker.color.cmyk({ format: 'decimal' }) // [0.31, 0.52, 0.32, 0.43] */ cmyk(options?: { format?: NumberColorFormat }): number[]; /** * Returns a CMYK color. * * @param options Options object. * @param options.format Format of generated CMYK color. Defaults to `'decimal'`. * * @example * faker.color.cmyk() // [0.31, 0.52, 0.32, 0.43] * faker.color.cmyk({ format: 'decimal' }) // [0.31, 0.52, 0.32, 0.43] * faker.color.cmyk({ format: 'css' }) // cmyk(100%, 0%, 0%, 0%) * faker.color.cmyk({ format: 'binary' }) // (8-32 bits) x 4 */ cmyk(options?: { format?: ColorFormat }): string | number[]; cmyk(options?: { format?: ColorFormat }): string | number[] { const color: string | number[] = Array.from({ length: 4 }).map(() => this.faker.datatype.float({ min: 0, max: 1, precision: 0.01 }) ); return toColorFormat(color, options?.format || 'decimal', 'cmyk'); } /** * Returns an HSL color. * * @example * faker.color.hsl() // [201, 0.23, 0.32] */ hsl(): number[]; /** * Returns an HSL color. * * @param options Options object. * @param options.format Format of generated HSL color. Defaults to `'decimal'`. * @param options.includeAlpha Adds an alpha value to the color (RGBA). Defaults to `false`. * * @example * faker.color.hsl() // [201, 0.23, 0.32] * faker.color.hsl({ format: 'css' }) // hsl(0deg, 100%, 80%) * faker.color.hsl({ format: 'css', includeAlpha: true }) // hsl(0deg 100% 50% / 0.5) * faker.color.hsl({ format: 'binary' }) // (8-32 bits) x 3 * faker.color.hsl({ format: 'binary', includeAlpha: true }) // (8-32 bits) x 4 */ hsl(options?: { format?: StringColorFormat; includeAlpha?: boolean }): string; /** * Returns an HSL color. * * @param options Options object. * @param options.format Format of generated HSL color. Defaults to `'decimal'`. * @param options.includeAlpha Adds an alpha value to the color (RGBA). Defaults to `false`. * * @example * faker.color.hsl() // [201, 0.23, 0.32] * faker.color.hsl({ format: 'decimal' }) // [300, 0.21, 0.52] * faker.color.hsl({ format: 'decimal', includeAlpha: true }) // [300, 0.21, 0.52, 0.28] */ hsl(options?: { format?: NumberColorFormat; includeAlpha?: boolean; }): number[]; /** * Returns an HSL color. * * @param options Options object. * @param options.format Format of generated HSL color. Defaults to `'decimal'`. * @param options.includeAlpha Adds an alpha value to the color (RGBA). Defaults to `false`. * * @example * faker.color.hsl() // [201, 0.23, 0.32] * faker.color.hsl({ format: 'decimal' }) // [300, 0.21, 0.52] * faker.color.hsl({ format: 'decimal', includeAlpha: true }) // [300, 0.21, 0.52, 0.28] * faker.color.hsl({ format: 'css' }) // hsl(0deg, 100%, 80%) * faker.color.hsl({ format: 'css', includeAlpha: true }) // hsl(0deg 100% 50% / 0.5) * faker.color.hsl({ format: 'binary' }) // (8-32 bits) x 3 * faker.color.hsl({ format: 'binary', includeAlpha: true }) // (8-32 bits) x 4 */ hsl(options?: { format?: ColorFormat; includeAlpha?: boolean; }): string | number[]; hsl(options?: { format?: ColorFormat; includeAlpha?: boolean; }): string | number[] { const hsl: number[] = [this.faker.datatype.number({ min: 0, max: 360 })]; for (let i = 0; i < (options?.includeAlpha ? 3 : 2); i++) { hsl.push(this.faker.datatype.float({ min: 0, max: 1, precision: 0.01 })); } return toColorFormat( hsl, options?.format || 'decimal', options?.includeAlpha ? 'hsla' : 'hsl' ); } /** * Returns an HWB color. * * @example * faker.color.hwb() // [201, 0.21, 0.31] */ hwb(): number[]; /** * Returns an HWB color. * * @param options Options object. * @param options.format Format of generated RGB color. Defaults to `'decimal'`. * * @example * faker.color.hwb() // [201, 0.21, 0.31] * faker.color.hwb({ format: 'css' }) // hwb(194 0% 0%) * faker.color.hwb({ format: 'binary' }) // (8-32 bits x 3) */ hwb(options?: { format?: StringColorFormat }): string; /** * Returns an HWB color. * * @param options Options object. * @param options.format Format of generated RGB color. Defaults to `'decimal'`. * * @example * faker.color.hwb() // [201, 0.21, 0.31] * faker.color.hwb({ format: 'decimal' }) // [201, 0.21, 0.31] */ hwb(options?: { format?: NumberColorFormat }): number[]; /** * Returns an HWB color. * * @param options Options object. * @param options.format Format of generated RGB color. Defaults to `'decimal'`. * * @example * faker.color.hwb() // [201, 0.21, 0.31] * faker.color.hwb({ format: 'decimal' }) // [201, 0.21, 0.31] * faker.color.hwb({ format: 'css' }) // hwb(194 0% 0%) * faker.color.hwb({ format: 'binary' }) // (8-32 bits x 3) */ hwb(options?: { format?: ColorFormat }): string | number[]; /** * Returns an HWB color. * * @param options Options object. * @param options.format Format of generated RGB color. Defaults to `'decimal'`. * * @example * faker.color.hwb() // [201, 0.21, 0.31] * faker.color.hwb({ format: 'decimal' }) // [201, 0.21, 0.31] * faker.color.hwb({ format: 'css' }) // hwb(194 0% 0%) * faker.color.hwb({ format: 'binary' }) // (8-32 bits x 3) */ hwb(options?: { format?: ColorFormat }): string | number[] { const hsl: number[] = [this.faker.datatype.number({ min: 0, max: 360 })]; for (let i = 0; i < 2; i++) { hsl.push(this.faker.datatype.float({ min: 0, max: 1, precision: 0.01 })); } return toColorFormat(hsl, options?.format || 'decimal', 'hwb'); } /** * Returns a LAB (CIELAB) color. * * @example * faker.color.lab() // [0.832133, -80.3245, 100.1234] */ lab(): number[]; /** * Returns a LAB (CIELAB) color. * * @param options Options object. * @param options.format Format of generated RGB color. Defaults to `'decimal'`. * * @example * faker.color.lab() // [0.832133, -80.3245, 100.1234] * faker.color.lab({ format: 'css' }) // lab(29.2345% 39.3825 20.0664) * faker.color.lab({ format: 'binary' }) // (8-32 bits x 3) */ lab(options?: { format?: StringColorFormat }): string; /** * Returns a LAB (CIELAB) color. * * @param options Options object. * @param options.format Format of generated RGB color. Defaults to `'decimal'`. * * @example * faker.color.lab() // [0.832133, -80.3245, 100.1234] * faker.color.lab({ format: 'decimal' }) // [0.856773, -80.2345, 100.2341] */ lab(options?: { format?: NumberColorFormat }): number[]; /** * Returns a LAB (CIELAB) color. * * @param options Options object. * @param options.format Format of generated RGB color. Defaults to `'decimal'`. * * @example * faker.color.lab() // [0.832133, -80.3245, 100.1234] * faker.color.lab({ format: 'decimal' }) // [0.856773, -80.2345, 100.2341] * faker.color.lab({ format: 'css' }) // lab(29.2345% 39.3825 20.0664) * faker.color.lab({ format: 'binary' }) // (8-32 bits x 3) */ lab(options?: { format?: ColorFormat }): string | number[]; lab(options?: { format?: ColorFormat }): string | number[] { const lab = [ this.faker.datatype.float({ min: 0, max: 1, precision: 0.000001 }), ]; for (let i = 0; i < 2; i++) { lab.push( this.faker.datatype.float({ min: -100, max: 100, precision: 0.0001 }) ); } return toColorFormat(lab, options?.format || 'decimal', 'lab'); } /** * Returns an LCH color. Even though upper bound of * chroma in LCH color space is theoretically unbounded, * it is bounded to 230 as anything above will not * make a noticeable difference in the browser. * * @example * faker.color.lch() // [0.522345, 72.2, 56.2] */ lch(): number[]; /** * Returns an LCH color. Even though upper bound of * chroma in LCH color space is theoretically unbounded, * it is bounded to 230 as anything above will not * make a noticeable difference in the browser. * * @param options Options object. * @param options.format Format of generated RGB color. Defaults to `'decimal'`. * * @example * faker.color.lch() // [0.522345, 72.2, 56.2] * faker.color.lch({ format: 'css' }) // lch(52.2345% 72.2 56.2) * faker.color.lch({ format: 'binary' }) // (8-32 bits x 3) */ lch(options?: { format?: StringColorFormat }): string; /** * Returns an LCH color. Even though upper bound of * chroma in LCH color space is theoretically unbounded, * it is bounded to 230 as anything above will not * make a noticeable difference in the browser. * * @param options Options object. * @param options.format Format of generated RGB color. Defaults to `'decimal'`. * * @example * faker.color.lch() // [0.522345, 72.2, 56.2] * faker.color.lch({ format: 'decimal' }) // [0.522345, 72.2, 56.2] */ lch(options?: { format?: NumberColorFormat }): number[]; /** * Returns an LCH color. Even though upper bound of * chroma in LCH color space is theoretically unbounded, * it is bounded to 230 as anything above will not * make a noticeable difference in the browser. * * @param options Options object. * @param options.format Format of generated RGB color. Defaults to `'decimal'`. * * @example * faker.color.lch() // [0.522345, 72.2, 56.2] * faker.color.lch({ format: 'decimal' }) // [0.522345, 72.2, 56.2] * faker.color.lch({ format: 'css' }) // lch(52.2345% 72.2 56.2) * faker.color.lch({ format: 'binary' }) // (8-32 bits x 3) */ lch(options?: { format?: ColorFormat }): string | number[]; lch(options?: { format?: ColorFormat }): string | number[] { const lch = [ this.faker.datatype.float({ min: 0, max: 1, precision: 0.000001 }), ]; for (let i = 0; i < 2; i++) { lch.push( this.faker.datatype.number({ min: 0, max: 230, precision: 0.1 }) ); } return toColorFormat(lch, options?.format || 'decimal', 'lch'); } /** * Returns a random color based on CSS color space specified. * * @example * faker.color.colorByCSSColorSpace() // [0.93, 1, 0.82] */ colorByCSSColorSpace(): number[]; /** * Returns a random color based on CSS color space specified. * * @param options Options object. * @param options.format Format of generated RGB color. Defaults to `'decimal'`. * @param options.space Color space to generate the color for. Defaults to `'sRGB'`. * * @example * faker.color.colorByCSSColorSpace() // [0.93, 1, 0.82] * faker.color.colorByCSSColorSpace({ format: 'css', space: 'display-p3' }) // color(display-p3 0.12 1 0.23) * faker.color.colorByCSSColorSpace({ format: 'binary' }) // (8-32 bits x 3) */ colorByCSSColorSpace(options?: { format?: StringColorFormat; space?: CSSSpace; }): string; /** * Returns a random color based on CSS color space specified. * * @param options Options object. * @param options.format Format of generated RGB color. Defaults to `'decimal'`. * @param options.space Color space to generate the color for. Defaults to `'sRGB'`. * * @example * faker.color.colorByCSSColorSpace() // [0.93, 1, 0.82] * faker.color.colorByCSSColorSpace({ format: 'decimal' }) // [0.12, 0.21, 0.31] */ colorByCSSColorSpace(options?: { format?: NumberColorFormat; space?: CSSSpace; }): number[]; /** * Returns a random color based on CSS color space specified. * * @param options Options object. * @param options.format Format of generated RGB color. Defaults to `'decimal'`. * @param options.space Color space to generate the color for. Defaults to `'sRGB'`. * * @example * faker.color.colorByCSSColorSpace() // [0.93, 1, 0.82] * faker.color.colorByCSSColorSpace({ format: 'decimal' }) // [0.12, 0.21, 0.31] * faker.color.colorByCSSColorSpace({ format: 'css', space: 'display-p3' }) // color(display-p3 0.12 1 0.23) * faker.color.colorByCSSColorSpace({ format: 'binary' }) // (8-32 bits x 3) */ colorByCSSColorSpace(options?: { format?: ColorFormat; space?: CSSSpace; }): string | number[]; colorByCSSColorSpace(options?: { format?: ColorFormat; space?: CSSSpace; }): string | number[] { if (options?.format === 'css' && !options?.space) { options = { ...options, space: 'sRGB' }; } const color = Array.from({ length: 3 }).map(() => this.faker.datatype.float({ min: 0, max: 1, precision: 0.0001 }) ); return toColorFormat( color, options?.format || 'decimal', 'color', options?.space ); } }
the_stack
import ServiceElectron from '../service.electron'; import ServiceStreams from '../service.streams'; import ServiceStreamSource from '../service.stream.sources'; import ServiceHotkeys from '../service.hotkeys'; import ServiceFileRecent from './service.file.recent'; import ServiceNotifications from '../service.notifications'; import ServiceRenderState from '../service.render.state'; import Logger from '../../tools/env.logger'; import { IPCMessages } from '../service.electron'; import { ENotificationType } from '../service.notifications'; import { IMapItem, ITicks } from '../../controllers/files.parsers/interface'; import { dialog, OpenDialogReturnValue } from 'electron'; import { getDefaultFileParser, AFileParser, getParserForFile } from '../../controllers/files.parsers/index'; import { Subscription } from '../../tools/index'; import { IService } from '../../interfaces/interface.service'; import { isHidden } from '../../tools/fs'; import { app } from 'electron'; import * as Tools from '../../tools/index'; import * as fs from 'fs'; import * as path from 'path'; interface IOpenFileResult { sourceId: number; options: any; } /** * @class ServiceFileOpener * @description Opens files dropped on render */ class ServiceFileOpener implements IService { private _logger: Logger = new Logger('ServiceFileOpener'); // Should detect by executable file private _subscriptions: { [key: string]: Subscription } = {}; private _active: Map<string, AFileParser> = new Map<string, AFileParser>(); private _recent: { path: string | undefined; pending: boolean; } = { path: undefined, pending: true, }; constructor() { app.on('open-file', this._onOSRecentFileOpen.bind(this)); ServiceRenderState.doOnInit(Tools.guid(), this._onRenderReady.bind(this)); } /** * Initialization function * @returns Promise<void> */ public init(): Promise<void> { return new Promise((resolve, reject) => { Promise.all([ ServiceElectron.IPC.subscribe(IPCMessages.FileOpenRequest, this._ipc_FileOpenRequest.bind(this)).then((subscription: Subscription) => { this._subscriptions.FileOpenRequest = subscription; }), ServiceElectron.IPC.subscribe(IPCMessages.FileListRequest, this._ipc_FileListRequest.bind(this)).then((subscription: Subscription) => { this._subscriptions.FileListRequest = subscription; }), ]).then(() => { this._subscriptions.onSessionClosed = ServiceStreams.getSubjects().onSessionClosed.subscribe(this._onSessionClosed.bind(this)); this._subscriptions.openLocalFile = ServiceHotkeys.getSubject().openLocalFile.subscribe(this._hotkey_openLocalFile.bind(this)); resolve(); }).catch((error: Error) => { this._logger.error(`Fail to init module due error: ${error.message}`); reject(error); }); }); } public destroy(): Promise<void> { return new Promise((resolve) => { Object.keys(this._subscriptions).forEach((key: string) => { this._subscriptions[key].destroy(); }); if (this._active.size === 0) { return resolve(); } Promise.all(Array.from(this._active.values()).map((task: AFileParser) => { return task.abort(); })).catch((error: Error) => { this._logger.error(`Fail to abort active tasks due error: ${error.message}`); }).finally(() => { resolve(); }); }); } public getName(): string { return 'ServiceFileOpener'; } public open(file: string, sessionId: string, parser?: AFileParser, opts?: any): Promise<IOpenFileResult> { return new Promise((resolve, reject) => { fs.stat(file, (error: NodeJS.ErrnoException | null, stats: fs.Stats) => { if (error) { return reject(error); } getParserForFile(file, parser).then((detectedParser: AFileParser | undefined) => { if (detectedParser === undefined) { detectedParser = getDefaultFileParser(); } if (detectedParser === undefined) { return reject(new Error(this._logger.warn(`Fail to find parser for file "${file}"`))); } // To resolve TS type checks, we need this here. const instanceParser: AFileParser = detectedParser; // Create file opener const open = (options: any) => { if (typeof options === 'boolean') { this._logger.debug(`User canceled opening file.`); return resolve({ sourceId: -1, options: undefined }); } const trackingId: string = Tools.guid(); this._setProgress(instanceParser, trackingId, file); // Trigger progress this._incrProgress(instanceParser, trackingId, sessionId, 0); // Store parser this._active.set(sessionId, instanceParser); // Send notification about opening ServiceElectron.IPC.send(new IPCMessages.FileOpenInprogressEvent({ session: sessionId, file: file, })).catch((progressNotificationErr: Error) => { this._logger.warn(`Fail notify render about starting of opening file "${file}" due error: ${progressNotificationErr.message}`); }); // Parser has direct method of reading and writing this._directReadWrite(file, sessionId, instanceParser, options, trackingId).then((sourceId: number) => { instanceParser.destroy().then(() => { // Save recent ServiceFileRecent.save(file, stats.size); // Get meta file info const info = ServiceStreamSource.get(sourceId); if (info !== undefined) { (info as IPCMessages.IStreamSourceNew).id = sourceId; } // Bound filename with session ServiceStreams.addBoundFile(sessionId, file); // Send meta info data ServiceElectron.IPC.send(new IPCMessages.FileOpenDoneEvent({ session: sessionId, file: file, stream: info as IPCMessages.IStreamSourceNew, options: options, })).catch((confirmNotificationErr: Error) => { this._logger.warn(`Fail notify render about opening file "${file}" due error: ${confirmNotificationErr.message}`); }); // Resolve resolve({ sourceId: sourceId, options: options }); }); }).catch((pipeError: Error) => { instanceParser.destroy().then(() => { reject(new Error(this._logger.error(`Fail to directly read file "${file}" due error: ${pipeError.message}`))); }); }).cancel(() => { this._logger.debug(`Reading operation with "${instanceParser.getAlias()}" was canceled`); }).finally(() => { this._unsetProgress(instanceParser, trackingId, sessionId); ServiceStreams.reattachSessionFileHandle(sessionId); this._active.delete(sessionId); }); }; if (opts !== undefined) { // Options are delivered already open(opts); } else { // Request options to open file this._getOptions(file, path.basename(file), instanceParser, stats.size).then((options: any) => { open(options); }).catch((getOptionsError: Error) => { reject(new Error(this._logger.error(`File "${file}" (${instanceParser.getAlias()}) will not be opened due error: ${getOptionsError.message}`))); }); } }).catch((gettingParserError: Error) => { reject(new Error(this._logger.warn(`Fail to find parser due error: ${gettingParserError.message}`))); }); }); }); } public openAsNew(file: string): Promise<void> { return new Promise((resolve, reject) => { ServiceElectron.IPC.request(new IPCMessages.RenderSessionAddRequest(), IPCMessages.RenderSessionAddResponse).then((response: IPCMessages.RenderSessionAddResponse) => { if (response.error !== undefined) { this._logger.warn(`Fail to add new session for file "${file}" due error: ${response.error}`); return reject(new Error(response.error)); } this.open(file, response.session).then(() => { resolve(); }).catch((openFileErr: Error) => { this._logger.warn(`Fail to open file "${file}" due error: ${openFileErr.message}`); reject(openFileErr); }); }).catch((addSessionErr: Error) => { this._logger.warn(`Fail to add new session for file "${file}" due error: ${addSessionErr.message}`); reject(addSessionErr); }); }); } public selectAndOpenFile(): Promise<string | undefined> { return this._openFile(); } private _onRenderReady() { this._recent.pending = false; if (this._recent.path === undefined) { return; } const filename = this._recent.path; const subscription = ServiceStreams.getSubjects().onSessionCreated.subscribe((session) => { subscription.unsubscribe(); this._logger.debug(`Attempt to open recent ${filename}`); this.open(filename, session.stream.guid).catch((err: Error) => { ServiceNotifications.notify({ message: this._logger.warn(`Fail open file "${filename}" due error: ${err.message}`), type: ENotificationType.warning, caption: 'Cannot open file', }); }); }); } private _ipc_FileListRequest(request: IPCMessages.TMessage, response: (instance: IPCMessages.TMessage) => any) { const req: IPCMessages.FileListRequest = request as IPCMessages.FileListRequest; Promise.all( req.files.map((file: string) => { return this._listFiles(file); })).then((fileLists: IPCMessages.IFile[][]) => { response(new IPCMessages.FileListResponse({ files: this._concatFileList(fileLists), })).catch((error: Error) => { this._logger.error(`Fail to respond to files ${req.files} due error: ${error.message}`); }); }).catch((error: Error) => { response(new IPCMessages.FileListResponse({ files: [], error: error.message, })); }); } private _concatFileList(fileLists: IPCMessages.IFile[][]): IPCMessages.IFile[] { const cConcatFiles: IPCMessages.IFile[] = []; return cConcatFiles.concat(...fileLists); } private _onOSRecentFileOpen(_event: Event | undefined, filename: string) { if (this._recent.pending) { this._logger.debug(`Open recent file operation for: ${filename} would be postponed`); this._recent.path = filename; } else { this._logger.debug(`Attempt to open recent ${filename}`); this.openAsNew(filename).catch((err: Error) => { ServiceNotifications.notify({ message: this._logger.warn(`Fail open file "${filename}" due error: ${err.message}`), type: ENotificationType.warning, caption: 'Cannot open file', }); }); } } private _ipc_FileOpenRequest(request: IPCMessages.TMessage, response: (instance: IPCMessages.TMessage) => any) { const req: IPCMessages.FileOpenRequest = request as IPCMessages.FileOpenRequest; this.open(req.file, req.session, undefined, req.options).then((result: IOpenFileResult) => { const info = ServiceStreamSource.get(result.sourceId); if (info !== undefined) { (info as IPCMessages.IStreamSourceNew).id = result.sourceId; } response(new IPCMessages.FileOpenResponse({ stream: info as IPCMessages.IStreamSourceNew, options: result.options, })); }).catch((openError: Error) => { response(new IPCMessages.FileOpenResponse({ error: openError.message, stream: undefined, })); }); } private _listFiles(startFile: string): Promise<IPCMessages.IFile[]> { return new Promise((resolve, reject) => { const allFiles: IPCMessages.IFile[] = []; const self = this; function listAllFiles(file: string): Promise<any> { return new Promise((resolved, rejected) => { fs.lstat(file, (lsErr, stats) => { if (lsErr) { return resolved(allFiles.push({ hasParser: false, isHidden: false, lastModified: 0, lastModifiedDate: new Date(), name: path.basename(file), path: file, size: 0, type: 'file', checked: false, disabled: true, })); } if (stats.isFile()) { // File if (stats.size === 0) { return resolved(allFiles.push({ hasParser: false, isHidden: false, lastModified: stats.mtimeMs, lastModifiedDate: stats.mtime, name: path.basename(file), path: file, size: stats.size, type: 'file', checked: false, disabled: true, })); } Promise.all([getParserForFile(file), isHidden(file)]).then((values: [AFileParser | undefined, boolean | undefined]) => { const parser = values[0]; const hideStatus = (values[1] === undefined) ? false : values[1]; return resolved(allFiles.push({ hasParser: (parser === undefined) ? false : true, isHidden: hideStatus, lastModified: stats.mtimeMs, lastModifiedDate: stats.mtime, name: path.basename(file), path: file, size: stats.size, type: 'file', checked: (parser === undefined || hideStatus) ? false : true, disabled: false, })); }).catch((error: Error) => { self._logger.warn(`Fail to indentify parser of ${file} due to error: ${error.message}`); return resolved(allFiles.push({ hasParser: false, isHidden: false, lastModified: stats.mtimeMs, lastModifiedDate: stats.mtime, name: path.basename(file), path: file, size: stats.size, type: 'file', checked: false, disabled: true, })); }); } else if (!(stats.isDirectory())) { // Neither file nor directory return rejected(new Error(self._logger.warn(`Fail to get file info of ${file} because it is neither a file nor a directory`))); } else { // Directory return fs.readdir(file, (err, files) => { if (err) { self._logger.warn(`Fail to list files of directory ${file} due to error: ${err.message}`); return resolved([]); } else { Promise.all(files.map((subFile: string) => { return listAllFiles(file + '/' + subFile); })).then(() => { resolved(allFiles); }).catch((error: Error) => { rejected(new Error(self._logger.warn(`Fail to list files of directory ${file} info due to error: ${error.message}`))); }); } }); } }); }); } listAllFiles(startFile).then(() => { resolve(allFiles); }).catch((error: Error) => { reject(new Error(self._logger.warn(`Fail to list files of directory ${startFile} info due to error: ${error.message}`))); }); }); } private _getOptions(fullFileName: string, fileName: string, parser: AFileParser, size: number ): Promise<any> { return new Promise((resolve, reject) => { ServiceElectron.IPC.request(new IPCMessages.FileGetOptionsRequest({ fileName: fileName, fullFileName: fullFileName, type: parser.getAlias(), size: size, session: ServiceStreams.getActiveStreamId(), }), IPCMessages.FileGetOptionsResponse).then((response: IPCMessages.FileGetOptionsResponse) => { if (!response.allowed) { return resolve(false); } resolve(response.options); }).catch((error: Error) => { reject(error); }); }); } private _directReadWrite(file: string, sessionId: string, parser: AFileParser, options: { [key: string]: any }, trackingId: string): Tools.CancelablePromise<number, void> { return new Tools.CancelablePromise<number, void>((resolve, reject, cancel) => { // Add new description of source const sourceId: number = ServiceStreamSource.add({ name: path.basename(file), session: sessionId, meta: parser.getMeta() }); // Get destination file const dest: { streamId: string, file: string } | Error = ServiceStreams.getStreamFile(); if (dest instanceof Error) { return reject(dest); } if (parser.parseAndIndex === undefined) { return reject(new Error(`This case isn't possible, but typescript compile.`)); } parser.parseAndIndex(file, dest.file, sourceId, options, (map: IMapItem[]) => { ServiceStreams.pushToStreamFileMap(dest.streamId, map); }, (ticks: ITicks) => { this._incrProgress(parser, trackingId, dest.streamId, ticks.ellapsed / ticks.total); }).then((map: IMapItem[]) => { // Doesn't need to update map here, because it's updated on fly // Notify render resolve(sourceId); }).cancel(() => { cancel(); }).catch((error: Error) => { reject(error); }); }); } private _openFile(parser?: AFileParser): Promise<string | undefined> { return new Promise((resolve, reject) => { const win = ServiceElectron.getBrowserWindow(); if (win === undefined) { return reject(new Error(`No window found`)); } if (parser !== undefined) { dialog.showOpenDialog(win, { properties: ['openFile', 'showHiddenFiles'], filters: parser.getExtnameFilters(), }).then((returnValue: OpenDialogReturnValue) => { if (!(returnValue.filePaths instanceof Array) || returnValue.filePaths.length !== 1) { return resolve(undefined); } const file: string = returnValue.filePaths[0]; this.open(file, ServiceStreams.getActiveStreamId(), parser).then(() => { resolve(file); }).catch((error: Error) => { this._logger.warn(`Fail open file due error: ${error.message}`); reject(new Error(`Fail open file due error: ${error.message}`)); }); }).catch((error: Error) => { this._logger.error(`Fail open file due error: ${error.message}`); reject(new Error(`Fail open file due error: ${error.message}`)); }); } else { dialog.showOpenDialog(win, { properties: ['openFile', 'showHiddenFiles'], filters: [ { name: 'All Files', extensions: ['*'] } ], }).then((returnValue: OpenDialogReturnValue) => { if (!(returnValue.filePaths instanceof Array) || returnValue.filePaths.length !== 1) { return resolve(undefined); } const filename: string = returnValue.filePaths[0]; getParserForFile(filename).then((_parser: AFileParser | undefined) => { if (_parser === undefined) { this._logger.error(`Fail to find a parser for file: ${filename}`); return reject(new Error(`Fail to find a parser for file: ${filename}`)); } ServiceElectron.IPC.request(new IPCMessages.RenderSessionAddRequest(), IPCMessages.RenderSessionAddResponse).then((response: IPCMessages.RenderSessionAddResponse) => { if (response.error !== undefined) { this._logger.warn(`Fail to add new session for file "${filename}" due error: ${response.error}`); return reject(new Error(`Fail to add new session for file "${filename}" due error: ${response.error}`)); } this.open(filename, response.session, _parser).then(() => { resolve(filename); }).catch((error: Error) => { this._logger.warn(`Fail open file "${filename}" due error: ${error.message}`); reject(new Error(`Fail open file "${filename}" due error: ${error.message}`)); }); }).catch((addSessionErr: Error) => { this._logger.warn(`Fail to add new session for file "${filename}" due error: ${addSessionErr.message}`); reject(new Error(`Fail to add new session for file "${filename}" due error: ${addSessionErr.message}`)); }); }).catch((error: Error) => { this._logger.error(`Error to open file "${filename}" due error: ${error.message}`); reject(new Error(`Error to open file "${filename}" due error: ${error.message}`)); }); }).catch((error: Error) => { this._logger.error(`Fail open file due error: ${error.message}`); reject(new Error(`Fail open file due error: ${error.message}`)); }); } }); } private _hotkey_openLocalFile() { this._openFile().catch((error: Error) => { this._logger.error(`Fail open file on CMD + P: ${error.message}`); }); } private _setProgress(parser: AFileParser, trackingId: string, file: string) { ServiceStreams.addProgressSession(trackingId, file); } private _unsetProgress(parser: AFileParser, trackingId: string, sessionId: string) { ServiceStreams.removeProgressSession(trackingId, sessionId); } private _incrProgress(parser: AFileParser, trackingId: string, sessionId: string, value: number) { ServiceStreams.updateProgressSession(trackingId, value, sessionId); } private _onSessionClosed(guid: string) { // Check for active tasks for session const task: AFileParser | undefined = this._active.get(guid); if (task === undefined) { // No any active tasks for closed session return; } task.abort().then(() => { this._logger.debug(`Session "${guid}" is closed. Task "${task.getAlias()}" is aborted.`); }); } } export default (new ServiceFileOpener());
the_stack
import { BuildError } from './errors'; import * as helpers from './helpers'; let originalEnv: any = null; describe('helpers', () => { beforeEach(() => { originalEnv = process.env; process.env = {}; }); afterEach(() => { process.env = originalEnv; }); describe('getIntPropertyValue', () => { it('should return an int', () => { // arrange const propertyName = 'test'; const propertyValue = '3000'; process.env[propertyName] = propertyValue; // act const result = helpers.getIntPropertyValue(propertyName); // assert expect(result).toEqual(3000); }); it('should round to an int', () => { // arrange const propertyName = 'test'; const propertyValue = '3000.03'; process.env[propertyName] = propertyValue; // act const result = helpers.getIntPropertyValue(propertyName); // assert expect(result).toEqual(3000); }); it('should round to a NaN', () => { // arrange const propertyName = 'test'; const propertyValue = 'tacos'; process.env[propertyName] = propertyValue; // act const result = helpers.getIntPropertyValue(propertyName); // assert expect(result).toEqual(NaN); }); }); describe('getBooleanPropertyValue', () => { beforeEach(() => { originalEnv = process.env; process.env = {}; }); afterEach(() => { process.env = originalEnv; }); it('should return true when value is "true"', () => { // arrange const propertyName = 'test'; const propertyValue = 'true'; process.env[propertyName] = propertyValue; // act const result = helpers.getBooleanPropertyValue(propertyName); // assert expect(result).toEqual(true); }); it('should return false when value is undefined/null', () => { // arrange const propertyName = 'test'; // act const result = helpers.getBooleanPropertyValue(propertyName); // assert expect(result).toEqual(false); }); it('should return false when value is not "true"', () => { // arrange const propertyName = 'test'; const propertyValue = 'taco'; process.env[propertyName] = propertyValue; // act const result = helpers.getBooleanPropertyValue(propertyName); // assert expect(result).toEqual(false); }); }); describe('processStatsImpl', () => { it('should convert object graph to known module map', () => { // arrange const moduleOne = '/Users/noone/myModuleOne.js'; const moduleTwo = '/Users/noone/myModuleTwo.js'; const moduleThree = '/Users/noone/myModuleThree.js'; const moduleFour = '/Users/noone/myModuleFour.js'; const objectGraph: any = { modules: [ { identifier: moduleOne, reasons: [ { moduleIdentifier: moduleTwo }, { moduleIdentifier: moduleThree } ] }, { identifier: moduleTwo, reasons: [ { moduleIdentifier: moduleThree } ] }, { identifier: moduleThree, reasons: [ { moduleIdentifier: moduleOne } ] }, { identifier: moduleFour, reasons: [] } ] }; // act const result = helpers.processStatsImpl(objectGraph); // assert const setOne = result.get(moduleOne); expect(setOne.has(moduleTwo)).toBeTruthy(); expect(setOne.has(moduleThree)).toBeTruthy(); const setTwo = result.get(moduleTwo); expect(setTwo.has(moduleThree)).toBeTruthy(); const setThree = result.get(moduleThree); expect(setThree.has(moduleOne)).toBeTruthy(); const setFour = result.get(moduleFour); expect(setFour.size).toEqual(0); }); }); describe('ensureSuffix', () => { it('should not include the suffix of a string that already has the suffix', () => { expect(helpers.ensureSuffix('dan dan the sunshine man', ' man')).toEqual('dan dan the sunshine man'); }); it('should ensure the suffix of a string without the suffix', () => { expect(helpers.ensureSuffix('dan dan the sunshine', ' man')).toEqual('dan dan the sunshine man'); }); }); describe('removeSuffix', () => { it('should remove the suffix of a string that has the suffix', () => { expect(helpers.removeSuffix('dan dan the sunshine man', ' man')).toEqual('dan dan the sunshine'); }); it('should do nothing if the string does not have the suffix', () => { expect(helpers.removeSuffix('dan dan the sunshine man', ' woman')).toEqual('dan dan the sunshine man'); }); }); describe('replaceAll', () => { it('should replace a variable', () => { expect(helpers.replaceAll('hello $VAR world', '$VAR', 'my')).toEqual('hello my world'); }); it('should replace a variable with newlines', () => { expect(helpers.replaceAll('hello\n $VARMORETEXT\n world', '$VAR', 'NO')).toEqual('hello\n NOMORETEXT\n world'); }); it('should replace a variable and handle undefined', () => { expect(helpers.replaceAll('hello $VAR world', '$VAR', undefined)).toEqual('hello world'); }); }); describe('buildErrorToJson', () => { it('should return a pojo', () => { const buildError = new BuildError('message1'); buildError.name = 'name1'; buildError.stack = 'stack1'; buildError.isFatal = true; buildError.hasBeenLogged = false; const object = helpers.buildErrorToJson(buildError); expect(object.message).toEqual('message1'); expect(object.name).toEqual(buildError.name); expect(object.stack).toEqual(buildError.stack); expect(object.isFatal).toEqual(buildError.isFatal); expect(object.hasBeenLogged).toEqual(buildError.hasBeenLogged); }); }); describe('upperCaseFirst', () => { it('should capitalize a one character string', () => { const result = helpers.upperCaseFirst('t'); expect(result).toEqual('T'); }); it('should capitalize the first character of string', () => { const result = helpers.upperCaseFirst('taco'); expect(result).toEqual('Taco'); }); }); describe('removeCaseFromString', () => { const map = new Map<string, string>(); map.set('test', 'test'); map.set('TEST', 'test'); map.set('testString', 'test string'); map.set('testString123', 'test string123'); map.set('testString_1_2_3', 'test string 1 2 3'); map.set('x_256', 'x 256'); map.set('anHTMLTag', 'an html tag'); map.set('ID123String', 'id123 string'); map.set('Id123String', 'id123 string'); map.set('foo bar123', 'foo bar123'); map.set('a1bStar', 'a1b star'); map.set('CONSTANT_CASE', 'constant case'); map.set('CONST123_FOO', 'const123 foo'); map.set('FOO_bar', 'foo bar'); map.set('dot.case', 'dot case'); map.set('path/case', 'path case'); map.set('snake_case', 'snake case'); map.set('snake_case123', 'snake case123'); map.set('snake_case_123', 'snake case 123'); map.set('"quotes"', 'quotes'); map.set('version 0.45.0', 'version 0 45 0'); map.set('version 0..78..9', 'version 0 78 9'); map.set('version 4_99/4', 'version 4 99 4'); map.set('amazon s3 data', 'amazon s3 data'); map.set('foo_13_bar', 'foo 13 bar'); map.forEach((value: string, key: string) => { const result = helpers.removeCaseFromString(key); expect(result).toEqual(value); }); }); describe('sentenceCase', () => { it('should lower case a single word', () => { const resultOne = helpers.sentenceCase('test'); const resultTwo = helpers.sentenceCase('TEST'); expect(resultOne).toEqual('Test'); expect(resultTwo).toEqual('Test'); }); it('should sentence case regular sentence cased strings', () => { const resultOne = helpers.sentenceCase('test string'); const resultTwo = helpers.sentenceCase('Test String'); expect(resultOne).toEqual('Test string'); expect(resultTwo).toEqual('Test string'); }); it('should sentence case non-alphanumeric separators', () => { const resultOne = helpers.sentenceCase('dot.case'); const resultTwo = helpers.sentenceCase('path/case'); expect(resultOne).toEqual('Dot case'); expect(resultTwo).toEqual('Path case'); }); }); describe('camelCase', () => { it('should lower case a single word', () => { const resultOne = helpers.camelCase('test'); const resultTwo = helpers.camelCase('TEST'); expect(resultOne).toEqual('test'); expect(resultTwo).toEqual('test'); }); it('should camel case regular sentence cased strings', () => { expect(helpers.camelCase('test string')).toEqual('testString'); expect(helpers.camelCase('Test String')).toEqual('testString'); }); it('should camel case non-alphanumeric separators', () => { expect(helpers.camelCase('dot.case')).toEqual('dotCase'); expect(helpers.camelCase('path/case')).toEqual('pathCase'); }); it('should underscore periods inside numbers', () => { expect(helpers.camelCase('version 1.2.10')).toEqual('version_1_2_10'); expect(helpers.camelCase('version 1.21.0')).toEqual('version_1_21_0'); }); it('should camel case pascal cased strings', () => { expect(helpers.camelCase('TestString')).toEqual('testString'); }); it('should camel case non-latin strings', () => { expect(helpers.camelCase('simple éxample')).toEqual('simpleÉxample'); }); }); describe('paramCase', () => { it('should param case a single word', () => { expect(helpers.paramCase('test')).toEqual('test'); expect(helpers.paramCase('TEST')).toEqual('test'); }); it('should param case regular sentence cased strings', () => { expect(helpers.paramCase('test string')).toEqual('test-string'); expect(helpers.paramCase('Test String')).toEqual('test-string'); }); it('should param case non-alphanumeric separators', () => { expect(helpers.paramCase('dot.case')).toEqual('dot-case'); expect(helpers.paramCase('path/case')).toEqual('path-case'); }); it('should param case param cased strings', () => { expect(helpers.paramCase('TestString')).toEqual('test-string'); expect(helpers.paramCase('testString1_2_3')).toEqual('test-string1-2-3'); expect(helpers.paramCase('testString_1_2_3')).toEqual('test-string-1-2-3'); }); it('should param case non-latin strings', () => { expect(helpers.paramCase('My Entrée')).toEqual('my-entrée'); }); }); describe('pascalCase', () => { it('should pascal case a single word', () => { expect(helpers.pascalCase('test')).toEqual('Test'); expect(helpers.pascalCase('TEST')).toEqual('Test'); }); it('should pascal case regular sentence cased strings', () => { expect(helpers.pascalCase('test string')).toEqual('TestString'); expect(helpers.pascalCase('Test String')).toEqual('TestString'); }); it('should pascal case non-alphanumeric separators', () => { expect(helpers.pascalCase('dot.case')).toEqual('DotCase'); expect(helpers.pascalCase('path/case')).toEqual('PathCase'); }); it('should pascal case pascal cased strings', () => { expect(helpers.pascalCase('TestString')).toEqual('TestString'); }); }); describe('snakeCase', () => { it('should convert the phrase to use underscores', () => { expect(helpers.snakeCase('taco bell')).toEqual('taco_bell'); }); }); describe('constantCase', () => { it('should capitalize and separate words by underscore', () => { expect(helpers.constantCase('taco bell')).toEqual('TACO_BELL'); }); it('should convert camel case to correct case', () => { expect(helpers.constantCase('TacoBell')).toEqual('TACO_BELL'); }); }); });
the_stack
class ArrayHelper { /** * Clone an array or an object. If an object is passed, a shallow clone will be created. * * @static * @param {*} arr The array or object to be cloned. * @returns {*} A clone of the array or object. */ static clone(arr) { let out = Array.isArray(arr) ? Array() : {}; for (let key in arr) { let value = arr[key]; if (typeof value.clone === 'function') { out[key] = value.clone(); } else { out[key] = (typeof value === 'object') ? ArrayHelper.clone(value) : value; } } return out; } /** * Returns a boolean indicating whether or not the two arrays contain the same elements. * Only supports 1d, non-nested arrays. * * @static * @param {Array} arrA An array. * @param {Array} arrB An array. * @returns {Boolean} A boolean indicating whether or not the two arrays contain the same elements. */ static equals(arrA, arrB) { if (arrA.length !== arrB.length) { return false; } let tmpA = arrA.slice().sort(); let tmpB = arrB.slice().sort(); for (var i = 0; i < tmpA.length; i++) { if (tmpA[i] !== tmpB[i]) { return false; } } return true; } /** * Returns a string representation of an array. If the array contains objects with an id property, the id property is printed for each of the elements. * * @static * @param {Object[]} arr An array. * @param {*} arr[].id If the array contains an object with the property 'id', the properties value is printed. Else, the array elements value is printend. * @returns {String} A string representation of the array. */ static print(arr) { if (arr.length == 0) { return ''; } let s = '('; for (let i = 0; i < arr.length; i++) { s += arr[i].id ? arr[i].id + ', ' : arr[i] + ', '; } s = s.substring(0, s.length - 2); return s + ')'; } /** * Run a function for each element in the array. The element is supplied as an argument for the callback function * * @static * @param {Array} arr An array. * @param {Function} callback The callback function that is called for each element. */ static each(arr, callback) { for (let i = 0; i < arr.length; i++) { callback(arr[i]); } } /** * Return the array element from an array containing objects, where a property of the object is set to a given value. * * @static * @param {Array} arr An array. * @param {(String|Number)} property A property contained within an object in the array. * @param {(String|Number)} value The value of the property. * @returns {*} The array element matching the value. */ static get(arr, property, value) { for (let i = 0; i < arr.length; i++) { if (arr[i][property] == value) { return arr[i]; } } } /** * Checks whether or not an array contains a given value. the options object passed as a second argument can contain three properties. value: The value to be searched for. property: The property that is to be searched for a given value. func: A function that is used as a callback to return either true or false in order to do a custom comparison. * * @static * @param {Array} arr An array. * @param {Object} options See method description. * @param {*} options.value The value for which to check. * @param {String} [options.property=undefined] The property on which to check. * @param {Function} [options.func=undefined] A custom property function. * @returns {Boolean} A boolean whether or not the array contains a value. */ static contains(arr, options) { if (!options.property && !options.func) { for (let i = 0; i < arr.length; i++) { if (arr[i] == options.value) { return true; } } } else if (options.func) { for (let i = 0; i < arr.length; i++) { if (options.func(arr[i])) { return true; } } } else { for (let i = 0; i < arr.length; i++) { if (arr[i][options.property] == options.value) { return true; } } } return false; } /** * Returns an array containing the intersection between two arrays. That is, values that are common to both arrays. * * @static * @param {Array} arrA An array. * @param {Array} arrB An array. * @returns {Array} The intersecting vlaues. */ static intersection(arrA, arrB) { let intersection = new Array(); for (let i = 0; i < arrA.length; i++) { for (let j = 0; j < arrB.length; j++) { if (arrA[i] === arrB[j]) { intersection.push(arrA[i]); } } } return intersection; } /** * Returns an array of unique elements contained in an array. * * @static * @param {Array} arr An array. * @returns {Array} An array of unique elements contained within the array supplied as an argument. */ static unique(arr) { let contains = {}; return arr.filter(function (i) { // using !== instead of hasOwnProperty (http://andrew.hedges.name/experiments/in/) return contains[i] !== undefined ? false : (contains[i] = true); }); } /** * Count the number of occurences of a value in an array. * * @static * @param {Array} arr An array. * @param {*} value A value to be counted. * @returns {Number} The number of occurences of a value in the array. */ static count(arr, value) { let count = 0; for (let i = 0; i < arr.length; i++) { if (arr[i] === value) { count++; } } return count; } /** * Toggles the value of an array. If a value is not contained in an array, the array returned will contain all the values of the original array including the value. If a value is contained in an array, the array returned will contain all the values of the original array excluding the value. * * @static * @param {Array} arr An array. * @param {*} value A value to be toggled. * @returns {Array} The toggled array. */ static toggle(arr, value) { let newArr = Array(); let removed = false; for (let i = 0; i < arr.length; i++) { // Do not copy value if it exists if (arr[i] !== value) { newArr.push(arr[i]); } else { // The element was not copied to the new array, which // means it was removed removed = true; } } // If the element was not removed, then it was not in the array // so add it if (!removed) { newArr.push(value); } return newArr; } /** * Remove a value from an array. * * @static * @param {Array} arr An array. * @param {*} value A value to be removed. * @returns {Array} A new array with the element with a given value removed. */ static remove(arr, value) { let tmp = Array(); for (let i = 0; i < arr.length; i++) { if (arr[i] !== value) { tmp.push(arr[i]); } } return tmp; } /** * Remove a value from an array with unique values. * * @static * @param {Array} arr An array. * @param {*} value A value to be removed. * @returns {Array} An array with the element with a given value removed. */ static removeUnique(arr, value) { let index = arr.indexOf(value); if (index > -1) { arr.splice(index, 1); } return arr; } /** * Remove all elements contained in one array from another array. * * @static * @param {Array} arrA The array to be filtered. * @param {Array} arrB The array containing elements that will be removed from the other array. * @returns {Array} The filtered array. */ static removeAll(arrA, arrB) { return arrA.filter(function (item) { return arrB.indexOf(item) === -1; }); } /** * Merges two arrays and returns the result. The first array will be appended to the second array. * * @static * @param {Array} arrA An array. * @param {Array} arrB An array. * @returns {Array} The merged array. */ static merge(arrA, arrB) { let arr = new Array(arrA.length + arrB.length); for (let i = 0; i < arrA.length; i++) { arr[i] = arrA[i]; } for (let i = 0; i < arrB.length; i++) { arr[arrA.length + i] = arrB[i]; } return arr; } /** * Checks whether or not an array contains all the elements of another array, without regard to the order. * * @static * @param {Array} arrA An array. * @param {Array} arrB An array. * @returns {Boolean} A boolean indicating whether or not both array contain the same elements. */ static containsAll(arrA, arrB) { let containing = 0; for (let i = 0; i < arrA.length; i++) { for (let j = 0; j < arrB.length; j++) { if (arrA[i] === arrB[j]) { containing++; } } } return containing === arrB.length; } /** * Sort an array of atomic number information. Where the number is indicated as x, x.y, x.y.z, ... * * @param {Object[]} arr An array of vertex ids with their associated atomic numbers. * @param {Number} arr[].vertexId A vertex id. * @param {String} arr[].atomicNumber The atomic number associated with the vertex id. * @returns {Object[]} The array sorted by atomic number. Example of an array entry: { atomicNumber: 2, vertexId: 5 }. */ static sortByAtomicNumberDesc(arr) { let map = arr.map(function(e, i) { return { index: i, value: e.atomicNumber.split('.').map(Number) }; }); map.sort(function(a, b) { let min = Math.min(b.value.length, a.value.length); let i = 0; while(i < min && b.value[i] === a.value[i]) { i++; } return i === min ? b.value.length - a.value.length : b.value[i] - a.value[i]; }); return map.map(function(e) { return arr[e.index]; }); } /** * Copies a an n-dimensional array. * * @param {Array} arr The array to be copied. * @returns {Array} The copy. */ static deepCopy(arr) { let newArr = Array(); for (let i = 0; i < arr.length; i++) { let item = arr[i]; if (item instanceof Array) { newArr[i] = ArrayHelper.deepCopy(item); } else { newArr[i] = item; } } return newArr; } } export default ArrayHelper;
the_stack
import * as React from "react"; import { Geometry, Point, Prototypes, ZoomInfo } from "../../../core"; import { DragContext, DragModifiers, Droppable } from "../../controllers"; import * as globals from "../../globals"; import { classNames } from "../../utils"; export interface DropZoneViewProps { zone: Prototypes.DropZones.Description; zoom: ZoomInfo; onDragEnter: ( data: any ) => (point: Point, modifiers: DragModifiers) => boolean; } export interface DropZoneViewState { active: boolean; } export class DropZoneView extends React.Component<DropZoneViewProps, DropZoneViewState> implements Droppable { public refs: { container: SVGGElement; }; constructor(props: DropZoneViewProps) { super(props); this.state = { active: false }; } public componentDidMount() { globals.dragController.registerDroppable(this, this.refs.container); } public componentWillUnmount() { globals.dragController.unregisterDroppable(this); } public onDragEnter(ctx: DragContext) { const data = ctx.data; const handler = this.props.onDragEnter(data); if (handler) { this.setState({ active: true, }); ctx.onLeave(() => { this.setState({ active: false, }); }); ctx.onDrop((point: Point, modifiers: DragModifiers) => { return handler(point, modifiers); }); return true; } else { return false; } } public makeClosePath(...points: Point[]) { return `M${points.map((d) => `${d.x},${d.y}`).join("L")}Z`; } public makeDashedLine(p1: Point, p2: Point) { return ( <line className="dropzone-element-dashline" x1={p1.x} y1={p1.y} x2={p2.x} y2={p2.y} /> ); } public makeLine( p1: Point, p2: Point, arrow1: number = 0, arrow2: number = 0 ) { const d1 = Geometry.vectorScale( Geometry.vectorNormalize(Geometry.vectorSub(p2, p1)), arrow1 ); const n1 = Geometry.vectorScale(Geometry.vectorRotate90(d1), 0.25); const p1n = Geometry.vectorAdd(p1, d1); const p1a1 = Geometry.vectorAdd(p1n, n1); const p1a2 = Geometry.vectorSub(p1n, n1); const d2 = Geometry.vectorScale( Geometry.vectorNormalize(Geometry.vectorSub(p2, p1)), arrow2 ); const n2 = Geometry.vectorScale(Geometry.vectorRotate90(d2), 0.25); const p2n = Geometry.vectorSub(p2, d2); const p2a1 = Geometry.vectorAdd(p2n, n2); const p2a2 = Geometry.vectorSub(p2n, n2); return ( <g className="dropzone-element-line"> <line x1={p1n.x} y1={p1n.y} x2={p2n.x} y2={p2n.y} style={{ strokeLinecap: "butt" }} /> {arrow1 > 0 ? <path d={this.makeClosePath(p1a1, p1a2, p1)} /> : null}, {arrow2 > 0 ? <path d={this.makeClosePath(p2a1, p2a2, p2)} /> : null} </g> ); } public makeTextAtCenter( p1: Point, p2: Point, text: string, dx: number = 0, dy: number = 0 ) { const cx = (p1.x + p2.x) / 2; const cy = (p1.y + p2.y) / 2; const angle = Math.atan2(p2.y - p1.y, p2.x - p1.x); const height = 9; let extra = ""; if (Math.abs(angle) < Math.PI / 2) { extra = `translate(0, ${-height / 2}) rotate(180) translate(0, ${ height / 2 })`; } return ( <g transform={`translate(${cx},${cy}) rotate(${ ((angle + Math.PI) / Math.PI) * 180 }) translate(${dx},${dy}) ${extra}`} > <text className="dropzone-element-text" x={0} y={0} style={{ textAnchor: "middle" }} > {text} </text> </g> ); } // eslint-disable-next-line public renderElement(z: Prototypes.DropZones.Description) { switch (z.type) { case "line": { const zone = z as Prototypes.DropZones.Line; let { p1: zp2, p2: zp1 } = zone; zp1 = Geometry.applyZoom(this.props.zoom, { x: zp1.x, y: -zp1.y }); zp2 = Geometry.applyZoom(this.props.zoom, { x: zp2.x, y: -zp2.y }); const vD = Geometry.vectorNormalize(Geometry.vectorSub(zp2, zp1)); const vN = Geometry.vectorRotate90(vD); return ( <g> <path className="dropzone-highlighter" d={this.makeClosePath( // zp1, zp2, Geometry.vectorAdd(zp1, Geometry.vectorScale(vN, -10)), Geometry.vectorAdd(zp2, Geometry.vectorScale(vN, -10)), Geometry.vectorAdd(zp2, Geometry.vectorScale(vN, 25)), Geometry.vectorAdd(zp1, Geometry.vectorScale(vN, 25)) )} /> <path className="dropzone-element-solid" d={this.makeClosePath( zp1, zp2, Geometry.vectorAdd(zp2, Geometry.vectorScale(vN, 5)), Geometry.vectorAdd(zp1, Geometry.vectorScale(vN, 5)) )} /> {this.makeTextAtCenter(zp1, zp2, zone.title, 0, -6)} </g> ); } case "arc": { const makeArc = ( x: number, y: number, radius: number, startAngle: number, endAngle: number ) => { const angleOffset = -90; const start = [ x + radius * Math.cos(Geometry.degreesToRadians(angleOffset + startAngle)), y + radius * Math.sin(Geometry.degreesToRadians(angleOffset + startAngle)), ]; const end = [ x + radius * Math.cos(Geometry.degreesToRadians(angleOffset + endAngle)), y + radius * Math.sin(Geometry.degreesToRadians(angleOffset + endAngle)), ]; const largeArcFlag = endAngle - startAngle < 180 ? 0 : 1; return [ "M", start[0].toFixed(6), start[1].toFixed(6), "A", radius.toFixed(6), radius.toFixed(6), 0, largeArcFlag, 1, end[0].toFixed(6), end[1].toFixed(6), ].join(" "); }; const zone = z as Prototypes.DropZones.Arc; const zcenter = Geometry.applyZoom(this.props.zoom, { x: zone.center.x, y: -zone.center.y, }); const zradius = zone.radius * this.props.zoom.scale; const width = 5; const angle1 = zone.angleStart; let angle2 = zone.angleEnd; const angleCenter = (angle1 + angle2) / 2; if ((angle2 - angle1) % 360 == 0) { angle2 -= 1e-4; } const arc = makeArc( zcenter.x, zcenter.y, zradius + width / 2, angle1, angle2 ); const p1 = Geometry.vectorAdd( zcenter, Geometry.vectorRotate( { x: zradius + 5, y: 0 }, Geometry.degreesToRadians(-angleCenter + 1 + 90) ) ); const p2 = Geometry.vectorAdd( zcenter, Geometry.vectorRotate( { x: zradius + 5, y: 0 }, Geometry.degreesToRadians(-angleCenter - 1 + 90) ) ); return ( <g> <path className="dropzone-highlighter-stroke" d={arc} style={{ strokeWidth: 25 }} /> <path className="dropzone-element-arc" d={arc} style={{ strokeWidth: 5 }} /> {this.makeTextAtCenter(p1, p2, zone.title, 0, 8)} </g> ); } // case "coordinate": { // let zone = z as Prototypes.DropZones.Coordinate; // let p1 = Geometry.applyZoom(this.props.zoom, { x: zone.p.x, y: zone.p.y }); // let p2 = Geometry.applyZoom(this.props.zoom, { x: zone.p.x, y: zone.p.y }); // let distance = 20; // let length = 25; // if (zone.mode == "x") { // p1.y -= distance * zone.direction; // p2.y -= distance * zone.direction; // p1.x += length / 2 * zone.direction; // p2.x -= length / 2 * zone.direction; // } // if (zone.mode == "y") { // p1.x -= distance * zone.direction; // p2.x -= distance * zone.direction; // p1.y -= length / 2 * zone.direction; // p2.y += length / 2 * zone.direction; // } // return ( // <g> // {zone.mode == "x" ? ( // <rect className="dropzone-highlighter" // x={Math.min(p1.x, p2.x)} // width={Math.abs(p2.x - p1.x)} // y={p1.y - 10} // height={20} // /> // ) : ( // <rect className="dropzone-highlighter" // y={Math.min(p1.y, p2.y)} // height={Math.abs(p2.y - p1.y)} // x={p1.x - 10} // width={20} // /> // )} // {this.makeDashedLine({ x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 }, Geometry.applyZoom(this.props.zoom, zone.p))} // {this.makeLine(p1, p2, 10, 10)} // {this.makeTextAtCenter(p1, p2, zone.title, 0, -5)} // </g> // ) // } case "region": { const zone = z as Prototypes.DropZones.Region; const p1 = Geometry.applyZoom(this.props.zoom, { x: zone.p1.x, y: -zone.p1.y, }); const p2 = Geometry.applyZoom(this.props.zoom, { x: zone.p2.x, y: -zone.p2.y, }); return ( <g> <rect className="dropzone-highlighter" opacity={0.5} x={Math.min(p1.x, p2.x)} y={Math.min(p1.y, p2.y)} width={Math.abs(p2.x - p1.x)} height={Math.abs(p2.y - p1.y)} /> <rect className="dropzone-element-solid" opacity={0.5} x={Math.min(p1.x, p2.x)} y={Math.min(p1.y, p2.y)} width={Math.abs(p2.x - p1.x)} height={Math.abs(p2.y - p1.y)} /> {this.makeTextAtCenter( { x: p1.x, y: (p1.y + p2.y) / 2 }, { x: p2.x, y: (p1.y + p2.y) / 2 }, zone.title, 0, 0 )} </g> ); } case "rectangle": { const zone = z as Prototypes.DropZones.Rectangle; const c = Geometry.applyZoom(this.props.zoom, { x: zone.cx, y: -zone.cy, }); const width = this.props.zoom.scale * zone.width; const height = this.props.zoom.scale * zone.height; return ( <g transform={`translate(${c.x},${c.y}) rotate(${-zone.rotation})`}> <rect className="dropzone-highlighter" opacity={0.5} x={-width / 2} y={-height / 2} width={width} height={height} /> <rect className="dropzone-element-solid" opacity={0.5} x={-width / 2} y={-height / 2} width={width} height={height} /> {this.makeTextAtCenter( { x: -width / 2, y: height / 2 }, { x: width / 2, y: height / 2 }, zone.title, 0, 0 )} </g> ); } } } public render() { const z = this.props.zone; return ( <g ref="container" className={classNames("dropzone", `dropzone-${z.type}`, [ "active", this.state.active, ])} > {this.renderElement(z)} </g> ); } }
the_stack
import { JSToken, stringToTokens } from "../../javascript"; import { TokenReader, IRenderSettings, ScriptLanguages, defaultRenderSettings, IRenderable } from "../../../helpers"; import { ValueTypes } from "../value/value"; import { TypeSignature } from "../types/type-signature"; import { Expression, VariableReference, tokenAsIdent } from "../value/expression"; import type { Module } from "../module"; import { ClassDeclaration } from "../constructs/class"; interface IVariableSettings { spread: boolean, typeSignature?: TypeSignature, parent: Module | ClassDeclaration, isConstant: boolean, value: ValueTypes, isStatic: boolean, isAbstract: boolean, context: VariableContext, isOptional: boolean, // For optional class fields } export enum VariableContext { Destruction, Parameter, Statement, For, Import } /** * Class that represents a variable declaration though using const, let, var declaration or a existing in a class field */ export class VariableDeclaration implements IRenderable, IVariableSettings { name: string; entries?: Map<string | number, VariableDeclaration | null>; value: ValueTypes; typeSignature?: TypeSignature; parent: Module | ClassDeclaration; isConstant: boolean = true; spread: boolean = false; from?: VariableReference; context: VariableContext = VariableContext.Statement; isStatic: boolean = false; isAbstract: boolean = false; isOptional: boolean = false; constructor( name: string | Map<string | number, VariableDeclaration | null>, settings: Partial<IVariableSettings> = {} ) { if (typeof name === "string") { this.name = name; } else if (name !== null) { this.entries = name; for (const entry of this.entries.values()) { if (entry) { entry.context = VariableContext.Destruction; } } } if (typeof settings.context === "undefined") settings.context = VariableContext.Statement; // TODO temp: Object.assign(this, settings); } render(settings: IRenderSettings = defaultRenderSettings): string { let acc = ""; if (this.isAbstract) { if (settings.scriptLanguage === ScriptLanguages.Typescript) { acc += "abstract "; } else { return ""; } } if (this.isStatic) acc += "static "; if ( (this.context === VariableContext.Statement || this.context === VariableContext.For) && !(this.parent instanceof ClassDeclaration) ) { if (!this.isConstant) { acc += "let "; } else { acc += "const "; } } if (this.context === VariableContext.Parameter && this.spread) { acc += "..."; } if (this.name) { acc += this.name; if (settings.scriptLanguage === ScriptLanguages.Typescript && this.isOptional) { acc += "?"; } } else if (this.entries) { // If all keys are numbers it is a array destructure // TODO Number.isFinite ??? if (Array.from(this.entries.keys()).every(key => Number.isFinite(key as number))) { acc += "["; for (let i = 0; i < this.entries.size; i++) { // TODO temp implementation acc += this.entries.get(i)!.render(settings); if (i !== this.entries.size - 1) acc += settings.minify ? "," : ", " } acc += "]"; } else { acc += "{"; let count = this.entries.size; for (const declaration of this.entries.values()) { if (declaration) { acc += declaration.render(settings); } if (--count > 0) acc += settings.minify ? "," : ", " } acc += "}"; } } if ( settings.scriptLanguage === ScriptLanguages.Typescript && this.context !== VariableContext.Import && this.context !== VariableContext.Destruction ) { if (this.typeSignature) { acc += ": " acc += this.typeSignature.render(settings); } } if (this.value) { acc += settings.minify ? "=" : " = "; acc += this.value.render(settings); } return acc; } /** * Returns a variableReference to the declared variable. TODO kinda temp */ toReference(): VariableReference { return new VariableReference(this.name); } static fromTokens(reader: TokenReader<JSToken>, settings: Partial<IVariableSettings> = {}): VariableDeclaration { let isConstant = false; if (reader.current.type === JSToken.Const) { isConstant = true; reader.move(); } else if (reader.current.type === JSToken.Let) { reader.move(); } else if (reader.current.type === JSToken.Var) { reader.move(); } let spread: boolean = settings.spread ?? false; if (settings.context === VariableContext.Parameter && reader.current.type === JSToken.Spread) { spread = true; reader.move(); } // Parse variable names let name: string | null = null; let entries: Map<string | number, VariableDeclaration | null> | null = null; try { name = reader.current.value ?? tokenAsIdent(reader.current.type); reader.move(); } catch { } if (name === null) { // Array destructuring eg const [a, b] if (reader.current.type === JSToken.OpenSquare) { reader.move(); entries = new Map(); let index = 0; while (reader.current.type as JSToken !== JSToken.CloseSquare) { if (reader.current.type === JSToken.OpenSquare) { entries.set(index++, VariableDeclaration.fromTokens(reader, { context: VariableContext.Destruction })); // TODO signal source is from destructor and not to do type & multiple etc continue; } else if (reader.current.type === JSToken.Comma) { entries.set(index++, null); reader.move(); continue; } else if (reader.current.type === JSToken.Spread) { reader.move(); const variable = VariableDeclaration.fromTokens(reader, { context: VariableContext.Destruction }); variable.spread = true; entries.set(index++, variable); } else { entries.set(index++, VariableDeclaration.fromTokens(reader, { context: VariableContext.Destruction })); } if (reader.current.type === JSToken.CloseSquare) break; else reader.expectNext(JSToken.Comma); } reader.move(); } // Object destructuring eg const {a, b} else if (reader.current.type === JSToken.OpenCurly) { reader.move(); entries = new Map(); while (reader.current.type as JSToken !== JSToken.CloseCurly) { let spread = false; if (reader.current.type as JSToken === JSToken.Spread) { reader.move(); spread = true; } reader.expect(JSToken.Identifier); const identifer = reader.current.value!; reader.move(); if (spread) { entries.set(identifer, new VariableDeclaration(identifer, { spread: true })) } else if (reader.current.type as JSToken === JSToken.Colon) { reader.move(); reader.expect(JSToken.Identifier); // TODO from entries.set(identifer, VariableDeclaration.fromTokens(reader, { context: VariableContext.Destruction })); } else if (reader.current.type as JSToken === JSToken.Assign) { reader.move(); const value = Expression.fromTokens(reader); entries.set(identifer, new VariableDeclaration(identifer, {value})); } else { entries.set(identifer, new VariableDeclaration(identifer)); } if (reader.current.type as JSToken === JSToken.CloseCurly) break; else reader.expectNext(JSToken.Comma); } reader.move(); } else { reader.throwExpect("Expected Ident, [ or {") } } // Type signature let type: TypeSignature | undefined; // Optionality under classes and function parameters let isOptional = false; if (reader.current.type === JSToken.OptionalMember && (settings.parent instanceof ClassDeclaration || settings.context === VariableContext.Parameter)) { isOptional = true; reader.move(); type = TypeSignature.fromTokens(reader); } if (reader.current.type === JSToken.Colon) { reader.move(); type = TypeSignature.fromTokens(reader); } // Assigned value let value: ValueTypes | undefined; if (reader.current.type as JSToken === JSToken.Assign) { reader.move(); value = Expression.fromTokens(reader); } // Throw if constant variable is not defined a variable. Not sure why to not do for but it is written different if (isConstant && !value && settings.context !== VariableContext.For) { reader.throwExpect("Expected assignment for constant variable"); } if (reader.current.type as JSToken === JSToken.Comma && settings.context === VariableContext.Statement) { // TODO temp: if (!name) throw Error() entries = new Map(); entries.set(name, new VariableDeclaration(name, { value })); while (reader.current.type as JSToken === JSToken.Comma) { reader.move(); const variable = VariableDeclaration.fromTokens(reader, { context: VariableContext.Destruction }); entries.set(variable.name, variable) } } const variable = new VariableDeclaration(entries ?? name!, { isConstant, spread, typeSignature: type, value, isOptional, isStatic: settings.isStatic ?? false, isAbstract: settings.isAbstract ?? false, context: settings.context, parent: settings.parent }); if (reader.current.type as JSToken === JSToken.SemiColon) reader.move(); return variable; } static fromString(string: string) { const reader = stringToTokens(string); const variable = VariableDeclaration.fromTokens(reader); reader.expect(JSToken.EOF); return variable; } }
the_stack
import { PdfViewer } from '../index'; import { PdfViewerBase, IPageAnnotations } from '../index'; import { createElement, isNullOrUndefined, isBlazor } from '@syncfusion/ej2-base'; import { Dialog } from '@syncfusion/ej2-popups'; import { PdfAnnotationBaseModel } from '../drawing/pdf-annotation-model'; import { PdfAnnotationBase } from '../drawing/pdf-annotation'; import { splitArrayCollection, processPathData, getPathString } from '@syncfusion/ej2-drawings'; import { TextBox } from '@syncfusion/ej2-inputs'; import { cloneObject } from '../drawing/drawing-util'; import { CheckBox } from '@syncfusion/ej2-buttons'; import { Tab, SelectEventArgs } from '@syncfusion/ej2-navigations'; import { Button } from '@syncfusion/ej2-buttons'; import { PdfAnnotationType } from '../drawing'; import { DisplayMode } from './types'; /** * @hidden */ export interface ISignAnnotation { strokeColor: string opacity: number bounds: IRectCollection pageIndex: number shapeAnnotationType: string thickness: number id: string data: string signatureName: string fontFamily?: string fontSize?: string } /** * @hidden */ interface IRectCollection { left: number top: number width: number height: number } /** * @hidden */ export class Signature { private pdfViewer: PdfViewer; private pdfViewerBase: PdfViewerBase; private mouseDetection: boolean; private oldX: number; private mouseX: number; private oldY: number; private mouseY: number; // eslint-disable-next-line private newObject: any = []; /** * @private */ public outputString: string = ''; /** * @private */ public signatureDialog: Dialog; /** * @private */ // eslint-disable-next-line public signaturecollection: any = []; /** * @private */ // eslint-disable-next-line public outputcollection: any = []; /** * @private */ public fontName: string; // eslint-disable-next-line private fontsign: any = []; // eslint-disable-next-line private signfontStyle: any = []; private signtypevalue: string; private signfont: string; private signHeight: string; private signWidth: string; private signaturetype: string; private tabObj: Tab; private isSaveSignature: boolean = false; // eslint-disable-next-line private saveSignatureString: string = ''; /** * @private */ // eslint-disable-next-line public saveImageString: string = ''; private signatureImageString: string = ''; /** * @private */ // eslint-disable-next-line public maxSaveLimit: number = 5; /** * Initialize the constructor of blazorUIadapater. * @private * @param { PdfViewer } pdfViewer - Specified PdfViewer class. * @param { PdfViewerBase } pdfViewerBase - The pdfViewerBase. */ constructor(pdfViewer: PdfViewer, pdfViewerBase: PdfViewerBase) { this.pdfViewer = pdfViewer; this.pdfViewerBase = pdfViewerBase; } /** * @private * @returns {void} */ public createSignaturePanel(): void { if (!isBlazor()) { const elementID: string = this.pdfViewer.element.id; const dialogDiv: HTMLElement = createElement('div', { id: elementID + '_signature_window', className: 'e-pv-signature-window' }); dialogDiv.style.display = 'block'; this.pdfViewerBase.pageContainer.appendChild(dialogDiv); const appearanceTab: HTMLElement = this.createSignatureCanvas(); let signaturePanelHeader: string; if(!this.pdfViewerBase.isToolbarSignClicked) { if(this.pdfViewerBase.isInitialField) { signaturePanelHeader = this.pdfViewer.localeObj.getConstant('HandwrittenInitialDialogHeaderText'); } else { signaturePanelHeader = this.pdfViewer.localeObj.getConstant('HandwrittenSignatureDialogHeaderText'); } } else { if(this.pdfViewerBase.isInitialField) { signaturePanelHeader = this.pdfViewer.localeObj.getConstant('InitialFieldDialogHeaderText'); } else { signaturePanelHeader = this.pdfViewer.localeObj.getConstant('SignatureFieldDialogHeaderText'); } } if (this.signatureDialog) { this.signatureDialog.content = appearanceTab; } else { this.signatureDialog = new Dialog({ // eslint-disable-next-line max-len showCloseIcon: true, closeOnEscape: false, isModal: true, header: signaturePanelHeader, cssClass: 'e-pv-signature-dialog-height', target: this.pdfViewer.element, content: appearanceTab, width: '750px', visible: true, allowDragging: true, beforeClose: (): void => { this.clearSignatureCanvas(); this.signatureDialog.destroy(); this.signatureDialog = null; if (this.tabObj) { this.tabObj.destroy(); } // eslint-disable-next-line let signatureWindow: any = document.getElementById(this.pdfViewer.element.id + '_signature_window'); if (signatureWindow) { // eslint-disable-next-line signatureWindow.parentNode ? signatureWindow.parentNode.removeChild(signatureWindow) : signatureWindow.parentElement.removeChild(signatureWindow); } // eslint-disable-next-line max-len if (!this.pdfViewerBase.isToolbarSignClicked && !this.pdfViewerBase.drawSignatureWithTool && !isNullOrUndefined(this.pdfViewer.formFieldsModule.currentTarget)) { this.pdfViewer.fireFocusOutFormField(this.pdfViewer.formFieldsModule.currentTarget.name, ''); } this.pdfViewerBase.isToolbarSignClicked = false; this.pdfViewer.formFieldsModule.setFocus(); } }); this.signatureDialog.buttons = [ // eslint-disable-next-line max-len { buttonModel: { content: this.pdfViewer.localeObj.getConstant('Clear'), disabled: true, cssClass: 'e-pv-clearbtn' }, click: this.clearSignatureCanvas.bind(this) }, // eslint-disable-next-line max-len { buttonModel: { content: this.pdfViewer.localeObj.getConstant('Cancel') }, click: this.closeSignaturePanel.bind(this) }, // eslint-disable-next-line max-len { buttonModel: { content: this.pdfViewer.localeObj.getConstant('Create'), isPrimary: true, disabled: true, cssClass: 'e-pv-createbtn' }, click: this.addSignatureInPage.bind(this) } ]; this.signatureDialog.appendTo(dialogDiv); } if(this.pdfViewer.enableRtl){ this.signatureDialog.enableRtl = this.pdfViewer.enableRtl; } let checkboxItem: any = (this.signatureDialog.content as any).ej2_instances[0].items[0]; if(checkboxItem.header.label === 'DRAW') { let drawCheckbox: HTMLElement = document.getElementById("checkbox"); this.hideSignatureCheckbox(drawCheckbox); } else if(checkboxItem.header.label === 'TYPE') { let typeCheckbox: HTMLElement = document.getElementById("checkbox1"); this.hideSignatureCheckbox(typeCheckbox); } else { let imageCheckbox: HTMLElement = document.getElementById("checkbox2"); this.hideSignatureCheckbox(imageCheckbox); } } else { // eslint-disable-next-line let canvas: any = document.getElementById(this.pdfViewer.element.id + '_signatureCanvas_'); if (canvas) { if (!this.pdfViewerBase.pageContainer.querySelector('.e-pv-signature-window')) { const elementID: string = this.pdfViewer.element.id; // eslint-disable-next-line max-len const dialogDiv: HTMLElement = createElement('div', { id: elementID + '_signature_window', className: 'e-pv-signature-window' }); dialogDiv.style.display = 'block'; this.pdfViewerBase.pageContainer.appendChild(dialogDiv); } canvas.addEventListener('mousedown', this.signaturePanelMouseDown.bind(this)); canvas.addEventListener('mousemove', this.signaturePanelMouseMove.bind(this)); canvas.addEventListener('mouseup', this.signaturePanelMouseUp.bind(this)); canvas.addEventListener('mouseleave', this.signaturePanelMouseUp.bind(this)); canvas.addEventListener('touchstart', this.signaturePanelMouseDown.bind(this)); canvas.addEventListener('touchmove', this.signaturePanelMouseMove.bind(this)); canvas.addEventListener('touchend', this.signaturePanelMouseUp.bind(this)); this.clearSignatureCanvas(); } this.pdfViewer._dotnetInstance.invokeMethodAsync('OpenSignaturePanel', this.pdfViewerBase.isToolbarSignClicked); } this.drawSavedSignature(); } private drawSavedSignature(): void { if (!this.pdfViewerBase.isToolbarSignClicked && this.isSaveSignature) { this.outputString = this.saveSignatureString; // eslint-disable-next-line let canvas: any = document.getElementById(this.pdfViewer.element.id + '_signatureCanvas_'); // eslint-disable-next-line let context: any = canvas.getContext('2d'); // eslint-disable-next-line let image: any = new Image(); image.onload = (): void => { context.drawImage(image, 0, 0); }; image.src = this.signatureImageString; // eslint-disable-next-line let checkbox: any = document.getElementById(this.pdfViewer.element.id + '_signatureCheckBox'); if (checkbox) { checkbox.checked = true; } this.enableCreateButton(false); this.enableClearbutton(false); } } private hideSignatureCheckbox(checkbox: any): void { if(!this.pdfViewerBase.isToolbarSignClicked) { if(this.pdfViewerBase.isInitialField) { if(this.pdfViewer.handWrittenSignatureSettings.initialDialogSettings.hideSaveSignature) { this.hideCheckboxParent(checkbox); } } else if(this.pdfViewer.handWrittenSignatureSettings.signatureDialogSettings.hideSaveSignature) { this.hideCheckboxParent(checkbox); } } else { if(this.pdfViewerBase.isInitialField) { if (this.pdfViewer.initialFieldSettings.initialDialogSettings.hideSaveSignature) { this.hideCheckboxParent(checkbox); } } else { if (this.pdfViewer.signatureFieldSettings.signatureDialogSettings.hideSaveSignature) { this.hideCheckboxParent(checkbox); } } } } private hideCheckboxParent(checkbox: any): void { if(checkbox) { checkbox.parentElement.style.display = 'none'; } } private saveSignatureImage(): void { // eslint-disable-next-line let checkbox: any = document.getElementById(this.pdfViewer.element.id + '_signatureCheckBox'); if (checkbox && checkbox.checked) { if (this.outputString !== '') { this.isSaveSignature = true; this.saveSignatureString = this.outputString; // eslint-disable-next-line let canvas: any = document.getElementById(this.pdfViewer.element.id + '_signatureCanvas_'); this.saveImageString = canvas.toDataURL(); this.signatureImageString = this.saveImageString; } } else { if (this.isSaveSignature) { this.isSaveSignature = false; this.saveSignatureString = ''; this.saveImageString = ''; this.signatureImageString = ''; } this.clearSignatureCanvas(); } } /** * @param type * @private */ // eslint-disable-next-line public addSignature(type?: any): void { let annot: PdfAnnotationBaseModel; if (this.pdfViewerBase.isToolbarSignClicked) { const annotationName: string = this.pdfViewer.annotation.createGUID(); this.pdfViewerBase.currentSignatureAnnot = null; this.pdfViewerBase.isSignatureAdded = true; const pageIndex: number = this.pdfViewerBase.currentPageNumber - 1; // eslint-disable-next-line max-len const thickness: number = this.pdfViewer.handWrittenSignatureSettings.thickness ? this.pdfViewer.handWrittenSignatureSettings.thickness : 1; // eslint-disable-next-line max-len const opacity: number = this.pdfViewer.handWrittenSignatureSettings.opacity ? this.pdfViewer.handWrittenSignatureSettings.opacity : 1; // eslint-disable-next-line max-len const strokeColor: string = this.pdfViewer.handWrittenSignatureSettings.strokeColor ? this.pdfViewer.handWrittenSignatureSettings.strokeColor : '#000000'; // eslint-disable-next-line let signatureBounds: any = this.pdfViewer.formFieldsModule.updateSignatureAspectRatio(this.outputString, true); // eslint-disable-next-line let canvas: any = document.getElementById(this.pdfViewer.element.id + '_signatureCanvas_'); this.saveImageString = canvas.toDataURL(); this.signatureImageString = this.saveImageString; annot = { // eslint-disable-next-line max-len id: 'sign' + this.pdfViewerBase.signatureCount, bounds: signatureBounds, pageIndex: pageIndex, data: this.outputString, shapeAnnotationType: 'HandWrittenSignature', opacity: opacity, strokeColor: strokeColor, thickness: thickness, signatureName: annotationName }; this.pdfViewerBase.currentSignatureAnnot = annot; // eslint-disable-next-line let checkbox: any; if (isBlazor()) { checkbox = document.getElementById(this.pdfViewer.element.id + '_signatureCheckBox'); } else { checkbox = document.getElementById('checkbox'); } if (checkbox && checkbox.checked) { this.addSignatureCollection(); } this.hideSignaturePanel(); this.pdfViewerBase.isToolbarSignClicked = false; } else { // eslint-disable-next-line let checkbox: any; if (isBlazor()) { checkbox = document.getElementById(this.pdfViewer.element.id + '_signatureCheckBox'); } else { checkbox = document.getElementById('checkbox'); } let isSignatureAdded: boolean = false; if (isBlazor() && type) { if (type[0] === 'Image') { this.imageAddSignature(); isSignatureAdded = true; this.outputString = ''; } else if (type[0] === 'Type') { this.typeAddSignature(); isSignatureAdded = true; this.outputString = ''; } } if (!isSignatureAdded) { // eslint-disable-next-line let canvas: any = document.getElementById(this.pdfViewer.element.id + '_signatureCanvas_'); this.saveImageString = canvas.toDataURL(); if (checkbox && checkbox.checked) { this.isSaveSignature = true; this.saveSignatureString = this.outputString; } else { this.isSaveSignature = false; this.saveSignatureString = ''; } this.signatureImageString = this.saveImageString; this.pdfViewer.formFieldsModule.drawSignature(null, null, this.pdfViewerBase.currentTarget, null); isSignatureAdded = true; } } } private addSignatureInPage(): void { if (this.signaturetype === 'Draw') { this.addSignature(); } else if (this.signaturetype === 'Type') { this.typeAddSignature(); } else { this.imageAddSignature(); } } private typeAddSignature(): void { if (this.pdfViewerBase.isToolbarSignClicked) { const zoomvalue: number = this.pdfViewerBase.getZoomFactor(); // eslint-disable-next-line let annot: any = null; const annotationName: string = this.pdfViewer.annotation.createGUID(); this.pdfViewerBase.currentSignatureAnnot = null; this.pdfViewerBase.isSignatureAdded = true; const pageIndex: number = this.pdfViewerBase.currentPageNumber - 1; const pageDiv: HTMLElement = document.getElementById(this.pdfViewer.element.id + '_pageDiv_' + pageIndex); let currentLeft: number = 0; let currentTop: number = 0; const currentHeight: number = 65; const currentWidth: number = 200; currentLeft = ((parseFloat(pageDiv.style.width) / 2) - (currentWidth / 2)) / zoomvalue; currentTop = ((parseFloat(pageDiv.style.height) / 2) - (currentHeight / 2)) / zoomvalue; const zoomFactor: number = this.pdfViewerBase.getZoomFactor(); if (!this.signtypevalue) { this.updateSignatureTypeValue(true); } const inputValue: string = this.signtypevalue; annot = { // eslint-disable-next-line max-len id: 'Typesign' + this.pdfViewerBase.signatureCount, bounds: { left: currentLeft / zoomFactor, top: currentTop / zoomFactor, x: currentLeft / zoomFactor, // eslint-disable-next-line max-len y: currentTop / zoomFactor, width: currentWidth, height: currentHeight }, pageIndex: pageIndex, dynamicText: inputValue, data: this.pdfViewerBase.signatureModule.outputString, shapeAnnotationType: 'SignatureText', fontFamily: this.fontName, signatureName: annotationName }; this.pdfViewerBase.currentSignatureAnnot = annot; // eslint-disable-next-line let checkbox: any; if (isBlazor()) { checkbox = document.getElementById(this.pdfViewer.element.id + '_signatureCheckBox'); } else { checkbox = document.getElementById('checkbox1'); } if (checkbox && checkbox.checked) { this.addSignatureCollection(); } this.signtypevalue = ''; this.hideSignaturePanel(); this.pdfViewerBase.isToolbarSignClicked = false; } else { if (this.outputString === '') { this.updateSignatureTypeValue(); } this.pdfViewer.formFieldsModule.drawSignature('Type', '', this.pdfViewerBase.currentTarget); this.hideSignaturePanel(); } } private imageAddSignature(): void { if (this.pdfViewerBase.isToolbarSignClicked) { const zoomvalue: number = this.pdfViewerBase.getZoomFactor(); // eslint-disable-next-line let annot: any = null; const annotationName: string = this.pdfViewer.annotation.createGUID(); this.pdfViewerBase.currentSignatureAnnot = null; this.pdfViewerBase.isSignatureAdded = true; const pageIndex: number = this.pdfViewerBase.currentPageNumber - 1; const pageDiv: HTMLElement = document.getElementById(this.pdfViewer.element.id + '_pageDiv_' + pageIndex); let currentLeft: number = 0; let currentTop: number = 0; const currentHeight: number = 65; //15arseFloat(this.signHeight); const currentWidth: number = 200; //parseFloat(this.signWidth); currentLeft = ((parseFloat(pageDiv.style.width) / 2) - (currentWidth / 2)) / zoomvalue; currentTop = ((parseFloat(pageDiv.style.height) / 2) - (currentHeight / 2)) / zoomvalue; const zoomFactor: number = this.pdfViewerBase.getZoomFactor(); const inputValue: string = this.signtypevalue; annot = { // eslint-disable-next-line max-len id: 'Typesign' + this.pdfViewerBase.signatureCount, bounds: { left: currentLeft / zoomFactor, top: currentTop / zoomFactor, x: currentLeft / zoomFactor, // eslint-disable-next-line max-len y: currentTop / zoomFactor, width: currentWidth, height: currentHeight }, pageIndex: pageIndex, dynamicText: inputValue, data: this.pdfViewerBase.signatureModule.outputString, shapeAnnotationType: 'SignatureImage', fontFamily: this.fontName, signatureName: annotationName }; this.pdfViewerBase.currentSignatureAnnot = annot; // eslint-disable-next-line let checkbox: any; if (isBlazor()) { checkbox = document.getElementById(this.pdfViewer.element.id + '_signatureCheckBox'); } else { checkbox = document.getElementById('checkbox2'); } if (checkbox && checkbox.checked) { this.addSignatureCollection(); } this.hideSignaturePanel(); this.pdfViewerBase.isToolbarSignClicked = false; } else { this.pdfViewer.formFieldsModule.drawSignature('Image', '', this.pdfViewerBase.currentTarget); this.hideSignaturePanel(); } } private updateSignatureTypeValue(isType?: boolean): void { // eslint-disable-next-line let fontElements: any = document.querySelectorAll('.e-pv-font-sign'); if (fontElements) { for (let j: number = 0; j < fontElements.length; j++) { if (fontElements[j] && fontElements[j].style.borderColor === 'red') { if (isType) { this.signtypevalue = fontElements[j].textContent; this.outputString = fontElements[j].textContent; } else { this.outputString = fontElements[j].textContent; } try { this.fontName = JSON.parse(fontElements[j].style.fontFamily); } catch (e) { this.fontName = fontElements[j].style.fontFamily; } } } } } /** * @private * @returns {void} */ public hideSignaturePanel(): void { if (this.signatureDialog) { this.signatureDialog.hide(); } } private bindTypeSignatureClickEvent(): void { if (isBlazor()) { for (let i: number = 0; i < 4; i++) { // eslint-disable-next-line let fontElement: any = document.querySelector('#' + this.pdfViewer.element.id + '_font_signature' + i); if (fontElement) { fontElement.addEventListener('click', this.typeSignatureclicked.bind(this)); } } } } private bindDrawSignatureClickEvent(): void { // eslint-disable-next-line let canvas: any = document.getElementById(this.pdfViewer.element.id + '_signatureCanvas_'); if (canvas) { canvas.addEventListener('mousedown', this.signaturePanelMouseDown.bind(this)); canvas.addEventListener('mousemove', this.signaturePanelMouseMove.bind(this)); canvas.addEventListener('mouseup', this.signaturePanelMouseUp.bind(this)); canvas.addEventListener('mouseleave', this.signaturePanelMouseUp.bind(this)); canvas.addEventListener('touchstart', this.signaturePanelMouseDown.bind(this)); canvas.addEventListener('touchmove', this.signaturePanelMouseMove.bind(this)); canvas.addEventListener('touchend', this.signaturePanelMouseUp.bind(this)); } } // eslint-disable-next-line private typeSignatureclicked(event: any): void { const eventTarget: HTMLElement = event.target as HTMLElement; if (eventTarget) { for (let i: number = 0; i < 4; i++) { // eslint-disable-next-line let fontElement: any = document.querySelector('#' + this.pdfViewer.element.id + '_font_signature' + i); if (fontElement) { fontElement.style.borderColor = ''; } } eventTarget.style.borderColor = 'red'; this.outputString = eventTarget.textContent; try { this.fontName = JSON.parse(eventTarget.style.fontFamily); } catch (e) { this.fontName = eventTarget.style.fontFamily; } this.enableCreateButton(false); } } // eslint-disable-next-line private createSignatureCanvas(): any { // eslint-disable-next-line let previousField: any = document.getElementById(this.pdfViewer.element.id + '_signatureCanvas_'); // eslint-disable-next-line let field: any = document.getElementById(this.pdfViewer.element.id + 'Signature_appearance'); if (previousField) { previousField.remove(); } if (field) { field.remove(); } // eslint-disable-next-line max-len const appearanceDiv: HTMLElement = createElement('div', { id: this.pdfViewer.element.id + 'Signature_appearance', className: 'e-pv-signature-apperance', styles:'margin-top:30px' }); // eslint-disable-next-line max-len const canvas: HTMLCanvasElement = createElement('canvas', { id: this.pdfViewer.element.id + '_signatureCanvas_', className: 'e-pv-signature-canvas' }) as HTMLCanvasElement; if (this.pdfViewer.element.offsetWidth > 750) { canvas.width = 714; } else { canvas.width = this.pdfViewer.element.offsetWidth - 35; } canvas.classList.add('e-pv-canvas-signature'); canvas.height = 305; canvas.style.height = '305px'; canvas.style.border = '1px dotted #bdbdbd'; canvas.style.backgroundColor = 'white'; canvas.style.boxSizing = 'border-box'; canvas.style.borderRadius = '2px'; canvas.addEventListener('mousedown', this.signaturePanelMouseDown.bind(this)); canvas.addEventListener('mousemove', this.signaturePanelMouseMove.bind(this)); canvas.addEventListener('mouseup', this.signaturePanelMouseUp.bind(this)); canvas.addEventListener('mouseleave', this.signaturePanelMouseUp.bind(this)); canvas.addEventListener('touchstart', this.signaturePanelMouseDown.bind(this)); canvas.addEventListener('touchmove', this.signaturePanelMouseMove.bind(this)); canvas.addEventListener('touchend', this.signaturePanelMouseUp.bind(this)); appearanceDiv.appendChild(canvas); // eslint-disable-next-line let checkBoxObj: any; // eslint-disable-next-line let input: any; let saveCheckBoxContent: string; if (this.pdfViewerBase.isToolbarSignClicked && !this.pdfViewerBase.isInitialField) { saveCheckBoxContent = this.pdfViewer.localeObj.getConstant('Save Signature'); } else { saveCheckBoxContent = this.pdfViewerBase.isInitialField ? this.pdfViewer.localeObj.getConstant('Save Initial') : this.pdfViewer.localeObj.getConstant('Save Signature'); } if (!this.pdfViewer.hideSaveSignature) { // eslint-disable-next-line input = document.createElement('input'); input.type = 'checkbox'; input.id = 'checkbox'; appearanceDiv.appendChild(input); checkBoxObj = new CheckBox({ label: saveCheckBoxContent, disabled: false, checked: false }); checkBoxObj.appendTo(input); } if (this.isSaveSignature) { checkBoxObj.checked = true; } //if (!this.pdfViewerBase.isToolbarSignClicked) { // eslint-disable-next-line let typeDiv: HTMLElement = createElement('div', { id: this.pdfViewer.element.id + 'type_appearance', className: 'e-pv-signature-apperance', styles:'margin-top:6px' }); // eslint-disable-next-line let inputText: any = document.createElement('input'); inputText.type = 'text'; inputText.id = this.pdfViewer.element.id + '_e-pv-Signtext-box'; typeDiv.appendChild(inputText); // eslint-disable-next-line let inputobj: any = new TextBox({ placeholder: this.pdfViewer.localeObj.getConstant('Enter Signature as Name'), floatLabelType: 'Auto' }); inputobj.appendTo(inputText); // eslint-disable-next-line let fontDiv: HTMLElement = createElement('div', { id: this.pdfViewer.element.id + '_font_appearance', className: 'e-pv-font-appearance-style' }); fontDiv.classList.add('e-pv-canvas-signature'); fontDiv.style.height = '270px'; fontDiv.style.border = '1px dotted #bdbdbd'; fontDiv.style.boxSizing = 'border-box'; fontDiv.style.borderRadius = '2px'; fontDiv.style.backgroundColor = 'white'; fontDiv.style.color = 'black'; fontDiv.style.marginTop = '8px' typeDiv.appendChild(fontDiv); input = document.createElement('input'); input.type = 'checkbox'; input.id = 'checkbox1'; typeDiv.appendChild(input); checkBoxObj = new CheckBox({ label: saveCheckBoxContent, disabled: false, checked: false }); checkBoxObj.appendTo(input); inputobj.addEventListener('input', this.renderSignatureText.bind(this)); this.enableCreateButton(true); // eslint-disable-next-line let tab: HTMLElement = createElement('div', { id: this.pdfViewer.element.id + 'Signature_tab' }); const uploadDiv: HTMLElement = createElement('div', { id: this.pdfViewer.element.id + 'upload_appearance', className: 'e-pv-signature-apperance', styles:'padding-top:30px' }); // eslint-disable-next-line let button: any = document.createElement('div'); button.id = this.pdfViewer.element.id + '_e-pv-upload-button'; uploadDiv.appendChild(button); // eslint-disable-next-line let uploadButton: any = new Button({ cssClass: 'e-pv-sign-upload', content: this.pdfViewer.localeObj.getConstant('Browse Signature Image') }); uploadButton.appendTo(button); uploadButton.element.style.position = 'absolute'; // eslint-disable-next-line max-len const uploadCanvas: HTMLCanvasElement = createElement('canvas', { id: this.pdfViewer.element.id + '_signatureuploadCanvas_', className: 'e-pv-signature-uploadcanvas' }) as HTMLCanvasElement; if (this.pdfViewer.element.offsetWidth > 750) { uploadCanvas.width = 714; } else { uploadCanvas.width = this.pdfViewer.element.offsetWidth - 35; } uploadCanvas.classList.add('e-pv-canvas-signature'); uploadCanvas.height = 305; uploadCanvas.style.height = '305px'; uploadButton.element.style.left = ((uploadCanvas.width / 2) - 50) + 'px'; uploadButton.element.style.top = ((parseFloat(uploadCanvas.style.height) / 2) + 20) + 'px'; uploadCanvas.style.border = '1px dotted #bdbdbd'; uploadCanvas.style.backgroundColor = 'white'; uploadCanvas.style.boxSizing = 'border-box'; uploadCanvas.style.borderRadius = '2px'; uploadCanvas.style.zIndex = '0'; uploadDiv.appendChild(uploadCanvas); input = document.createElement('input'); input.type = 'checkbox'; input.id = 'checkbox2'; uploadDiv.appendChild(input); checkBoxObj = new CheckBox({ label: saveCheckBoxContent, disabled: false, checked: false }); checkBoxObj.appendTo(input); button.addEventListener('click', this.uploadSignatureImage.bind(this)); // eslint-disable-next-line max-len this.signfontStyle = [{ FontName: 'Helvetica' }, { FontName: 'Times New Roman' }, { FontName: 'Courier' }, { FontName: 'Symbol' }]; // eslint-disable-next-line let fontSignature: any = []; if (!isNullOrUndefined(this.pdfViewer.handWrittenSignatureSettings.typeSignatureFonts)) { for (let j: number = 0; j < 4; j++) { if (!isNullOrUndefined(this.pdfViewer.handWrittenSignatureSettings.typeSignatureFonts[j])) { this.signfontStyle[j].FontName = this.pdfViewer.handWrittenSignatureSettings.typeSignatureFonts[j]; } } } for (let i: number = 0; i < this.signfontStyle.length; i++) { fontSignature[i] = document.createElement('div'); fontSignature[i].id = '_font_signature' + i + ''; fontSignature[i].classList.add('e-pv-font-sign'); } this.fontsign = fontSignature; // eslint-disable-next-line let proxy: any = this; let items: any = []; if (!this.pdfViewerBase.isToolbarSignClicked) { if(this.pdfViewerBase.isInitialField) { items = this.showHideSignatureTab(this.pdfViewer.handWrittenSignatureSettings.initialDialogSettings.displayMode, appearanceDiv, typeDiv, uploadDiv); } else { items = this.showHideSignatureTab(this.pdfViewer.handWrittenSignatureSettings.signatureDialogSettings.displayMode, appearanceDiv, typeDiv, uploadDiv); } } else { if(this.pdfViewerBase.isInitialField) { items = this.showHideSignatureTab(this.pdfViewer.initialFieldSettings.initialDialogSettings.displayMode, appearanceDiv, typeDiv, uploadDiv); } else { items = this.showHideSignatureTab(this.pdfViewer.signatureFieldSettings.signatureDialogSettings.displayMode, appearanceDiv, typeDiv, uploadDiv); } } // eslint-disable-next-line this.tabObj = new Tab({ selected: (args: SelectEventArgs): void => { proxy.handleSelectEvent(args); }, items: items }); this.tabObj.appendTo(tab); if(tab && tab.lastElementChild) { (tab.lastElementChild as any).style.overflow = 'hidden'; } if(items[0].header.label === 'DRAW') { this.signaturetype = 'Draw'; } else if(items[0].header.label === 'TYPE') { this.signaturetype = 'Type'; } else { this.signaturetype = 'Image'; } return tab; // } else { // return appearanceDiv; // } } private handleSelectEvent(e: SelectEventArgs): void { // eslint-disable-next-line let headerText: string = ''; let tabInstance = (document.getElementById(this.pdfViewer.element.id + 'Signature_tab') as any).ej2_instances[0]; if(tabInstance) { if (tabInstance.items.length > 0) { for (let i: number = 0; i < tabInstance.items.length; i++) { let headerValue = tabInstance.items[i].header.text; if (headerValue === e.selectedItem.textContent) { headerText = tabInstance.items[i].header.label; } } } } let checkbox: any = document.getElementById('checkbox'); if (checkbox && checkbox.checked) { if (e.previousIndex === 0 && this.outputString !== '') { this.isSaveSignature = true; this.saveSignatureString = this.outputString; // eslint-disable-next-line let canvas: any = document.getElementById(this.pdfViewer.element.id + '_signatureCanvas_'); this.saveImageString = canvas.toDataURL(); this.signatureImageString = this.saveImageString; } } else { if (this.isSaveSignature) { this.isSaveSignature = false; this.saveSignatureString = ''; this.saveImageString = ''; this.signatureImageString = ''; } this.clearSignatureCanvas(); } // eslint-disable-next-line if (headerText.toLocaleLowerCase() === 'draw') { this.signaturetype = 'Draw'; if (this.isSaveSignature) { this.enableCreateButton(false); } let drawCheckbox = document.getElementById("checkbox"); this.hideSignatureCheckbox(drawCheckbox); } else if (headerText.toLocaleLowerCase() === 'type') { this.outputString = ''; this.signaturetype = 'Type'; // eslint-disable-next-line this.enableCreateButton(true); let typeCheckbox = document.getElementById("checkbox1"); this.hideSignatureCheckbox(typeCheckbox); } else if (headerText.toLocaleLowerCase() === 'upload') { this.signaturetype = 'Image'; this.enableCreateButton(true); let imageCheckbox = document.getElementById("checkbox2"); this.hideSignatureCheckbox(imageCheckbox); } } private showHideSignatureTab(displayMode: DisplayMode, appearanceDiv: HTMLElement, typeDiv: HTMLElement, uploadDiv: HTMLElement): any { let items: any = []; if(displayMode & DisplayMode.Draw) { items.push({ header: { 'text': this.pdfViewer.localeObj.getConstant('Draw-hand Signature'), 'label': 'DRAW' }, content: appearanceDiv }) } if(displayMode & DisplayMode.Text) { items.push({ header: { 'text': this.pdfViewer.localeObj.getConstant('Type Signature'), 'label': 'TYPE' }, content: typeDiv }) } if(displayMode & DisplayMode.Upload) { items.push({ header: { 'text': this.pdfViewer.localeObj.getConstant('Upload Signature'), 'label': 'UPLOAD' }, content: uploadDiv }) } return items; } /** * @private * @returns {void} */ public createSignatureFileElement(): void { // eslint-disable-next-line let signImage: any = createElement('input', { id: this.pdfViewer.element.id + '_signElement', attrs: { 'type': 'file' } }); signImage.setAttribute('accept', '.jpg,.jpeg,.png'); signImage.style.position = 'absolute'; signImage.style.left = '0px'; signImage.style.top = '0px'; signImage.style.visibility = 'hidden'; document.body.appendChild(signImage); signImage.addEventListener('change', this.addStampImage); } private uploadSignatureImage(): void { // eslint-disable-next-line let signImage: any = document.getElementById(this.pdfViewer.element.id + '_signElement'); if (signImage) { signImage.click(); } } // eslint-disable-next-line private addStampImage = (args: any): void => { // eslint-disable-next-line let proxy: any = this; // eslint-disable-next-line let upoadedFiles: any = args.target.files; if (args.target.files[0] !== null) { const uploadedFile: File = upoadedFiles[0]; if (uploadedFile.type.split('/')[0] === 'image') { const reader: FileReader = new FileReader(); // eslint-disable-next-line reader.onload = (e: any): void => { // eslint-disable-next-line let canvas: any = document.getElementById(this.pdfViewer.element.id + '_signatureuploadCanvas_'); // eslint-disable-next-line let context: any = canvas.getContext('2d'); // eslint-disable-next-line let image: any = new Image(); // eslint-disable-next-line let proxy: any = this; image.onload = (): void => { // eslint-disable-next-line let signbutton: any = document.getElementById(this.pdfViewer.element.id + '_e-pv-upload-button'); signbutton.style.visibility = 'hidden'; context.drawImage(image, 0, 0, canvas.width, canvas.height); proxy.enableCreateButton(false); proxy.outputString = image.src; }; image.src = e.currentTarget.result; proxy.outputString = e.currentTarget.result; }; reader.readAsDataURL(uploadedFile); } } }; private renderSignatureText(): void { // eslint-disable-next-line let fontDiv: any = document.getElementById(this.pdfViewer.element.id + '_font_appearance'); // eslint-disable-next-line let textBox: any = document.getElementById(this.pdfViewer.element.id + '_e-pv-Signtext-box'); for (let i: number = 0; i < this.signfontStyle.length; i++) { this.fontsign[i].innerHTML = textBox.value; this.fontsign[i].style.fontFamily = this.signfontStyle[i].FontName; if (this.signfontStyle[i].FontName === 'Helvetica') { this.fontsign[i].style.borderColor = 'red'; } fontDiv.appendChild(this.fontsign[i]); } for (let i: number = 0; i < this.signfontStyle.length; i++) { // eslint-disable-next-line let clickSign: any = document.getElementById('_font_signature' + i + ''); clickSign.addEventListener('click', this.typeSignatureclick.bind(this)); } this.enableCreateButton(false); this.enableClearbutton(false); } private typeSignatureclick(): void { const eventTarget: HTMLElement = event.target as HTMLElement; // eslint-disable-next-line let createButton: any = document.getElementsByClassName('e-pv-createbtn')[0]; createButton.disabled = false; for (let i: number = 0; i < 4; i++) { // eslint-disable-next-line let fontElement: any = document.getElementById('_font_signature' + i + ''); if (fontElement) { fontElement.style.borderColor = ''; } } eventTarget.style.borderColor = 'red'; this.outputString = eventTarget.textContent; try { this.fontName = JSON.parse(eventTarget.style.fontFamily); } catch (e) { this.fontName = eventTarget.style.fontFamily; } } /** * @param bounds * @param position * @private */ // eslint-disable-next-line public addSignatureCollection(bounds?: any, position?: any): void { let minimumX: number = -1; let minimumY: number = -1; let maximumX: number = -1; let maximumY: number = -1; // eslint-disable-next-line let collectionData: any = processPathData(this.outputString); // eslint-disable-next-line let newCanvas: any = document.createElement('canvas'); // eslint-disable-next-line let context: any = newCanvas.getContext('2d'); // eslint-disable-next-line let imageString: any; const signatureType: string = this.pdfViewerBase.currentSignatureAnnot.shapeAnnotationType; if (signatureType === 'HandWrittenSignature') { if (collectionData.length !== 0) { // eslint-disable-next-line for (let k = 0; k < collectionData.length; k++) { // eslint-disable-next-line let val = collectionData[k]; if (minimumX === -1) { // eslint-disable-next-line minimumX = (val['x']); // eslint-disable-next-line maximumX = (val['x']); // eslint-disable-next-line minimumY = (val['y']); // eslint-disable-next-line maximumY = (val['y']); } else { // eslint-disable-next-line let point1 = (val['x']); // eslint-disable-next-line let point2 = (val['y']); if (minimumX >= point1) { minimumX = point1; } if (minimumY >= point2) { minimumY = point2; } if (maximumX <= point1) { maximumX = point1; } if (maximumY <= point2) { maximumY = point2; } } } const newdifferenceX: number = maximumX - minimumX; const newdifferenceY: number = maximumY - minimumY; let differenceX: number = newdifferenceX / 100; let differenceY: number = newdifferenceY / 100; let left: number = 0; let top: number = 0; if (bounds) { newCanvas.width = position.currentWidth; newCanvas.height = position.currentHeight; differenceX = newdifferenceX / (bounds.width); differenceY = newdifferenceY / (bounds.height); left = bounds.x - position.currentLeft; top = bounds.y - position.currentTop; } else { newCanvas.width = 100; newCanvas.height = 100; } context.beginPath(); for (let n: number = 0; n < collectionData.length; n++) { // eslint-disable-next-line let val: any = collectionData[n]; // eslint-disable-next-line let point1: number = ((val['x'] - minimumX) / differenceX) + left; // eslint-disable-next-line let point2: number = ((val['y'] - minimumY) / differenceY) + top; // eslint-disable-next-line if (val['command'] === 'M') { context.moveTo(point1, point2); // eslint-disable-next-line } else if (val['command'] === 'L') { context.lineTo(point1, point2); } } context.stroke(); context.closePath(); imageString = newCanvas.toDataURL(); } } else if (signatureType === 'SignatureText') { imageString = this.outputString; } else { imageString = this.outputString; } if (bounds) { this.saveImageString = imageString; } else { // eslint-disable-next-line let signCollection: any = {}; signCollection['sign_' + this.pdfViewerBase.imageCount] = this.outputString; this.outputcollection.push(signCollection); // eslint-disable-next-line let signature: any = []; signature.push({ id: 'sign_' + this.pdfViewerBase.imageCount, imageData: imageString, signatureType: signatureType, fontFamily: this.pdfViewerBase.currentSignatureAnnot.fontFamily }); this.signaturecollection.push({ image: signature, isInitial: this.pdfViewerBase.isInitialField }); this.pdfViewerBase.imageCount++; } } /** * @private] * @param {number} limit - The limit. * @returns {number} - Returns number. */ public getSaveLimit(limit: number): number { if (limit > this.maxSaveLimit) { limit = this.maxSaveLimit; } else if (limit < 1) { limit = 1; } return limit; } /** * @private * @returns {void} */ public RenderSavedSignature(): void { this.pdfViewerBase.signatureCount++; const zoomvalue: number = this.pdfViewerBase.getZoomFactor(); let annot: PdfAnnotationBaseModel; if (this.pdfViewerBase.isAddedSignClicked) { const annotationName: string = this.pdfViewer.annotation.createGUID(); this.pdfViewerBase.currentSignatureAnnot = null; this.pdfViewerBase.isSignatureAdded = true; const pageIndex: number = this.pdfViewerBase.currentPageNumber - 1; const pageDiv: HTMLElement = document.getElementById(this.pdfViewer.element.id + '_pageDiv_' + pageIndex); let currentLeft: number = 0; let currentTop: number = 0; // eslint-disable-next-line max-len let currentWidth: number = this.pdfViewer.handWrittenSignatureSettings.width ? this.pdfViewer.handWrittenSignatureSettings.width : 100; // eslint-disable-next-line max-len let currentHeight: number = this.pdfViewer.handWrittenSignatureSettings.height ? this.pdfViewer.handWrittenSignatureSettings.height : 100; // eslint-disable-next-line max-len const thickness: number = this.pdfViewer.handWrittenSignatureSettings.thickness ? this.pdfViewer.handWrittenSignatureSettings.thickness : 1; // eslint-disable-next-line max-len const opacity: number = this.pdfViewer.handWrittenSignatureSettings.opacity ? this.pdfViewer.handWrittenSignatureSettings.opacity : 1; // eslint-disable-next-line max-len const strokeColor: string = this.pdfViewer.handWrittenSignatureSettings.strokeColor ? this.pdfViewer.handWrittenSignatureSettings.strokeColor : '#000000'; currentLeft = ((parseFloat(pageDiv.style.width) / 2) - (currentWidth / 2)) / zoomvalue; // eslint-disable-next-line max-len currentTop = ((parseFloat(pageDiv.style.height) / 2) - (currentHeight / 2)) / zoomvalue; let keyString: string = ''; let signatureType: PdfAnnotationType; let signatureFontFamily: string; for (let collection: number = 0; collection < this.outputcollection.length; collection++) { // eslint-disable-next-line let collectionAddedsign: any = this.outputcollection[collection]; // eslint-disable-next-line let eventTarget: HTMLElement = event.target as HTMLElement; // eslint-disable-next-line max-len if (eventTarget && eventTarget.id === 'sign_' + collection || eventTarget && eventTarget.id === 'sign_border' + collection) { keyString = collectionAddedsign['sign_' + collection]; break; } } for (let signatureIndex: number = 0; signatureIndex < this.signaturecollection.length; signatureIndex++) { const eventTarget: HTMLElement = event.target as HTMLElement; const signatureId: string = this.signaturecollection[signatureIndex].image[0].id.split('_')[1]; if (eventTarget && eventTarget.id === 'sign_' + signatureId || eventTarget && eventTarget.id === 'sign_border' + signatureId) { signatureType = this.signaturecollection[signatureIndex].image[0].signatureType; signatureFontFamily = this.signaturecollection[signatureIndex].image[0].fontFamily; break; } } if (signatureType === 'HandWrittenSignature') { // eslint-disable-next-line const signatureBounds: any = this.pdfViewer.formFieldsModule.updateSignatureAspectRatio(keyString, true); // eslint-disable-next-line max-len currentWidth = signatureBounds.width ? signatureBounds.width : currentWidth; // eslint-disable-next-line max-len currentHeight = signatureBounds.height ? signatureBounds.height : currentHeight; } else { currentWidth = currentWidth === 150 ? 200 : this.pdfViewer.handWrittenSignatureSettings.width; // eslint-disable-next-line max-len currentHeight = currentHeight === 100 ? 65 : this.pdfViewer.handWrittenSignatureSettings.height; } annot = { // eslint-disable-next-line max-len id: 'sign' + this.pdfViewerBase.signatureCount, bounds: { x: currentLeft, y: currentTop, width: currentWidth, height: currentHeight }, pageIndex: pageIndex, data: keyString, // eslint-disable-next-line max-len shapeAnnotationType: signatureType, opacity: opacity, fontFamily: signatureFontFamily, strokeColor: strokeColor, thickness: thickness, signatureName: annotationName }; this.pdfViewerBase.currentSignatureAnnot = annot; this.pdfViewerBase.isAddedSignClicked = false; } else { this.pdfViewer.formFieldsModule.drawSignature(); } } /** * @private * @returns {void} */ public updateCanvasSize(): void { // eslint-disable-next-line let canvas: any = document.getElementById(this.pdfViewer.element.id + '_signatureCanvas_'); if (canvas && this.signatureDialog && this.signatureDialog.visible) { if (this.pdfViewer.element.offsetWidth > 750) { canvas.width = 714; canvas.style.width = '714px'; } else { canvas.width = this.pdfViewer.element.offsetWidth - 35; canvas.style.width = canvas.width + 'px'; } } } private signaturePanelMouseDown(e: MouseEvent | TouchEvent): void { if (e.type !== 'contextmenu') { e.preventDefault(); this.findMousePosition(e); this.mouseDetection = true; this.oldX = this.mouseX; this.oldY = this.mouseY; this.newObject = []; this.drawMousePosition(e); } } private enableCreateButton(isEnable: boolean): void { // eslint-disable-next-line let createbtn: any = document.getElementsByClassName('e-pv-createbtn')[0]; if (createbtn) { createbtn.disabled = isEnable; } this.enableClearbutton(isEnable); } private enableClearbutton(isEnable: boolean): void { // eslint-disable-next-line let clearbtn: any = document.getElementsByClassName('e-pv-clearbtn')[0]; if (clearbtn) { clearbtn.disabled = isEnable; } } private signaturePanelMouseMove(e: MouseEvent | TouchEvent): void { if (this.mouseDetection) { this.findMousePosition(e); this.enableCreateButton(false); this.drawMousePosition(e); } } private findMousePosition(event: MouseEvent | TouchEvent): void { let offsetX: number; let offsetY: number; if (event.type.indexOf('touch') !== -1) { event = event as TouchEvent; const element: HTMLElement = event.target as HTMLElement; // eslint-disable-next-line let currentRect: any = element.getBoundingClientRect(); this.mouseX = event.touches[0].pageX - currentRect.left; this.mouseY = event.touches[0].pageY - currentRect.top; } else { event = event as MouseEvent; this.mouseX = event.offsetX; this.mouseY = event.offsetY; } } private drawMousePosition(event: MouseEvent | TouchEvent): void { if (this.mouseDetection) { this.drawSignatureInCanvas(); this.oldX = this.mouseX; this.oldY = this.mouseY; } } private drawSignatureInCanvas(): void { // eslint-disable-next-line let canvas: any = document.getElementById(this.pdfViewer.element.id + '_signatureCanvas_'); // eslint-disable-next-line let context: any = canvas.getContext('2d'); context.beginPath(); context.moveTo(this.oldX, this.oldY); context.lineTo(this.mouseX, this.mouseY); context.stroke(); context.lineWidth = 2; context.arc(this.oldX, this.oldY, 2 / 2, 0, Math.PI * 2, true); context.closePath(); this.newObject.push(this.mouseX, this.mouseY); } private signaturePanelMouseUp(): void { if (this.mouseDetection) { this.convertToPath(this.newObject); } this.mouseDetection = false; } // eslint-disable-next-line private convertToPath(newObject: any): void { this.movePath(newObject[0], newObject[1]); this.linePath(newObject[0], newObject[1]); for (let n: number = 2; n < newObject.length; n = n + 2) { this.linePath(newObject[n], newObject[n + 1]); } } private linePath(x: number, y: number): void { this.outputString += 'L' + x + ',' + y + ' '; } private movePath(x: number, y: number): void { this.outputString += 'M' + x + ',' + y + ' '; } /** * @private * @returns {void} */ public clearSignatureCanvas(): void { this.outputString = ''; this.newObject = []; // eslint-disable-next-line let canvas: any = document.getElementById(this.pdfViewer.element.id + '_signatureCanvas_'); // eslint-disable-next-line if (canvas) { // eslint-disable-next-line let context: any = canvas.getContext('2d'); context.clearRect(0, 0, canvas.width, canvas.height); } // eslint-disable-next-line let imageCanvas: any = document.getElementById(this.pdfViewer.element.id + '_signatureuploadCanvas_'); if (imageCanvas) { // eslint-disable-next-line let context: any = imageCanvas.getContext('2d'); context.clearRect(0, 0, imageCanvas.width, imageCanvas.height); // eslint-disable-next-line let signbutton: any = document.getElementById(this.pdfViewer.element.id + '_e-pv-upload-button'); if (signbutton) { signbutton.style.visibility = ''; } } // eslint-disable-next-line let fontdiv: any = document.getElementById(this.pdfViewer.element.id + '_font_appearance'); // eslint-disable-next-line let textbox: any = document.getElementById(this.pdfViewer.element.id + '_e-pv-Signtext-box'); if (fontdiv && textbox) { textbox.value = ''; if (!isBlazor()) { fontdiv.innerHTML = ''; } } this.enableCreateButton(true); } /** * @private * @returns {void} */ public closeSignaturePanel(): void { if (this.pdfViewerBase.currentTarget) { this.pdfViewerBase.drawSignatureWithTool = true; } this.clearSignatureCanvas(); if (!isBlazor()) { this.signatureDialog.hide(); } this.pdfViewerBase.isToolbarSignClicked = false; this.pdfViewerBase.drawSignatureWithTool = false; } /** * @private * @returns {string} - Returns the string. */ public saveSignature(): string { // eslint-disable-next-line let storeObject: string = null; if (this.pdfViewerBase.isStorageExceed) { storeObject = this.pdfViewerBase.annotationStorage[this.pdfViewerBase.documentId + '_annotations_sign']; } else { storeObject = window.sessionStorage.getItem(this.pdfViewerBase.documentId + '_annotations_sign'); } // eslint-disable-next-line let annotations: Array<any> = new Array(); for (let j: number = 0; j < this.pdfViewerBase.pageCount; j++) { annotations[j] = []; } if (storeObject) { const annotationCollection: IPageAnnotations[] = JSON.parse(storeObject); for (let i: number = 0; i < annotationCollection.length; i++) { let newArray: ISignAnnotation[] = []; const pageAnnotationObject: IPageAnnotations = annotationCollection[i]; if (pageAnnotationObject) { for (let z: number = 0; pageAnnotationObject.annotations.length > z; z++) { // eslint-disable-next-line max-len const strokeColorString: string = pageAnnotationObject.annotations[z].strokeColor; pageAnnotationObject.annotations[z].strokeColor = JSON.stringify(this.getRgbCode(strokeColorString)); // eslint-disable-next-line max-len pageAnnotationObject.annotations[z].bounds = JSON.stringify(this.pdfViewer.annotation.getBounds(pageAnnotationObject.annotations[z].bounds, pageAnnotationObject.pageIndex)); if (pageAnnotationObject.annotations[z].shapeAnnotationType === 'HandWrittenSignature') { // eslint-disable-next-line let collectionData: any = processPathData(pageAnnotationObject.annotations[z].data); // eslint-disable-next-line let csData: any = splitArrayCollection(collectionData); pageAnnotationObject.annotations[z].data = JSON.stringify(csData); } else { if (pageAnnotationObject.annotations[z].shapeAnnotationType === 'SignatureText' && !this.checkDefaultFont(pageAnnotationObject.annotations[z].fontFamily)) { const signTypeCanvas: HTMLCanvasElement = createElement('canvas') as HTMLCanvasElement; signTypeCanvas.width = 150; signTypeCanvas.height = pageAnnotationObject.annotations[z].fontSize * 2; // eslint-disable-next-line const canvasContext: any = signTypeCanvas.getContext('2d'); const x: number = signTypeCanvas.width / 2; const y: number = (signTypeCanvas.height / 2) - 10; canvasContext.textAlign = 'center'; canvasContext.font = pageAnnotationObject.annotations[z].fontSize + 'px ' + pageAnnotationObject.annotations[z].fontFamily; canvasContext.fillText(pageAnnotationObject.annotations[z].data, x, y); pageAnnotationObject.annotations[z].data = JSON.stringify(signTypeCanvas.toDataURL('image/png')); pageAnnotationObject.annotations[z].shapeAnnotationType = 'SignatureImage'; } else { pageAnnotationObject.annotations[z].data = JSON.stringify(pageAnnotationObject.annotations[z].data); } } } newArray = pageAnnotationObject.annotations; } annotations[pageAnnotationObject.pageIndex] = newArray; } } return JSON.stringify(annotations); } private checkDefaultFont(fontName: string): boolean { // eslint-disable-next-line [{ FontName: 'Helvetica' }, { FontName: 'Times New Roman' }, { FontName: 'Courier' }, { FontName: 'Symbol' }]; if (fontName === 'Helvetica' || fontName === 'Times New Roman' || fontName === 'Courier' || fontName === 'Symbol') { return true; } return false; } /** * @param colorString * @private */ // eslint-disable-next-line public getRgbCode(colorString: string): any { if (!colorString.match(/#([a-z0-9]+)/gi) && !colorString.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/)) { colorString = this.pdfViewer.annotationModule.nameToHash(colorString); } let stringArray: string[] = colorString.split(','); if (isNullOrUndefined(stringArray[1])) { colorString = this.pdfViewer.annotationModule.getValue(colorString, 'rgba'); stringArray = colorString.split(','); } // eslint-disable-next-line radix const r: number = parseInt(stringArray[0].split('(')[1]); // eslint-disable-next-line radix const g: number = parseInt(stringArray[1]); // eslint-disable-next-line radix const b: number = parseInt(stringArray[2]); // eslint-disable-next-line radix const a: number = parseInt(stringArray[3]); return { r: r, g: g, b: b, a: a }; } /** * @private * @param {number} left - The left. * @param {number} top - The top. * @returns {void} */ public renderSignature(left: number, top: number): void { let annot: PdfAnnotationBaseModel; // eslint-disable-next-line let currentAnnotation: any = this.pdfViewerBase.currentSignatureAnnot; const annotationName: string = this.pdfViewer.annotation.createGUID(); if (currentAnnotation) { annot = { // eslint-disable-next-line max-len id: currentAnnotation.id, bounds: { x: left, y: top, width: currentAnnotation.bounds.width, height: currentAnnotation.bounds.height }, pageIndex: currentAnnotation.pageIndex, data: currentAnnotation.data, shapeAnnotationType: 'HandWrittenSignature', opacity: currentAnnotation.opacity, strokeColor: currentAnnotation.strokeColor, thickness: currentAnnotation.thickness, signatureName: annotationName }; this.pdfViewer.add(annot as PdfAnnotationBase); // eslint-disable-next-line let canvass: any = document.getElementById(this.pdfViewer.element.id + '_annotationCanvas_' + currentAnnotation.pageIndex); // eslint-disable-next-line this.pdfViewer.renderDrawing(canvass as any, currentAnnotation.pageIndex); this.pdfViewerBase.signatureAdded = true; // eslint-disable-next-line max-len this.pdfViewer.fireSignatureAdd(currentAnnotation.pageIndex, currentAnnotation.signatureName, currentAnnotation.shapeAnnotationType, currentAnnotation.bounds, currentAnnotation.opacity, currentAnnotation.strokeColor, currentAnnotation.thickness); this.storeSignatureData(currentAnnotation.pageIndex, annot); this.pdfViewerBase.currentSignatureAnnot = null; this.pdfViewerBase.signatureCount++; } } /** * @param annotationCollection * @param pageIndex * @param isImport * @private */ // eslint-disable-next-line public renderExistingSignature(annotationCollection: any, pageIndex: number, isImport: boolean): void { let annot: PdfAnnotationBaseModel; for (let n: number = 0; n < annotationCollection.length; n++) { // eslint-disable-next-line let currentAnnotation: any = annotationCollection[n]; // eslint-disable-next-line if (currentAnnotation) { // eslint-disable-next-line let bounds: any = currentAnnotation.Bounds; const currentLeft: number = bounds.X; const currentTop: number = bounds.Y; const currentWidth: number = bounds.Width; const currentHeight: number = bounds.Height; // eslint-disable-next-line let data: any = currentAnnotation.PathData; if (isImport) { if (currentAnnotation.IsSignature) { data = currentAnnotation.PathData; } else if (currentAnnotation.AnnotationType === 'SignatureImage' || currentAnnotation.AnnotationType === 'SignatureText' ) { data = JSON.parse(currentAnnotation.PathData); } else { if (data.includes('command')) { data = getPathString(JSON.parse(currentAnnotation.PathData)); } else { data = currentAnnotation.PathData; } } } if (currentAnnotation.AnnotationType === 'SignatureText') { annot = { // eslint-disable-next-line max-len id: 'sign' + this.pdfViewerBase.signatureCount, bounds: { x: currentLeft, y: currentTop, width: currentWidth, height: currentHeight }, pageIndex: pageIndex, data: data, fontFamily: currentAnnotation.FontFamily, fontSize: currentAnnotation.FontSize, shapeAnnotationType: 'SignatureText', opacity: currentAnnotation.Opacity, strokeColor: currentAnnotation.StrokeColor, thickness: currentAnnotation.Thickness, signatureName: currentAnnotation.SignatureName }; } else if (currentAnnotation.AnnotationType === 'SignatureImage') { annot = { // eslint-disable-next-line max-len id: 'sign' + this.pdfViewerBase.signatureCount, bounds: { x: currentLeft, y: currentTop, width: currentWidth, height: currentHeight }, pageIndex: pageIndex, data: data, shapeAnnotationType: 'SignatureImage', opacity: currentAnnotation.Opacity, strokeColor: currentAnnotation.StrokeColor, thickness: currentAnnotation.Thickness, signatureName: currentAnnotation.SignatureName }; } else { annot = { // eslint-disable-next-line max-len id: 'sign' + this.pdfViewerBase.signatureCount, bounds: { x: currentLeft, y: currentTop, width: currentWidth, height: currentHeight }, pageIndex: pageIndex, data: data, shapeAnnotationType: 'HandWrittenSignature', opacity: currentAnnotation.Opacity, strokeColor: currentAnnotation.StrokeColor, thickness: currentAnnotation.Thickness, signatureName: currentAnnotation.SignatureName }; } this.pdfViewer.add(annot as PdfAnnotationBase); // eslint-disable-next-line let canvass: any = document.getElementById(this.pdfViewer.element.id + '_annotationCanvas_' + currentAnnotation.pageIndex); // eslint-disable-next-line this.pdfViewer.renderDrawing(canvass as any, annot.pageIndex); this.storeSignatureData(annot.pageIndex, annot); this.pdfViewerBase.currentSignatureAnnot = null; this.pdfViewerBase.signatureCount++; // eslint-disable-next-line max-len if (this.pdfViewerBase.navigationPane && this.pdfViewerBase.navigationPane.annotationMenuObj && this.pdfViewer.isSignatureEditable) { // eslint-disable-next-line max-len this.pdfViewerBase.navigationPane.annotationMenuObj.enableItems([this.pdfViewer.localeObj.getConstant('Export Annotations')], true); // eslint-disable-next-line max-len this.pdfViewerBase.navigationPane.annotationMenuObj.enableItems([this.pdfViewer.localeObj.getConstant('Export XFDF')], true); } } } } /** * @param pageNumber * @param annotations * @private */ // eslint-disable-next-line public storeSignatureData(pageNumber: number, annotations: any): void { // eslint-disable-next-line max-len this.pdfViewer.annotation.addAction(annotations.pageIndex, null, annotations as PdfAnnotationBase, 'Addition', '', annotations as PdfAnnotationBase, annotations); let annotation: ISignAnnotation = null; let left: number = annotations.bounds.left ? annotations.bounds.left : annotations.bounds.x; let top: number = annotations.bounds.top ? annotations.bounds.top : annotations.bounds.y; if (annotations.wrapper && annotations.wrapper.bounds) { left = annotations.wrapper.bounds.left; top = annotations.wrapper.bounds.top; } annotation = { // eslint-disable-next-line max-len id: annotations.id, bounds: { left: left, top: top, width: annotations.bounds.width, height: annotations.bounds.height }, shapeAnnotationType: annotations.shapeAnnotationType, opacity: annotations.opacity, thickness: annotations.thickness, strokeColor: annotations.strokeColor, pageIndex: annotations.pageIndex, data: annotations.data, fontSize: annotations.fontSize, fontFamily: annotations.fontFamily, signatureName: annotations.signatureName }; // eslint-disable-next-line const sessionSize: any = Math.round(JSON.stringify(window.sessionStorage).length / 1024); // eslint-disable-next-line const currentAnnotation: any = Math.round(JSON.stringify(annotation).length / 1024); if ((sessionSize + currentAnnotation) > 4500) { this.pdfViewerBase.isStorageExceed = true; this.pdfViewer.annotationModule.clearAnnotationStorage(); } // eslint-disable-next-line let storeObject: any = window.sessionStorage.getItem(this.pdfViewerBase.documentId + '_annotations_sign'); let index: number = 0; if (!storeObject) { this.storeSignatureCollections(annotation, pageNumber); const shapeAnnotation: IPageAnnotations = { pageIndex: pageNumber, annotations: [] }; shapeAnnotation.annotations.push(annotation); index = shapeAnnotation.annotations.indexOf(annotation); const annotationCollection: IPageAnnotations[] = []; annotationCollection.push(shapeAnnotation); const annotationStringified: string = JSON.stringify(annotationCollection); if (this.pdfViewerBase.isStorageExceed) { this.pdfViewerBase.annotationStorage[this.pdfViewerBase.documentId + '_annotations_sign'] = annotationStringified; } else { window.sessionStorage.setItem(this.pdfViewerBase.documentId + '_annotations_sign', annotationStringified); } } else { this.storeSignatureCollections(annotation, pageNumber); const annotObject: IPageAnnotations[] = JSON.parse(storeObject); window.sessionStorage.removeItem(this.pdfViewerBase.documentId + '_annotations_sign'); const pageIndex: number = this.pdfViewer.annotationModule.getPageCollection(annotObject, pageNumber); if (annotObject[pageIndex]) { (annotObject[pageIndex] as IPageAnnotations).annotations.push(annotation); index = (annotObject[pageIndex] as IPageAnnotations).annotations.indexOf(annotation); } else { const markupAnnotation: IPageAnnotations = { pageIndex: pageNumber, annotations: [] }; markupAnnotation.annotations.push(annotation); index = markupAnnotation.annotations.indexOf(annotation); annotObject.push(markupAnnotation); } const annotationStringified: string = JSON.stringify(annotObject); if (this.pdfViewerBase.isStorageExceed) { this.pdfViewerBase.annotationStorage[this.pdfViewerBase.documentId + '_annotations_sign'] = annotationStringified; } else { window.sessionStorage.setItem(this.pdfViewerBase.documentId + '_annotations_sign', annotationStringified); } } } /** * @param property * @param pageNumber * @param annotationBase * @param isSignatureEdited * @private */ // eslint-disable-next-line public modifySignatureCollection(property: string, pageNumber: number, annotationBase: any, isSignatureEdited?: boolean): ISignAnnotation { this.pdfViewer.isDocumentEdited = true; let currentAnnotObject: ISignAnnotation = null; const pageAnnotations: ISignAnnotation[] = this.getAnnotations(pageNumber, null); if (pageAnnotations != null && annotationBase) { for (let i: number = 0; i < pageAnnotations.length; i++) { if (annotationBase.id === pageAnnotations[i].id) { if (property === 'bounds') { // eslint-disable-next-line max-len pageAnnotations[i].bounds = { left: annotationBase.wrapper.bounds.left, top: annotationBase.wrapper.bounds.top, width: annotationBase.bounds.width, height: annotationBase.bounds.height }; pageAnnotations[i].fontSize = annotationBase.fontSize; } else if (property === 'stroke') { pageAnnotations[i].strokeColor = annotationBase.wrapper.children[0].style.strokeColor; } else if (property === 'opacity') { pageAnnotations[i].opacity = annotationBase.wrapper.children[0].style.opacity; } else if (property === 'thickness') { pageAnnotations[i].thickness = annotationBase.wrapper.children[0].style.strokeWidth; } else if (property === 'delete') { this.updateSignatureCollection(pageAnnotations[i]); currentAnnotObject = pageAnnotations.splice(i, 1)[0]; break; } if (property && property !== 'delete') { this.storeSignatureCollections(pageAnnotations[i], pageNumber); } if (isSignatureEdited) { pageAnnotations[i].opacity = annotationBase.wrapper.children[0].style.opacity; pageAnnotations[i].strokeColor = annotationBase.wrapper.children[0].style.strokeColor; pageAnnotations[i].thickness = annotationBase.wrapper.children[0].style.strokeWidth; this.storeSignatureCollections(pageAnnotations[i], pageNumber); break; } } } this.manageAnnotations(pageAnnotations, pageNumber); } return currentAnnotObject; } /** * @param annotation * @param pageNumber * @private */ // eslint-disable-next-line public storeSignatureCollections(annotation: any, pageNumber: number): void { // eslint-disable-next-line let collectionDetails: any = this.checkSignatureCollection(annotation); // eslint-disable-next-line let selectAnnotation: any = cloneObject(annotation); selectAnnotation.annotationId = annotation.signatureName; selectAnnotation.pageNumber = pageNumber; delete selectAnnotation.annotName; if (annotation.id) { selectAnnotation.uniqueKey = annotation.id; delete selectAnnotation.id; } if (collectionDetails.isExisting) { this.pdfViewer.signatureCollection.splice(collectionDetails.position, 0, selectAnnotation); } else { this.pdfViewer.signatureCollection.push(selectAnnotation); } } // eslint-disable-next-line private checkSignatureCollection(signature: any): any { // eslint-disable-next-line let collections: any = this.pdfViewer.signatureCollection; if (collections && signature) { for (let i: number = 0; i < collections.length; i++) { if (collections[i].annotationId === signature.signatureName) { this.pdfViewer.signatureCollection.splice(i, 1); return { isExisting: true, position: i }; } } } return { isExisting: false, position: null }; } /** * @param signature * @private */ // eslint-disable-next-line public updateSignatureCollection(signature: any): void { // eslint-disable-next-line let collections: any = this.pdfViewer.signatureCollection; if (collections && signature) { for (let i: number = 0; i < collections.length; i++) { if (collections[i].annotationId === signature.signatureName) { this.pdfViewer.signatureCollection.splice(i, 1); break; } } } } /** * @param pageNumber * @param signature * @private */ // eslint-disable-next-line public addInCollection(pageNumber: number, signature: any): void { if (signature) { this.storeSignatureCollections(signature, pageNumber); // eslint-disable-next-line let pageSignatures: any[] = this.getAnnotations(pageNumber, null); if (pageSignatures) { pageSignatures.push(signature); } this.manageAnnotations(pageSignatures, pageNumber); } } // eslint-disable-next-line private getAnnotations(pageIndex: number, shapeAnnotations: any[]): any[] { // eslint-disable-next-line let annotationCollection: any[]; // eslint-disable-next-line let storeObject: string = null; if (this.pdfViewerBase.isStorageExceed){ storeObject = this.pdfViewerBase.annotationStorage[this.pdfViewerBase.documentId + '_annotations_sign']; } else { storeObject = window.sessionStorage.getItem(this.pdfViewerBase.documentId + '_annotations_sign'); } if (storeObject) { const annotObject: IPageAnnotations[] = JSON.parse(storeObject); const index: number = this.pdfViewer.annotationModule.getPageCollection(annotObject, pageIndex); if (annotObject[index]) { annotationCollection = annotObject[index].annotations; } else { annotationCollection = shapeAnnotations; } } else { annotationCollection = shapeAnnotations; } return annotationCollection; } private manageAnnotations(pageAnnotations: ISignAnnotation[], pageNumber: number): void { // eslint-disable-next-line let storeObject: string = null; if (this.pdfViewerBase.isStorageExceed) { storeObject = this.pdfViewerBase.annotationStorage[this.pdfViewerBase.documentId + '_annotations_sign']; } else { storeObject = window.sessionStorage.getItem(this.pdfViewerBase.documentId + '_annotations_sign'); } if (storeObject) { const annotObject: IPageAnnotations[] = JSON.parse(storeObject); window.sessionStorage.removeItem(this.pdfViewerBase.documentId + '_annotations_sign'); const index: number = this.pdfViewer.annotationModule.getPageCollection(annotObject, pageNumber); if (annotObject[index]) { annotObject[index].annotations = pageAnnotations; } const annotationStringified: string = JSON.stringify(annotObject); if (this.pdfViewerBase.isStorageExceed) { this.pdfViewerBase.annotationStorage[this.pdfViewerBase.documentId + '_annotations_sign'] = annotationStringified; } else { window.sessionStorage.setItem(this.pdfViewerBase.documentId + '_annotations_sign', annotationStringified); } } } /** * @private * @param {boolean} isShow - Returns the true or false. * @returns {void} */ public showSignatureDialog(isShow: boolean): void { if (isShow) { this.createSignaturePanel(); } } /** * @private * @returns {void} */ public setAnnotationMode(): void { this.pdfViewerBase.isToolbarSignClicked = true; this.showSignatureDialog(true); } /** * @private * @returns {void} */ public setInitialMode(): void { this.pdfViewerBase.isToolbarSignClicked = true; this.pdfViewerBase.isInitialField = true; this.showSignatureDialog(true); } /** * @param number * @private */ // eslint-disable-next-line public ConvertPointToPixel(number: any): any { return (number * (96 / 72)); } /** * @param signature * @param pageIndex * @param isImport * @private */ // eslint-disable-next-line public updateSignatureCollections(signature: any, pageIndex: number, isImport?: boolean): any { let annot: PdfAnnotationBaseModel; // eslint-disable-next-line if (signature) { // eslint-disable-next-line let bounds: any = signature.Bounds; const currentLeft: number = bounds.X; const currentTop: number = bounds.Y; const currentWidth: number = bounds.Width; const currentHeight: number = bounds.Height; // eslint-disable-next-line let data: any = signature.PathData; if (isImport) { data = getPathString(JSON.parse(signature.PathData)); } annot = { // eslint-disable-next-line max-len id: 'sign' + signature.SignatureName, bounds: { x: currentLeft, y: currentTop, width: currentWidth, height: currentHeight }, pageIndex: pageIndex, data: data, shapeAnnotationType: 'HandWrittenSignature', opacity: signature.Opacity, strokeColor: signature.StrokeColor, thickness: signature.Thickness, signatureName: signature.SignatureName }; return annot; } } /** * @private * @returns {void} */ public destroy(): void { window.sessionStorage.removeItem('_annotations_sign'); // eslint-disable-next-line let signImage: any = document.getElementById(this.pdfViewer.element.id + '_signElement'); if (signImage) { signImage.removeEventListener('change', this.addStampImage); if (signImage.parentElement) signImage.parentElement.removeChild(signImage); } if (this.signatureDialog) this.signatureDialog.destroy(); } }
the_stack
import assert from 'assert'; import request from 'axios'; import debugTest from 'debug'; import EventEmitter from 'events'; import type { ErrorRequestHandler, Express } from 'express'; import express from 'express'; import http from 'http'; import shutdown from 'http-shutdown'; import type { InlineKeyboardMarkup, Message, MessageEntity, Params, } from 'typegram'; import { requestLogger } from './modules/requestLogger'; import { sendResult } from './modules/sendResult'; import type { CallbackQueryRequest, ClientOptions, CommandRequest, MessageRequest, } from './modules/telegramClient'; import { TelegramClient, } from './modules/telegramClient'; import { routes } from './routes/index'; const debugServer = debugTest('TelegramServer:server'); const debugStorage = debugTest('TelegramServer:storage'); interface WebHook { url: string; } type Server = ReturnType<typeof shutdown>; interface StoredUpdate { time: number; botToken: string; updateId: number; messageId: number; isRead: boolean; } type BotIncommingMessage = Params<'sendMessage', never>[0]; type BotEditTextIncommingMessage = Params<'editMessageText', never>[0]; type RawIncommingMessage = { reply_markup?: string | object; entities?:string | object } export interface StoredBotUpdate extends StoredUpdate { message: BotIncommingMessage; } interface StoredMessageUpdate extends StoredUpdate { message: MessageRequest; } interface StoredCommandUpdate extends StoredUpdate { message: CommandRequest; entities: MessageEntity[]; } interface StoredCallbackQueryUpdate extends StoredUpdate { callbackQuery: CallbackQueryRequest; callbackId: number; } export type StoredClientUpdate = | StoredMessageUpdate | StoredCommandUpdate | StoredCallbackQueryUpdate; interface Storage { userMessages: StoredClientUpdate[]; botMessages: StoredBotUpdate[]; } export interface TelegramServerConfig { /** @default 9000 */ port: number; /** @default localhost */ host: string; /** @default http */ protocol: 'http' | 'https'; /** where you want to store messages. Right now, only RAM option is implemented. */ storage: 'RAM' | string; /** * how many seconds you want to store user and bot messages which were not fetched by bot or client. * @default 60 */ storeTimeout: number; } export class TelegramServer extends EventEmitter { private webServer: Express; private started = false; private updateId = 1; private messageId = 1; private callbackId = 1; public config: TelegramServerConfig & { apiURL: string }; public storage: Storage = { userMessages: [], botMessages: [], }; // eslint-disable-next-line no-undef private cleanUpDaemonInterval: NodeJS.Timer | null = null; private server: Server | null = null; private webhooks: Record<string, WebHook> = {}; constructor(config: Partial<TelegramServerConfig> = {}) { super(); this.config = TelegramServer.normalizeConfig(config); debugServer(`Telegram API server config: ${JSON.stringify(this.config)}`); this.webServer = express(); this.webServer.use(sendResult); this.webServer.use(express.json()); this.webServer.use(express.urlencoded({ extended: true })); this.webServer.use(requestLogger); if (this.config.storage === 'RAM') { this.storage = { userMessages: [], botMessages: [], }; } for (let i = 0; i < routes.length; i++) { routes[i](this.webServer, this); } // there was no route to process request this.webServer.use((_req, res) => { res.sendError(new Error('Route not found')); }); /** * Catch uncought errors e.g. express bodyParser error * @see https://expressjs.com/en/guide/error-handling.html#the-default-error-handler */ const globalErrorHandler: ErrorRequestHandler = (error, _req, res, _next) => { debugServer(`Error: ${error}`); res.sendError(new Error(`Something went wrong. ${error}`)); }; this.webServer.use(globalErrorHandler); } static normalizeConfig(config: Partial<TelegramServerConfig>) { const appConfig = { port: config.port || 9000, host: config.host || 'localhost', protocol: config.protocol || 'http', storage: config.storage || 'RAM', storeTimeout: (config.storeTimeout || 60) * 1000, // store for a minute by default apiURL: '', }; appConfig.apiURL = `${appConfig.protocol}://${appConfig.host}:${appConfig.port}`; return appConfig; } getClient(botToken: string, options?: Partial<ClientOptions>) { return new TelegramClient(this.config.apiURL, botToken, options); } addBotMessage(rawMessage: BotIncommingMessage, botToken: string) { const d = new Date(); const millis = d.getTime(); const message = TelegramServer.normalizeMessage(rawMessage); const add = { time: millis, botToken, message, updateId: this.updateId, messageId: this.messageId, isRead: false, }; this.storage.botMessages.push(add); // only InlineKeyboardMarkup is allowed in response let inlineMarkup: InlineKeyboardMarkup | undefined; if (message.reply_markup && 'inline_keyboard' in message.reply_markup) { inlineMarkup = message.reply_markup; } const msg: Message.TextMessage = { ...message, reply_markup: inlineMarkup, message_id: this.messageId, date: add.time, text: message.text, chat: { id: Number(message.chat_id), first_name: 'Bot', type: 'private', }, }; this.messageId++; this.updateId++; this.emit('AddedBotMessage'); return msg; } editMessageText(rawMessage: BotEditTextIncommingMessage) { const message = TelegramServer.normalizeMessage(rawMessage); const update = this.storage.botMessages.find( (u) =>( String(u.messageId) === String(message.message_id) && String(u.message.chat_id) === String(message.chat_id) ), ); if (update) { update.message = {...update.message, ...message }; this.emit('EditedMessageText'); } } async waitBotEdits() { return new Promise<void>((resolve) => { this.once('EditedMessageText', () => resolve()); }); } async waitBotMessage() { return new Promise<void>((resolve) => { this.once('AddedBotMessage', () => resolve()); }); } async waitUserMessage() { return new Promise<void>((resolve) => { const messageHandler = () => { this.off('AddedUserMessage', messageHandler); this.off('AddedUserCommand', messageHandler); this.off('AddedUserCallbackQuery', messageHandler); resolve(); }; this.on('AddedUserMessage', messageHandler); this.on('AddedUserCommand', messageHandler); this.on('AddedUserCallbackQuery', messageHandler); }); } async addUserMessage(message: MessageRequest) { await this.addUserUpdate({ ...this.getCommonFields(message.botToken), message, }); this.messageId++; this.emit('AddedUserMessage'); } async addUserCommand(message: CommandRequest) { assert.ok(message.entities, 'Command should have entities'); await this.addUserUpdate({ ...this.getCommonFields(message.botToken), message, entities: message.entities, }); this.messageId++; this.emit('AddedUserCommand'); } async addUserCallback(callbackQuery: CallbackQueryRequest) { await this.addUserUpdate({ ...this.getCommonFields(callbackQuery.botToken), callbackQuery, callbackId: this.callbackId, }); this.callbackId++; this.emit('AddedUserCallbackQuery'); } private getCommonFields(botToken: string) { const d = new Date(); const millis = d.getTime(); return { time: millis, botToken, updateId: this.updateId, messageId: this.messageId, isRead: false, }; } private async addUserUpdate(update: StoredClientUpdate) { assert.ok( update.botToken, 'The message must be of type object and must contain `botToken` field.', ); const webhook = this.webhooks[update.botToken]; if (webhook) { const resp = await request({ url: webhook.url, method: 'POST', data: TelegramServer.formatUpdate(update), }); if (resp.status > 204) { debugServer( `Webhook invocation failed: ${JSON.stringify({ url: webhook.url, method: 'POST', requestBody: update, responseStatus: resp.status, responseBody: resp.data, })}`, ); throw new Error('Webhook invocation failed'); } } else { this.storage.userMessages.push(update); } this.updateId++; } messageFilter(message: StoredUpdate) { const d = new Date(); const millis = d.getTime(); return message.time > millis - this.config.storeTimeout; } cleanUp() { debugStorage('clearing storage'); debugStorage( `current userMessages storage: ${this.storage.userMessages.length}`, ); this.storage.userMessages = this.storage.userMessages.filter( this.messageFilter, this, ); debugStorage( `filtered userMessages storage: ${this.storage.userMessages.length}`, ); debugStorage( `current botMessages storage: ${this.storage.botMessages.length}`, ); this.storage.botMessages = this.storage.botMessages.filter( this.messageFilter, this, ); debugStorage( `filtered botMessages storage: ${this.storage.botMessages.length}`, ); } cleanUpDaemon() { if (!this.started) { return; } this.cleanUpDaemonInterval = setInterval( this.cleanUp.bind(this), this.config.storeTimeout, ); } /** * Obtains all updates (messages or any other content) sent or received by specified bot. * Doesn't mark updates as "read". * Very useful for testing `deleteMessage` Telegram API method usage. */ getUpdatesHistory(token: string) { return [...this.storage.botMessages, ...this.storage.userMessages] .filter((item) => item.botToken === token) .sort((a, b) => a.time - b.time); } getUpdates(token: string) { const messages = this.storage.userMessages.filter( (update) => update.botToken === token && !update.isRead, ); // turn messages into updates return messages.map((update) => { // eslint-disable-next-line no-param-reassign update.isRead = true; return TelegramServer.formatUpdate(update); }); } async start() { this.server = shutdown(http.createServer(this.webServer)); await new Promise((resolve, reject) => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.server!.listen(this.config.port, this.config.host) .once('listening', resolve) .once('error', reject); }); debugServer( `Telegram API server is up on port ${this.config.port} in ${this.webServer.settings.env} mode`, ); this.started = true; this.cleanUpDaemon(); } removeUserMessage(updateId: number) { this.storage.userMessages = this.storage.userMessages.filter( (update) => update.updateId !== updateId, ); } removeBotMessage(updateId: number) { this.storage.botMessages = this.storage.botMessages.filter( (update) => update.updateId !== updateId, ); } setWebhook(webhook: WebHook, botToken: string) { this.webhooks[botToken] = webhook; debugServer(`Webhook for bot ${botToken} set to: ${webhook.url}`); } deleteWebhook(botToken: string) { delete this.webhooks[botToken]; debugServer(`Webhook unset for bot ${botToken}`); } /** * Deletes specified message from the storage: sent by bots or by clients. * @returns `true` if the message was deleted successfully. */ deleteMessage(chatId: number, messageId: number) { const isMessageToDelete = ( update: StoredClientUpdate | StoredBotUpdate, ) => { let messageChatId: number; if ('callbackQuery' in update) { messageChatId = update.callbackQuery.message.chat.id; } else if ('chat' in update.message) { messageChatId = update.message.chat.id; } else { messageChatId = Number(update.message.chat_id); } return messageChatId === chatId && update.messageId === messageId; }; const userUpdate = this.storage.userMessages.find(isMessageToDelete); if (userUpdate) { this.removeUserMessage(userUpdate.updateId); return true; } const botUpdate = this.storage.botMessages.find(isMessageToDelete); if (botUpdate) { this.removeBotMessage(botUpdate.updateId); return true; } return false; } async stop() { if (this.server === undefined) { debugServer('Cant stop server - it is not running!'); return false; } this.started = false; if (this.cleanUpDaemonInterval) { clearInterval(this.cleanUpDaemonInterval); } const expressStop = new Promise<void>((resolve) => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.server!.shutdown(() => { resolve(); }); }); debugServer('Stopping server...'); this.storage = { userMessages: [], botMessages: [], }; await expressStop; debugServer('Server shutdown ok'); return true; } private static formatUpdate(update: StoredClientUpdate) { if ('callbackQuery' in update) { return { update_id: update.updateId, callback_query: { id: String(update.callbackId), from: update.callbackQuery.from, message: update.callbackQuery.message, data: update.callbackQuery.data, }, }; } return { update_id: update.updateId, message: { ...update.message, message_id: update.messageId, }, }; } /** * Telegram API docs say that `reply_markup` and `entities` must JSON serialized string * however e.g. Telegraf sends it as an object and the real Telegram API works just fine * with that, so aparently those fields are _sometimes_ a JSON serialized strings. * For testing purposes it is easier to have everything uniformely parsed, thuse we parse them. * @see https://git.io/J1kiM for more info on that topic. * @param message incomming message that can have JSON-serialized strings * @returns the same message but with reply_markdown & entities parsed */ private static normalizeMessage <T extends RawIncommingMessage>(message: T) { if ('reply_markup' in message) { // eslint-disable-next-line no-param-reassign message.reply_markup = typeof message.reply_markup === 'string' ? JSON.parse(message.reply_markup) : message.reply_markup; } if ('entities' in message) { // eslint-disable-next-line no-param-reassign message.entities = typeof message.entities === 'string' ? JSON.parse(message.entities) : message.entities; } return message; } }
the_stack
import { connect } from 'react-redux' import { withRouter } from 'react-router-dom' import { withStyles } from '@material-ui/core/styles' import Button from '@material-ui/core/Button' import Chip from '@material-ui/core/Chip' import Divider from '@material-ui/core/Divider' import Grid from '@material-ui/core/Grid' import Paper from '@material-ui/core/Paper' import PaypalExpressBtn from 'react-paypal-express-checkout' import React, { Component } from 'react' import Table from '@material-ui/core/Table' import TableBody from '@material-ui/core/TableBody' import TableCell from '@material-ui/core/TableCell' import TableHead from '@material-ui/core/TableHead' import TableRow from '@material-ui/core/TableRow' import Typography from '@material-ui/core/Typography' import classNames from 'classnames' import { Order } from 'core/domain/cart' import * as addToCartActions from 'store/actions/addToCartActions' import * as checkoutActions from 'store/actions/checkoutActions' import { IReviewComponentProps } from './IReviewComponentProps' import { IReviewComponentState } from './IReviewComponentState' // - Import API // - Import actions const styles = (theme: any) => ({ listItem: { padding: theme.spacing(1, 0), }, total: { fontWeight: '700', }, title: { marginTop: theme.spacing(2), }, subtitle: { fontSize: 12, fontFamily: '"Montserrat", sans-serif', lineHeight: '150%', color: '#b4b4b4', textTransform: 'capitalize', fontWeight: 700 }, subheading: { fontSize: 12, fontFamily: '"Montserrat", sans-serif', lineHeight: '150%', color: '#2e2e2e', textTransform: 'capitalize', fontWeight: 700 }, subcontent: { fontSize: 12, fontFamily: 'sans-serif', lineHeight: '200%', color: '#6c6c6c' }, row: { '&:nth-of-type(odd)': { backgroundColor: '#f7f7f7' }, }, itemcell: { minWidth: 158, fontSize: 12 }, borderbottom: { borderBottom: 'none' }, itemred: { color: '#f62f5e' }, chip: { margin: theme.spacing.unit, }, head: { fontSize: 12, fontFamily: '"Montserrat", sans-serif', lineHeight: '150%', color: '#b4b4b4', textTransform: 'capitalize' }, table: { fontSize: 12, }, iconButton: { padding: 10, position: 'absolute', right: 0, top: '1.5rem', color: '#000' }, subtotaltitlemargin: { marginRight: '1.5rem' }, subtotalcontentmargin: { marginRight: '2.9rem' }, shippingtitlemargin: { marginRight: '0.5rem' }, shippingcontentmargin: { marginRight: '2.8rem' }, grandtotalcontentmargin: { marginRight: '2.4rem', fontSize: 16, fontFamily: '"Montserrat", sans-serif', lineHeight: '150%', color: '#2e2e2e' }, button: { textTransform: 'capitalize', borderRadius: 30, padding: `${15}px ${60}px`, boxShadow: 'none' }, backbutton: { backgroundColor: '#ffffff', color: '#f62f5e' }, paperbuttons: { marginBottom: theme.spacing(3), backgroundColor: '#f7f7f7', borderTopLeftRadius: 0, borderTopRightRadius: 0, boxShadow: '0px 2px 2px 0px rgba(0,0,0,0.14), 0px 3px 1px -2px rgba(0,0,0,0.12)', padding: theme.spacing(2), [theme.breakpoints.up(600 + theme.spacing(3) * 2)]: { padding: `${24}px ${48}px`, }, position: 'relative', width: '116%', bottom: -72, left: -48 }, }) /** * Create component class */ export class ReviewComponent extends Component<IReviewComponentProps,IReviewComponentState> { static propTypes = { /** * List of users */ } /** * Component constructor * @param {object} props is an object properties of component */ constructor (props: IReviewComponentProps) { super(props) // Defaul state this.state = { subtotalofcart: 0, grandtotalofcart: 0 } // Binding functions to `this` this.handleBack = this.handleBack.bind(this) this.handleNext = this.handleNext.bind(this) this.onSuccess = this.onSuccess.bind(this) this.onCancel = this.onCancel.bind(this) this.onError = this.onError.bind(this) this.settotals = this.settotals.bind(this) this.setgrandtotal = this.setgrandtotal.bind(this) this.reviewproductsList = this.reviewproductsList.bind(this) } /** * Handle backbutton step on change */ handleBack = () => { this.props.update!(0) } /** * Handle backbutton step on change */ handleNext = () => { this.props.update!(2) } reviewproductsList = () => { const {classes,shippingAddress } = this.props const getCartProducts = this.props.getCart var subtotal = 0 var grandtotal = 0 const cartProductsList: any[] = [] if (getCartProducts) { getCartProducts.forEach((cartItem: any, cartId: string) => { cartItem.forEach((row: any, key: any) => { {subtotal = subtotal + (row.get('productQuantity') * row.get('productPrice') )} cartProductsList.push( <TableRow className={classes.row} key={row.get('productId')}> <TableCell scope='row' className={classNames(classes.itemcell, classes.borderbottom)}> {row.get('productName')} </TableCell> <TableCell align='right' className={classes.borderbottom}>{row.get('productQuantity')}</TableCell> <TableCell align='right' className={classNames(classes.itemred, classes.borderbottom)}>{row.get('productPrice')}</TableCell> </TableRow> ) }) }) } if (shippingAddress.get('shippingCost')) { grandtotal = grandtotal + (shippingAddress.get('shippingCost') + subtotal) this.setgrandtotal( grandtotal ) } // this.settotals( subtotal ) return cartProductsList } settotals = (subtotal: any) => { this.setState(prevState => { if (prevState.subtotalofcart === 0) { return { subtotalofcart: subtotal } } else { return null } }) } setgrandtotal = (grandtotal: any) => { this.setState(prevState => { if (prevState.grandtotalofcart === 0 ) { return { grandtotalofcart: grandtotal } } else { return null } }) } onSuccess = (payment: any) => { // Congratulation, it came here means everything's fine! console.log('The payment was succeeded!', payment) const getorderId = this.props.orderId this.props.updateOrder!(getorderId,{ status: 1, comments: 'payment is succeeded', authcode: payment.paymentID, reference: payment }) this.props.update!(3) // You can bind the "payment" object's value to your state or props or whatever here, please see below for sample returned data } onCancel = (data: any) => { // User pressed "cancel" or close Paypal's popup! console.log('The payment was cancelled!', data) // You can bind the "data" object's value to your state or props or whatever here, please see below for sample returned data } onError = (err: any) => { // The main Paypal's script cannot be loaded or somethings block the loading of that script! console.log('Error!', err) // Because the Paypal's main script is loaded asynchronously from "https://www.paypalobjects.com/api/checkout.js" // => sometimes it may take about 0.5 second for everything to get set, or for the button to appear } /** * Reneder component DOM * @return {react element} return the DOM which rendered by component */ render () { let env = 'sandbox' // you can set here to 'production' for production let currency = 'GBP' // or you can set this value from your props or state let total = this.state.grandtotalofcart // same as above, this is the total amount (based on currency) to be paid by using Paypal express checkout // Document on Paypal's currency code: https://developer.paypal.com/docs/classic/api/currency_codes/ const client = { sandbox: 'AW7kNlHYjoTuR3VHL5lWv6FYk-eFouc8wdJ8WrcM9SCbizMlzH6V9hmTzC0Y1Kygj2sEBPG0x38jGgYw', production: 'AYSwvTQ2zG3GOIyqrJyILdhiNm0yaRAyJbc5D78yQ4hzb2UVosjFvM-x9qMlVJPv-UhGTeiMjDrd3zUL', } const { classes,shippingAddress } = this.props let id = 0 function createData( item: any, qty: any, price: any ) { id += 1 return {id, item, qty, price} } return ( <React.Fragment> <Grid container spacing={5}> <Grid item xs={12} sm={8}> <Typography variant='body2' gutterBottom className={classes.subheading}> Order summary </Typography> <Table className={classes.table}> <TableHead className={classes.head}> <TableRow> <TableCell className={classNames(classes.borderbottom, classes.head)}>Item</TableCell> <TableCell align='right' className={classNames(classes.borderbottom, classes.head)}>Qty</TableCell> <TableCell align='right' className={classNames(classes.borderbottom, classes.head)}>Price</TableCell> </TableRow> </TableHead> <TableBody> {this.reviewproductsList()} </TableBody> </Table> </Grid> <Grid item xs={12} sm={4}> <Typography variant='body2' gutterBottom className={classes.subheading}> Delivery </Typography> <br /> <Typography variant='body2' gutterBottom className={classes.subtitle}> Address </Typography> <br /> <Typography className={classes.subcontent} gutterBottom>{shippingAddress.get('address1')}, {shippingAddress.get('city')}, {shippingAddress.get('country')}, {shippingAddress.get('postalCode')}</Typography> <br /> <Typography variant='body2' gutterBottom className={classes.subtitle}> Delivery options </Typography> <br /> <Typography className={classes.subcontent} variant='body2' gutterBottom> {shippingAddress.get('shippingType')} </Typography> </Grid> <Grid item xs={12}> <Divider variant='middle' /> </Grid> <Grid container spacing={0} direction='row'> <Grid item container xs={6} sm={3} direction='column' alignItems='center'> <Chip label='NEWYEAR8%' className={classes.chip} variant='outlined'/> </Grid> <Grid item container xs={6} sm={3} direction='column' alignItems='flex-end'> <Typography variant='body2' gutterBottom className={classNames(classes.subtitle, classes.subtotaltitlemargin)}> Subtotal </Typography> <Typography gutterBottom className={classNames(classes.subcontent, classes.subtotalcontentmargin)}> £{this.state.subtotalofcart} </Typography> </Grid> <Grid item container xs={6} sm={2} direction='column' alignItems='flex-end'> <Typography variant='body2' gutterBottom className={classNames(classes.subtitle, classes.shippingtitlemargin)}> Shipping </Typography> <Typography gutterBottom className={classNames(classes.subcontent, classes.shippingcontentmargin)}> £{shippingAddress.get('shippingCost')} </Typography> </Grid> <Grid item xs={6} sm={2} container direction='column' alignItems='center'> <Typography variant='body2' gutterBottom className={classes.subtitle}> Grandtotal </Typography> <Typography gutterBottom className={classNames(classes.subcontent, classes.grandtotalcontentmargin)}> £{this.state.grandtotalofcart} </Typography> </Grid> </Grid> </Grid> <Paper className={classes.paperbuttons}> <React.Fragment> <Grid container spacing={8}> <Grid item container xs={12} sm={6} direction='row' justify='flex-start' alignItems='center'> <Button onClick={this.handleBack} className={classNames(classes.backbutton, classes.button)} variant='contained' > Back </Button> </Grid> <Grid item xs={12} sm={6} container direction='row' justify='flex-end' alignItems='center' > <PaypalExpressBtn env={env} client={client} currency={currency} total={total} onError={this.onError} onSuccess={this.onSuccess} onCancel={this.onCancel} /> </Grid> </Grid> </React.Fragment> </Paper> </React.Fragment> ) } } /** * Map dispatch to props * @param {func} dispatch is the function to dispatch action to reducers * @param {object} ownProps is the props belong to component * @return {object} props of component */ const mapDispatchToProps = (dispatch: Function, ownProps: IReviewComponentProps) => { return { update: (value: number) => dispatch(checkoutActions.setActiveStep(value)), updateOrder: (orderId: string, order: Order) => dispatch(addToCartActions.dbUpdateOrder(orderId, order)) } } /** * Map state to props * @param {object} state is the obeject from redux store * @param {object} ownProps is the props belong to component * @return {object} props of component */ const mapStateToProps = (state: any, ownProps: IReviewComponentProps) => { const uid = state.getIn(['authorize', 'uid'], 0) const getCart = state.getIn(['addToCart', 'cartProducts']) const orderId = state.getIn(['addToCart', 'order', 'orderId']) return { uid, getCart, orderId } } // - Connect component to redux store export default withRouter<any>(connect(mapStateToProps, mapDispatchToProps)(withStyles(styles as any, { withTheme: true })(ReviewComponent as any) as any)) as typeof ReviewComponent
the_stack
import { InstanceElement, ObjectType, PrimitiveTypes, PrimitiveType, ReferenceExpression, ElemID, ListType, BuiltinTypes, CORE_ANNOTATIONS, MapType, } from '@salto-io/adapter-api' import { extendGeneratedDependencies, FlatDetailedDependency, DetailedDependency } from '../src/dependencies' describe('dependencies', () => { const mockStrType = new PrimitiveType({ elemID: new ElemID('mockAdapter', 'str'), primitive: PrimitiveTypes.STRING, annotations: { testAnno: 'TEST ANNO TYPE' }, path: ['here', 'we', 'go'], }) const mockElem = new ElemID('mockAdapter', 'test') const mockType = new ObjectType({ elemID: mockElem, annotationRefsOrTypes: { testAnno: mockStrType, }, annotations: { testAnno: 'TEST ANNO', }, fields: { ref: { refType: BuiltinTypes.STRING }, str: { refType: BuiltinTypes.STRING, annotations: { testAnno: 'TEST FIELD ANNO' } }, file: { refType: BuiltinTypes.STRING }, bool: { refType: BuiltinTypes.BOOLEAN }, num: { refType: BuiltinTypes.NUMBER }, numArray: { refType: new ListType(BuiltinTypes.NUMBER) }, strArray: { refType: new ListType(BuiltinTypes.STRING) }, numMap: { refType: new MapType(BuiltinTypes.NUMBER) }, strMap: { refType: new MapType(BuiltinTypes.STRING) }, obj: { refType: new ListType(new ObjectType({ elemID: mockElem, fields: { field: { refType: BuiltinTypes.STRING }, otherField: { refType: BuiltinTypes.STRING, }, value: { refType: BuiltinTypes.STRING }, mapOfStringList: { refType: new MapType(new ListType(BuiltinTypes.STRING)) }, innerObj: { refType: new ObjectType({ elemID: mockElem, fields: { name: { refType: BuiltinTypes.STRING }, listOfNames: { refType: new ListType(BuiltinTypes.STRING) }, magical: { refType: new ObjectType({ elemID: mockElem, fields: { deepNumber: { refType: BuiltinTypes.NUMBER }, deepName: { refType: BuiltinTypes.STRING }, }, }), }, }, }), }, }, })), }, }, path: ['this', 'is', 'happening'], }) describe('extendGeneratedDependencies', () => { it('should create the _generated_dependencies annotation if it does not exist', () => { const type = new ObjectType({ elemID: mockElem, annotationRefsOrTypes: { testAnno: mockStrType, }, annotations: { testAnno: 'TEST ANNO', }, fields: { f1: { refType: BuiltinTypes.STRING }, }, }) const inst = new InstanceElement('something', mockType, {}) const reference = new ReferenceExpression(new ElemID('adapter', 'type123')) const flatRefs: FlatDetailedDependency[] = [{ reference, direction: 'input' }] const structuredRefs = [{ reference, occurrences: [{ direction: 'input' }] }] extendGeneratedDependencies(type, flatRefs) expect(type.annotations[CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]).toBeDefined() expect(type.annotations[CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]).toEqual(structuredRefs) extendGeneratedDependencies(inst, flatRefs) expect(inst.annotations[CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]).toBeDefined() expect(inst.annotations[CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]).toEqual(structuredRefs) expect(type.fields.f1.annotations[CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]).toBeUndefined() extendGeneratedDependencies(type.fields.f1, flatRefs) expect(type.fields.f1.annotations[CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]).toBeDefined() expect(type.fields.f1.annotations[CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]).toEqual( structuredRefs ) }) it('should extend the _generated_dependencies annotation if it already exists', () => { const oldRefs = [{ reference: new ReferenceExpression(new ElemID('adapter', 'type123')) }] const type = new ObjectType({ elemID: mockElem, annotationRefsOrTypes: { testAnno: mockStrType, }, annotations: { testAnno: 'TEST ANNO', [CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]: [...oldRefs], }, fields: { f1: { refType: BuiltinTypes.STRING, annotations: { [CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]: [...oldRefs] }, }, }, }) const inst = new InstanceElement( 'something', mockType, {}, undefined, { [CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]: [...oldRefs] }, ) const newRefs: FlatDetailedDependency[] = [ { reference: new ReferenceExpression(new ElemID('adapter', 'type456')) }, ] extendGeneratedDependencies(type, newRefs) expect(type.annotations[CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]).toBeDefined() expect(type.annotations[CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]).toEqual( [...oldRefs, ...newRefs] ) extendGeneratedDependencies(inst, newRefs) expect(inst.annotations[CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]).toBeDefined() expect(inst.annotations[CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]).toEqual( [...oldRefs, ...newRefs] ) expect(type.fields.f1.annotations[CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]).toBeDefined() extendGeneratedDependencies(type.fields.f1, newRefs) expect(type.fields.f1.annotations[CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]).toBeDefined() expect(type.fields.f1.annotations[CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]).toEqual( [...oldRefs, ...newRefs] ) }) it('should do nothing if no new annotations are added', () => { const oldRefs = [{ reference: new ReferenceExpression(new ElemID('adapter', 'type123')) }] const type = new ObjectType({ elemID: mockElem, annotationRefsOrTypes: { testAnno: mockStrType, }, annotations: { testAnno: 'TEST ANNO', [CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]: [...oldRefs], }, fields: { f1: { refType: BuiltinTypes.STRING, annotations: { [CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]: [...oldRefs] }, }, }, }) const inst = new InstanceElement( 'something', mockType, {}, undefined, { [CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]: [...oldRefs] }, ) extendGeneratedDependencies(type, []) expect(type.annotations[CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]).toBeDefined() expect(type.annotations[CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]).toEqual(oldRefs) extendGeneratedDependencies(inst, []) expect(inst.annotations[CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]).toBeDefined() expect(inst.annotations[CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]).toEqual(oldRefs) expect(type.fields.f1.annotations[CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]).toBeDefined() extendGeneratedDependencies(type.fields.f1, []) expect(type.fields.f1.annotations[CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]).toBeDefined() expect(type.fields.f1.annotations[CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]).toEqual(oldRefs) }) describe('annotation structure', () => { let type: ObjectType beforeAll(() => { type = new ObjectType({ elemID: mockElem, annotations: { [CORE_ANNOTATIONS.GENERATED_DEPENDENCIES]: [ { reference: new ReferenceExpression(new ElemID('adapter', 'type123')) }, { reference: new ReferenceExpression(new ElemID('adapter', 'type456')) }, { reference: new ReferenceExpression(new ElemID('adapter', 'type789')), occurrences: [ // intentionally not sorted correctly { direction: 'output' }, { direction: 'input' }, ], }, ], }, }) extendGeneratedDependencies(type, [ { reference: new ReferenceExpression(new ElemID('adapter', 'type456')), location: new ReferenceExpression(mockElem.createNestedID('attr', 'def1')), direction: 'output', }, { reference: new ReferenceExpression(new ElemID('adapter', 'type456')), location: new ReferenceExpression(mockElem.createNestedID('attr', 'def2')), direction: 'input', }, { reference: new ReferenceExpression(new ElemID('adapter', 'type456', 'instance', 'inst456')), location: new ReferenceExpression(mockElem.createNestedID('attr', 'def2')), direction: 'input', }, { reference: new ReferenceExpression(new ElemID('adapter', 'type456', 'instance', 'inst456')), location: new ReferenceExpression(mockElem.createNestedID('attr', 'def2')), direction: 'output', }, { reference: new ReferenceExpression(new ElemID('adapter', 'type456', 'instance', 'inst456')), }, { reference: new ReferenceExpression(new ElemID('adapter', 'type123')) }, { reference: new ReferenceExpression(new ElemID('adapter', 'type456')), location: new ReferenceExpression(mockElem.createNestedID('attr', 'def3')), }, { reference: new ReferenceExpression(new ElemID('adapter', 'type456')), location: new ReferenceExpression(mockElem.createNestedID('attr', 'def2')), }, { reference: new ReferenceExpression(new ElemID('adapter', 'aaa')) }, ]) }) const findRefDeps = (id: ElemID): DetailedDependency => ( type.annotations[CORE_ANNOTATIONS.GENERATED_DEPENDENCIES].find( (e: DetailedDependency) => e.reference.elemID.isEqual(id) ) ) const getOccurrences = ( dep: DetailedDependency ): { direction?: string; location?: string}[] | undefined => ( dep.occurrences?.map(oc => ({ ...oc, location: oc.location?.elemID.getFullName() })) ) it('should have one entry for each reference, sorted by the referenced elem id', () => { expect(type.annotations[CORE_ANNOTATIONS.GENERATED_DEPENDENCIES].map( (e: DetailedDependency) => e.reference.elemID.getFullName() )).toEqual([ 'adapter.aaa', 'adapter.type123', 'adapter.type456', 'adapter.type456.instance.inst456', 'adapter.type789', ]) }) it('should have an empty list of occurrences when no additional details are provided', () => { const type123Refs = findRefDeps(new ElemID('adapter', 'type123')) expect(type123Refs).toBeDefined() expect(type123Refs.occurrences).toBeUndefined() const aaaRefs = findRefDeps(new ElemID('adapter', 'aaa')) expect(aaaRefs).toBeDefined() expect(aaaRefs.occurrences).toBeUndefined() }) it('should keep the existing annotation value when no new details are addded', () => { const type789Refs = findRefDeps(new ElemID('adapter', 'type789')) expect(type789Refs).toBeDefined() expect(type789Refs.occurrences).toBeDefined() expect(getOccurrences(type789Refs)).toEqual([ { direction: 'output' }, { direction: 'input' }, ]) }) it('should omit less-specific occurrences when more detailed ones are provided', () => { const type456Refs = findRefDeps(new ElemID('adapter', 'type456')) expect(type456Refs).toBeDefined() expect(type456Refs.occurrences).toBeDefined() expect(getOccurrences(type456Refs)).toEqual([ { location: mockElem.createNestedID('attr', 'def3').getFullName() }, { location: mockElem.createNestedID('attr', 'def2').getFullName(), direction: 'input' }, { location: mockElem.createNestedID('attr', 'def1').getFullName(), direction: 'output' }, ]) const inst456Refs = findRefDeps(new ElemID('adapter', 'type456', 'instance', 'inst456')) expect(inst456Refs).toBeDefined() expect(inst456Refs.occurrences).toBeDefined() expect(getOccurrences(inst456Refs)).toEqual([ { location: mockElem.createNestedID('attr', 'def2').getFullName(), direction: 'input' }, { location: mockElem.createNestedID('attr', 'def2').getFullName(), direction: 'output' }, ]) }) }) }) })
the_stack
import { Channel } from 'channel/channel' import { ChannelManager } from 'channel/channelmanager' import { ExtendedSocket } from 'extendedsocket' import { Room, RoomReadyStatus, RoomStatus } from 'room/room' import { UserSession } from 'user/usersession' import { ChatMessageType } from 'packets/definitions' import { InRoomPacket, InRoomType } from 'packets/in/room' import { InRoomCountdown } from 'packets/in/room/countdown' import { InRoomNewRequest } from 'packets/in/room/fullrequest' import { InRoomJoinRequest } from 'packets/in/room/joinrequest' import { InRoomSetUserTeamRequest } from 'packets/in/room/setuserteamreq' import { InRoomUpdateSettings } from 'packets/in/room/updatesettings' import { OutChatPacket } from 'packets/out/chat' import { GAME_ROOM_CHANGETEAM_FAILED, GAME_ROOM_COUNTDOWN_FAILED_NOENEMIES, GAME_ROOM_JOIN_FAILED_BAD_PASSWORD, GAME_ROOM_JOIN_FAILED_CLOSED, GAME_ROOM_JOIN_FAILED_FULL } from 'gamestrings' import { OutHostPacket } from 'packets/out/host' export class RoomHandler { /** * called when the user sends a Room packet * @param reqData the packet's data * @param sourceConn the user's socket * @param users the user manager object */ public onRoomRequest(reqData: Buffer, sourceConn: ExtendedSocket): boolean { if (sourceConn.session == null) { console.warn( `connection ${sourceConn.uuid} did a room request without a session` ) return false } const roomPacket: InRoomPacket = new InRoomPacket(reqData) switch (roomPacket.packetType) { case InRoomType.NewRoomRequest: return this.onNewRoomRequest(roomPacket, sourceConn) case InRoomType.JoinRoomRequest: return this.onJoinRoomRequest(roomPacket, sourceConn) case InRoomType.GameStartRequest: return this.onGameStartRequest(sourceConn) case InRoomType.LeaveRoomRequest: return this.onLeaveRoomRequest(sourceConn) case InRoomType.ToggleReadyRequest: return this.onToggleReadyRequest(sourceConn) case InRoomType.UpdateSettings: return this.onRoomUpdateSettings(roomPacket, sourceConn) case InRoomType.OnCloseResultWindow: return this.onCloseResultRequest(sourceConn) case InRoomType.SetUserTeamRequest: return this.onSetTeamRequest(roomPacket, sourceConn) case InRoomType.GameStartCountdownRequest: return this.onGameStartToggleRequest(roomPacket, sourceConn) } console.warn('Unknown room request %i', roomPacket.packetType) return true } /** * returns a channel object by its channel index and channel server index * @param channelIndex the channel's index * @param channelServerIndex the channel's channel server index */ public getChannel( channelIndex: number, channelServerIndex: number ): Channel { return ChannelManager.getServerByIndex( channelServerIndex ).getChannelByIndex(channelIndex) } /** * called when the user requests to create a new room * @param roomPacket the incoming packet * @param sourceConn the packet's source connection * @returns true if successful */ private onNewRoomRequest( roomPacket: InRoomPacket, sourceConn: ExtendedSocket ): boolean { const newRoomReq: InRoomNewRequest = new InRoomNewRequest(roomPacket) const session: UserSession = sourceConn.session // if the user wants to create a new room, let it // this will remove the user from its current room // it should help mitigating the 'ghost room' issue, // where a room has users that aren't in it on the client's side if (session.currentRoom != null) { const curRoom: Room = session.currentRoom console.warn( 'user ID %i tried to create a new room, while in an existing one current room: "%s" (id: %i)', curRoom.id, curRoom.settings.roomName, curRoom.id ) curRoom.removeUser(session.user.id) session.currentRoom = null // return false } const channel: Channel = session.currentChannel if (channel == null) { console.warn( `user ID ${session.user.id} requested a new room, but it isn't in a channel` ) return false } const newRoom: Room = channel.createRoom(session.user.id, sourceConn, { gameModeId: newRoomReq.gameModeId, killLimit: newRoomReq.killLimit, mapId: newRoomReq.mapId, roomName: newRoomReq.roomName, roomPassword: newRoomReq.roomPassword, winLimit: newRoomReq.winLimit }) session.currentRoom = newRoom newRoom.sendJoinNewRoom(session.user.id) newRoom.sendRoomSettingsTo(session.user.id) console.log( `user ID ${session.user.id} created a new room. name: "${newRoom.settings.roomName}" (id: ${newRoom.id})` ) return true } /** * called when the user requests to join an existing room * @param roomPacket the incoming packet * @param sourceConn the packet's source connection * @returns true if successful */ private onJoinRoomRequest( roomPacket: InRoomPacket, sourceConn: ExtendedSocket ): boolean { const joinReq: InRoomJoinRequest = new InRoomJoinRequest(roomPacket) const session: UserSession = sourceConn.session const channel: Channel = session.currentChannel if (channel == null) { console.warn( `user ID ${session.user.id} tried to join a room, but it isn't in a channel` ) return false } const desiredRoom: Room = channel.getRoomById(joinReq.roomId) if (desiredRoom == null) { this.SendUserDialogBox(sourceConn, GAME_ROOM_JOIN_FAILED_CLOSED) console.warn( 'user ID %i tried to join a non existing room. room id: %i', session.user.id, joinReq.roomId ) return false } if (desiredRoom.hasFreeSlots() === false) { this.SendUserDialogBox(sourceConn, GAME_ROOM_JOIN_FAILED_FULL) console.warn( 'user ID %i tried to join a full room. room name "%s" room id: %i', session.user.id, desiredRoom.settings.roomName, desiredRoom.id ) return false } if ( desiredRoom.IsPasswordProtected() === true && desiredRoom.ComparePassword(joinReq.roomPassword) === false ) { this.SendUserDialogBox( sourceConn, GAME_ROOM_JOIN_FAILED_BAD_PASSWORD ) console.warn( 'user ID %i tried to join a password protected room with wrong password "%s", really password: "%s". room name "%s" room id: %i', session.user.id, joinReq.roomPassword, desiredRoom.settings.roomPassword, desiredRoom.settings.roomName, desiredRoom.id ) return false } desiredRoom.addUser(session.user.id, sourceConn) session.currentRoom = desiredRoom desiredRoom.sendJoinNewRoom(session.user.id) desiredRoom.sendRoomSettingsTo(session.user.id) desiredRoom.updateNewPlayerReadyStatus(session.user.id) console.log( 'user id %i joined a room. room name: "%s" room id: %i', session.user.id, desiredRoom.settings.roomName, desiredRoom.id ) return true } /** * called when the user (must be host) requests to start the game * after the countdown is complete * @param sourceConn the source connection * @returns true if successful */ private onGameStartRequest(sourceConn: ExtendedSocket): boolean { const session: UserSession = sourceConn.session const currentRoom: Room = session.currentRoom if (currentRoom == null) { console.warn( `user ID ${session.user.id} tried to start a room's match, although it isn't in any` ) return false } // if started by the host if (session.user.id === currentRoom.host.userId) { currentRoom.hostGameStart() console.debug( 'host ID %i is starting a match in room "%s" (room id: %i)', session.user.id, currentRoom.settings.roomName, currentRoom.id ) return true } else if (currentRoom.getStatus() === RoomStatus.Ingame) { currentRoom.guestGameJoin(session.user.id) console.debug( 'user ID %i is joining a match in room "%s" (room id: %i)', session.user.id, currentRoom.settings.roomName, currentRoom.id ) return true } console.warn( `user ID ${session.user.id} tried to start a room's match, although it isn't the host. room name "${currentRoom.settings.roomName}" room id: ${currentRoom.id}` ) return false } /** * called when the user requests to leave the current room its in * @param sourceConn the source connection * @returns true if successful */ private onLeaveRoomRequest(sourceConn: ExtendedSocket): boolean { const session: UserSession = sourceConn.session const currentRoom: Room = session.currentRoom if (currentRoom == null) { console.warn( `user ID ${session.user.id} tried to leave a room, although it isn't in any` ) return false } if ( currentRoom.isUserReady(session.user.id) && currentRoom.isGlobalCountdownInProgress() ) { return false } currentRoom.removeUser(session.user.id) session.currentRoom = null console.log( 'user ID %i left room "%s" (room id: %i)', session.user.id, currentRoom.settings.roomName, currentRoom.id ) ChannelManager.sendRoomListTo(sourceConn, session.currentChannel) return true } /** * called when the user requests to toggle ready status * @param sourceConn the source connection * @returns true if successful */ private onToggleReadyRequest(sourceConn: ExtendedSocket): boolean { const session: UserSession = sourceConn.session const currentRoom: Room = session.currentRoom if (currentRoom == null) { console.warn( `user ID ${session.user.id} tried toggle ready status, although it isn't in any room` ) return false } const readyStatus: RoomReadyStatus = currentRoom.toggleUserReadyStatus( session.user.id ) if (readyStatus == null) { console.warn( `failed to set user ID ${session.user.id}'s ready status` ) return false } // inform every user in the room of the changes currentRoom.broadcastNewUserReadyStatus(session.user.id) if (readyStatus === RoomReadyStatus.Ready) { console.log( 'user ID %i readied in room "%s" (id %i)', session.user.id, currentRoom.settings.roomName, currentRoom.id ) } else if (readyStatus === RoomReadyStatus.NotReady) { console.log( 'user ID %i unreadied in room "%s" (id %i)', session.user.id, currentRoom.settings.roomName, currentRoom.id ) } else { console.log( 'user ID %i did something with ready status. status: %i room ""%s"" (id %i)', session.user.id, readyStatus, currentRoom.settings.roomName, currentRoom.id ) } return true } /** * called when the user requests to update its current room settings * @param roomPacket the incoming packet * @param sourceConn the packet's source connection * @returns true if successful */ private onRoomUpdateSettings( roomPacket: InRoomPacket, sourceConn: ExtendedSocket ): boolean { const newSettingsReq: InRoomUpdateSettings = new InRoomUpdateSettings( roomPacket ) const session: UserSession = sourceConn.session const currentRoom: Room = session.currentRoom if (currentRoom == null) { console.warn( `user ${session.user.id} tried to update a room's settings without being in one` ) return false } if (session.user.id !== currentRoom.host.userId) { console.warn( `user ID ${session.user.id} tried to update a room's settings, although it isn't the host. name "${currentRoom.settings.roomName}" room id: ${currentRoom.id}`, session.user.id, currentRoom.settings.roomName, currentRoom.id ) return false } if (currentRoom.isGlobalCountdownInProgress()) { console.warn( `user ID ${session.user.id} tried to update a room's settings, although a countdown is in progress. name "${currentRoom.settings.roomName}" room id: ${currentRoom.id}` ) return false } currentRoom.updateSettings(newSettingsReq) console.log( 'host ID %i updated room "%s"\'s settings (room id: %i)', session.user.id, currentRoom.settings.roomName, currentRoom.id ) return true } /** * called when the user requests to update its current room settings * @param sourceConn the source connection * @returns true if successful */ private onCloseResultRequest(sourceConn: ExtendedSocket): boolean { sourceConn.send(OutHostPacket.leaveResultWindow()) console.log( `user ID ${sourceConn.session.user.id} closed game result window` ) return true } /** * called when the user requests to change team * @param roomPacket the incoming packet * @param sourceConn the packet's source connection * @returns true if successful */ private onSetTeamRequest( roomPacket: InRoomPacket, sourceConn: ExtendedSocket ): boolean { const setTeamReq: InRoomSetUserTeamRequest = new InRoomSetUserTeamRequest( roomPacket ) const session: UserSession = sourceConn.session const currentRoom: Room = session.currentRoom if (currentRoom == null) { console.warn( `user ID ${session.user.id} tried change team in a room, although it isn't in any` ) return false } if (currentRoom.isUserReady(session.user.id)) { this.SendUserSystemMsg(sourceConn, GAME_ROOM_CHANGETEAM_FAILED) console.warn( 'user ID %i tried change team in a room, although it\'s ready. room name "%s" room id: %i', session.user.id, currentRoom.settings.roomName, currentRoom.id ) return false } if ( currentRoom.settings.areBotsEnabled && session.user.id !== currentRoom.host.userId ) { console.warn( 'user ID %i tried change team in a room when bot mode is enabled, but its not the host.' + 'room name "%s" room id: %i', session.user.id, currentRoom.settings.roomName, currentRoom.id ) return false } currentRoom.updateUserTeam(session.user.id, setTeamReq.newTeam) console.log( 'user ID %i changed to team %i. room name "%s" room id: %i', session.user.id, setTeamReq.newTeam, currentRoom.settings.roomName, currentRoom.id ) return true } /** * called when the user (must be host) requests to start * counting down until the game starts * @param roomPacket the incoming packet * @param sourceConn the packet's source connection * @returns true if successful */ private onGameStartToggleRequest( roomPacket: InRoomPacket, sourceConn: ExtendedSocket ): boolean { const countdownReq: InRoomCountdown = new InRoomCountdown(roomPacket) const session: UserSession = sourceConn.session const currentRoom: Room = session.currentRoom if (currentRoom == null) { console.warn( `user ID ${session.user.id} tried to toggle a room's game start countdown, although it isn't in any` ) return false } if (session.user.id !== currentRoom.host.userId) { console.warn( `user ID ${session.user.id} tried to toggle a room's game start countdown, although it isn't the host. room name "${currentRoom.settings.roomName}" room id: ${currentRoom.id}` ) return false } const shouldCountdown: boolean = countdownReq.shouldCountdown() const count: number = countdownReq.count if (currentRoom.canStartGame() === false) { this.SendUserSystemMsg( sourceConn, GAME_ROOM_COUNTDOWN_FAILED_NOENEMIES ) console.warn( `user ID ${session.user.id} tried to toggle a room's game start countdown, although it can't start. room name "${currentRoom.settings.roomName}" room id: ${currentRoom.id}` ) return false } if (shouldCountdown) { currentRoom.progressCountdown(count) console.log( 'room "%s"\'s (id %i) countdown is at %i (host says it\'s at %i)', currentRoom.settings.roomName, currentRoom.id, currentRoom.getCountdown(), count ) } else { currentRoom.stopCountdown() console.log( 'user ID %i canceled room "%s"\'s (id %i) countdown', session.user.id, currentRoom.settings.roomName, currentRoom.id ) } currentRoom.broadcastCountdown(shouldCountdown) return true } private SendUserDialogBox(userConn: ExtendedSocket, msg: string) { const sysDialog: OutChatPacket = OutChatPacket.systemMessage( msg, ChatMessageType.DialogBox ) userConn.send(sysDialog) } private SendUserSystemMsg(userConn: ExtendedSocket, msg: string) { const sysDialog: OutChatPacket = OutChatPacket.systemMessage( msg, ChatMessageType.System ) userConn.send(sysDialog) } }
the_stack
import { fsSyncer } from 'fs-syncer'; import { UmzugCLI } from '../src/cli'; import path = require('path'); import fs = require('fs'); import childProcess = require('child_process'); import { Umzug } from '../src'; import del = require('del'); import { expectTypeOf } from 'expect-type'; describe('cli from instance', () => { jest.spyOn(console, 'log').mockImplementation(() => {}); const syncer = fsSyncer(path.join(__dirname, 'generated/cli/from-instance'), { 'umzug.js': ` const { Umzug, JSONStorage } = require(${JSON.stringify(require.resolve('../src'))}) exports.default = new Umzug({ migrations: { glob: ['migrations/*.js', { cwd: __dirname }] }, storage: new JSONStorage({path: __dirname + '/storage.json'}), }) `, 'storage.json': '[]', migrations: { 'm1.js': `exports.up = exports.down = async params => console.log(params)`, 'm2.js': `exports.up = exports.down = async params => console.log(params)`, 'm3.js': `exports.up = exports.down = async params => console.log(params)`, }, }); syncer.sync(); const uzmugPath = path.join(syncer.baseDir, 'umzug.js'); // eslint-disable-next-line @typescript-eslint/no-var-requires const umzug: Umzug<{}> = require(uzmugPath).default; test('cli', async () => { /** run the cli with the specified args, then return the executed migration names */ const runCli = async (argv: string[]) => { await new UmzugCLI(umzug).executeWithoutErrorHandling(argv); return (await umzug.executed()).map(e => e.name); }; await expect(runCli(['up'])).resolves.toEqual(['m1.js', 'm2.js', 'm3.js']); await expect(runCli(['down'])).resolves.toEqual(['m1.js', 'm2.js']); await expect(runCli(['down', '--to', '0'])).resolves.toEqual([]); await expect(runCli(['up', '--to', 'm2.js'])).resolves.toEqual(['m1.js', 'm2.js']); await expect(runCli(['down', '--to', '0'])).resolves.toEqual([]); await expect(runCli(['up', '--step', '2'])).resolves.toEqual(['m1.js', 'm2.js']); await expect(runCli(['down', '--step', '2'])).resolves.toEqual([]); await expect(runCli(['up', '--name', 'm1.js', '--to', 'm2.js'])).rejects.toThrowError( /Can't specify 'to' and 'name' together/ ); await expect(runCli(['up', '--to', 'm2.js', '--step', '2'])).rejects.toThrowError( /Can't specify 'to' and 'step' together/ ); await expect(runCli(['up', '--step', '2', '--name', 'm1.js'])).rejects.toThrowError( /Can't specify 'step' and 'name' together/ ); await expect(runCli(['up', '--name', 'm1.js', '--name', 'm3.js'])).resolves.toEqual(['m1.js', 'm3.js']); await expect(runCli(['down', '--name', 'm1.js'])).resolves.toEqual(['m3.js']); await expect(runCli(['up', '--name', 'm3.js'])).rejects.toThrowError( /Couldn't find migration to apply with name "m3.js"/ ); await expect(runCli(['up', '--rerun', 'ALLOW'])).rejects.toThrowError(/Can't specify 'rerun' without 'name'/); await expect(runCli(['up', '--name', 'm3.js', '--rerun', 'THROW'])).rejects.toThrowError( /Couldn't find migration to apply with name "m3.js"/ ); await expect(runCli(['up', '--name', 'm3.js', '--rerun', 'ALLOW'])).resolves.toEqual(['m3.js']); }); }); describe('run as cli', () => { jest.spyOn(console, 'log').mockImplementation(() => {}); const syncer = fsSyncer(path.join(__dirname, 'generated/cli/run-as-cli'), { 'umzug.js': ` const { Umzug, JSONStorage } = require(${JSON.stringify(require.resolve('..'))}) const umzug = new Umzug({ migrations: { glob: ['migrations/*.js', { cwd: __dirname }] }, storage: new JSONStorage({path: __dirname + '/storage.json'}), }) if (require.main === module) { umzug.runAsCLI() } `, 'notumzug.js': `exports.default = 1234`, 'storage.json': '[]', migrations: { 'm1.js': `exports.up = exports.down = async params => console.log(params)`, 'm2.js': `exports.up = exports.down = async params => console.log(params)`, 'm3.js': `exports.up = exports.down = async params => console.log(params)`, }, }); syncer.sync(); const uzmugPath = path.join(syncer.baseDir, 'umzug.js'); test('run as cli', async () => { // note: this test requires the library to have been built since it's spawning a sub-process which doesn't transform typescript via jest. childProcess.execSync(['node', uzmugPath, 'up'].join(' ')); // await require(uzmugPath).run(); // eslint-disable-next-line @typescript-eslint/no-var-requires expect(require(path.join(syncer.baseDir, 'storage.json'))).toEqual(['m1.js', 'm2.js', 'm3.js']); }); }); describe('list migrations', () => { const mockLog = jest.spyOn(console, 'log').mockImplementation(() => {}); const syncer = fsSyncer(path.join(__dirname, 'generated/cli/list'), { 'umzug.js': ` const { Umzug, JSONStorage } = require(${JSON.stringify(require.resolve('../src'))}) exports.default = new Umzug({ migrations: { glob: ['migrations/*.js', { cwd: __dirname }] }, storage: new JSONStorage({path: __dirname + '/storage.json'}), }) `, 'notumzug.js': `exports.default = 1234`, 'storage.json': '[]', migrations: { 'm1.js': `exports.up = exports.down = async () => {}`, 'm2.js': `exports.up = exports.down = async () => {}`, 'm3.js': `exports.up = exports.down = async () => {}`, }, }); syncer.sync(); const uzmugPath = path.join(syncer.baseDir, 'umzug.js'); // eslint-disable-next-line @typescript-eslint/no-var-requires const umzug: Umzug<{}> = require(uzmugPath).default; test('pending and executed', async () => { /** clear console log calls, run the cli, then return new console log calls */ const runCLI = async (argv: string[]) => { mockLog.mockClear(); await umzug.runAsCLI(argv); // json output includes full paths, which might use windows separators. get rid of cwd and normalise separators. return mockLog.mock.calls[0][0] .split(JSON.stringify(process.cwd()).slice(1, -1)) .join('<cwd>') .split(JSON.stringify('\\').slice(1, -1)) .join('/'); }; await expect(runCLI(['pending'])).resolves.toMatchInlineSnapshot(` "m1.js m2.js m3.js" `); await expect(runCLI(['executed'])).resolves.toMatchInlineSnapshot(`""`); await umzug.up(); await expect(runCLI(['pending'])).resolves.toMatchInlineSnapshot(`""`); await expect(runCLI(['executed'])).resolves.toMatchInlineSnapshot(` "m1.js m2.js m3.js" `); await expect(runCLI(['executed', '--json'])).resolves.toMatchInlineSnapshot(` "[ { \\"name\\": \\"m1.js\\", \\"path\\": \\"<cwd>/test/generated/cli/list/migrations/m1.js\\" }, { \\"name\\": \\"m2.js\\", \\"path\\": \\"<cwd>/test/generated/cli/list/migrations/m2.js\\" }, { \\"name\\": \\"m3.js\\", \\"path\\": \\"<cwd>/test/generated/cli/list/migrations/m3.js\\" } ]" `); }); }); describe('create migration file', () => { jest.spyOn(console, 'log').mockImplementation(() => {}); // prettier-ignore beforeEach(() => { const dates = [...Array.from({length: 100})].map((_, i) => new Date(new Date('2000').getTime() + (1000 * 60 * 60 * 24 * i)).toISOString()); jest.spyOn(Date.prototype, 'toISOString').mockImplementation(() => dates.shift()!); }); test('create', async () => { const syncer = fsSyncer(path.join(__dirname, 'generated/cli/create'), { 'umzug.js': ` const { Umzug, JSONStorage } = require(${JSON.stringify(require.resolve('../src'))}) exports.default = new Umzug({ migrations: { glob: ['migrations/*.{js,ts,cjs,mjs,sql}', { cwd: __dirname }], resolve: params => ({ ...params, up: async () => {}, down: async () => {} }), }, storage: new JSONStorage({path: __dirname + '/storage.json'}), }) `, 'storage.json': '[]', migrations: {}, }); syncer.sync(); del.sync(path.join(syncer.baseDir, 'migrations/')); const uzmugPath = path.join(syncer.baseDir, 'umzug.js'); // eslint-disable-next-line @typescript-eslint/no-var-requires const umzug: Umzug<{}> = require(uzmugPath).default; /** run the cli with the specified args, then return the *new* migration files on disk */ const runCLI = async (argv: string[]) => { const migrationsBefore = (syncer.read() as Record<string, any>).migrations; await new UmzugCLI(umzug).executeWithoutErrorHandling(argv); const migrationsAfter = (syncer.read() as Record<string, any>).migrations; // eslint-disable-next-line @typescript-eslint/no-dynamic-delete Object.keys(migrationsBefore || {}).forEach(k => delete migrationsAfter[k]); return migrationsAfter; }; await expect(runCLI(['create', '--name', 'm1.js'])).rejects.toThrowErrorMatchingInlineSnapshot( `"Couldn't infer a directory to generate migration file in. Pass --folder explicitly"` ); // a folder must be specified for the first migration await expect(runCLI(['create', '--name', 'm1.js', '--folder', path.join(syncer.baseDir, 'migrations')])).resolves .toMatchInlineSnapshot(` Object { "2000.01.02T00.00.00.m1.js": "/** @type {import('umzug').MigrationFn<any>} */ exports.up = async params => {}; /** @type {import('umzug').MigrationFn<any>} */ exports.down = async params => {}; ", } `); // for the second migration, the program should guess it's supposed to live next to the previous one. await expect(runCLI(['create', '--name', 'm2.ts'])).resolves.toMatchInlineSnapshot(` Object { "2000.01.03T00.00.00.m2.ts": "import { MigrationFn } from 'umzug'; export const up: MigrationFn = params => {}; export const down: MigrationFn = params => {}; ", } `); expect(fs.existsSync(path.join(syncer.baseDir, 'migrations/down'))).toBe(false); await expect(runCLI(['create', '--name', 'm3.sql'])).resolves.toMatchInlineSnapshot(` Object { "2000.01.04T00.00.00.m3.sql": "-- up migration ", "down": Object { "2000.01.04T00.00.00.m3.sql": "-- down migration ", }, } `); await expect(runCLI(['create', '--name', 'm4.txt'])).rejects.toThrowErrorMatchingInlineSnapshot( `"Extension .txt not allowed. Allowed extensions are .js, .cjs, .mjs, .ts, .sql. See help for --allow-extension to avoid this error."` ); await expect(runCLI(['create', '--name', 'm4.txt', '--allow-extension', '.txt'])).rejects.toThrowError( /Expected .*2000.01.06T00.00.00.m4.txt to be a pending migration but it wasn't! You should investigate this./ ); await expect(runCLI(['create', '--name', 'm4.txt', '--allow-extension', '.txt', '--skip-verify'])).resolves .toMatchInlineSnapshot(` Object { "2000.01.07T00.00.00.m4.txt": "", } `); await expect(runCLI(['create', '--name', 'm5.cjs', '--prefix', 'DATE'])).resolves.toMatchInlineSnapshot(` Object { "2000.01.08.m5.cjs": "/** @type {import('umzug').MigrationFn<any>} */ exports.up = async params => {}; /** @type {import('umzug').MigrationFn<any>} */ exports.down = async params => {}; ", } `); // this will fail because we're creating "000.m6.js" with no prefix. This results in an unexpected alphabetical order. await expect( runCLI(['create', '--name', '000.m6.js', '--prefix', 'NONE']) ).rejects.toThrowErrorMatchingInlineSnapshot( `"Can't create 000.m6.js, since it's unclear if it should run before or after existing migration 2000.01.02T00.00.00.m1.js. Use --allow-confusing-ordering to bypass this error."` ); // Explicitly allow the weird alphabetical ordering. await expect(runCLI(['create', '--name', '000.m6.mjs', '--prefix', 'NONE', '--allow-confusing-ordering'])).resolves .toMatchInlineSnapshot(` Object { "000.m6.mjs": "/** @type {import('umzug').MigrationFn<any>} */ export const up = async params => {}; /** @type {import('umzug').MigrationFn<any>} */ export const down = async params => {}; ", } `); }); test('create with custom template', async () => { const syncer = fsSyncer(path.join(__dirname, 'generated/cli/create-custom-template'), { 'umzug.js': ` const { Umzug, JSONStorage } = require(${JSON.stringify(require.resolve('../src'))}) const path = require('path') exports.default = new Umzug({ migrations: { glob: ['migrations/*.{js,ts,sql}', { cwd: __dirname }], resolve: (params) => ({ ...params, up: async () => {}, down: async () => {} }), }, storage: new JSONStorage({path: __dirname + '/storage.json'}), create: { template: filepath => { const downpath = path.join(path.dirname(filepath), 'down', path.basename(filepath)) return [ [filepath, '-- custom up template'], [downpath, '-- custom down template'] ] } } }) `, 'storage.json': '[]', migrations: {}, }); syncer.sync(); del.sync(path.join(syncer.baseDir, 'migrations/')); const uzmugPath = path.join(syncer.baseDir, 'umzug.js'); // eslint-disable-next-line @typescript-eslint/no-var-requires const umzug: Umzug<{}> = require(uzmugPath).default; /** run the cli with the specified args, then return the *new* migration files on disk */ const runCLI = async (argv: string[]) => { const migrationsBefore = (syncer.read() as Record<string, any>).migrations; await new UmzugCLI(umzug).executeWithoutErrorHandling(argv); const migrationsAfter = (syncer.read() as Record<string, any>).migrations; // eslint-disable-next-line @typescript-eslint/no-dynamic-delete Object.keys(migrationsBefore || {}).forEach(k => delete migrationsAfter[k]); return migrationsAfter; }; await expect(runCLI(['create', '--name', 'm1.sql', '--folder', path.join(syncer.baseDir, 'migrations')])).resolves .toMatchInlineSnapshot(` Object { "2000.01.11T00.00.00.m1.sql": "-- custom up template", "down": Object { "2000.01.11T00.00.00.m1.sql": "-- custom down template", }, } `); }); test('create with invalid custom template', async () => { const syncer = fsSyncer(path.join(__dirname, 'generated/cli/create-invalid-template'), { 'umzug.js': ` const { Umzug, JSONStorage } = require(${JSON.stringify(require.resolve('../src'))}) const path = require('path') exports.default = new Umzug({ migrations: { glob: ['migrations/*.{js,ts,sql}', { cwd: __dirname }], resolve: (params) => ({ ...params, up: async () => {}, down: async () => {} }), }, storage: new JSONStorage({path: __dirname + '/storage.json'}), create: { folder: path.join(__dirname, 'migrations'), template: filepath => { return [filepath, '-- custom up template'] // will fail: should be Array<[string, string]>, not [string, string] } } }) `, 'storage.json': '[]', migrations: {}, }); syncer.sync(); del.sync(path.join(syncer.baseDir, 'migrations/')); const uzmugPath = path.join(syncer.baseDir, 'umzug.js'); // eslint-disable-next-line @typescript-eslint/no-var-requires const umzug: Umzug<{}> = require(uzmugPath).default; /** run the cli with the specified args */ const runCLI = async (argv: string[]) => { await new UmzugCLI(umzug).executeWithoutErrorHandling(argv); }; await expect(runCLI(['create', '--name', 'm1.sql'])).rejects.toMatchInlineSnapshot( `[Error: Expected [filepath, content] pair. Check that the file template function returns an array of pairs.]` ); }); }); describe('exported from package', () => { test('cli exported as namespace', () => { expectTypeOf<import('../src').UmzugCLI>().toEqualTypeOf<UmzugCLI>(); }); });
the_stack
import { Component, OnInit, OnDestroy, Inject, AfterViewInit, ViewChild } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA, MatTabGroup, MatTab } from '@angular/material'; import { Subscription } from "rxjs"; import { HmiService } from '../../_services/hmi.service'; import { TranslateService } from '@ngx-translate/core'; import { Utils } from '../../_helpers/utils'; import { Tag, TAG_PREFIX } from '../../_models/device'; @Component({ selector: 'app-topic-property', templateUrl: './topic-property.component.html', styleUrls: ['./topic-property.component.css'] }) export class TopicPropertyComponent implements OnInit, AfterViewInit, OnDestroy { @ViewChild('grptabs') grptabs: MatTabGroup; @ViewChild('tabsub') tabsub: MatTab; @ViewChild('tabpub') tabpub: MatTab; private subscriptionBrowse: Subscription; editMode = false; topicSource = '#'; topicsList = {}; topicContent = []; topicSelectedSubType = 'raw'; discoveryError = ''; discoveryWait = false; discoveryTimer = null; selectedTopic = { name: '', key: '', value: null, subs: null }; topicToAdd = {}; invokeSubscribe = null; invokePublish = null; topicSelectedPubType = 'raw'; publishTopicName: string; publishTopicPath: string; pubPayload = new MqttPayload(); pubPayloadResult = ''; itemType = MqttItemType; itemTag = Utils.getEnumKey(MqttItemType, MqttItemType.tag); itemTimestamp = Utils.getEnumKey(MqttItemType, MqttItemType.timestamp); itemValue = Utils.getEnumKey(MqttItemType, MqttItemType.value); itemStatic = Utils.getEnumKey(MqttItemType, MqttItemType.static); constructor( private hmiService: HmiService, private translateService: TranslateService, public dialogRef: MatDialogRef<TopicPropertyComponent>, @Inject(MAT_DIALOG_DATA) public data: any) { } ngOnInit() { this.subscriptionBrowse = this.hmiService.onDeviceBrowse.subscribe(value => { if (value.result === 'error') { this.discoveryError = value.result; } else if (value.topic) { if (this.topicsList[value.topic]) { this.topicsList[value.topic].value = value.msg; } else { let checked = false; let enabled = true; if (this.data.device.tags[value.topic]) { checked = true; enabled = false; } // key => value this.topicsList[value.topic] = { name: value.topic, content: value.msg, checked: checked, enabled: enabled }; } } }); Object.keys(this.itemType).forEach(key => { this.translateService.get(this.itemType[key]).subscribe((txt: string) => { this.itemType[key] = txt }); }); // check if edit the topic if (this.data.topic) { let tag = <Tag>this.data.topic; if (tag.options) { if (tag.options.subs) { // sure a subscription this.grptabs.selectedIndex = 0; this.tabpub.disabled = true; this.topicSelectedSubType = tag.type; this.editMode = true; this.selectTopic({ name: tag.name, key: tag.address, value: { content: tag.value }, subs: tag.options.subs }); } else { // publish topic this.grptabs.selectedIndex = 1; this.tabsub.disabled = true; this.publishTopicPath = tag.address; this.publishTopicName = tag.name; this.topicSelectedPubType = tag.type; if (tag.options.pubs) { // sure publish this.pubPayload.items = tag.options.pubs; } } } } this.loadSelectedSubTopic(); this.stringifyPublishItem(); } ngAfterViewInit() { } ngOnDestroy() { // this.checkToSave(); try { if (this.subscriptionBrowse) { this.subscriptionBrowse.unsubscribe(); } } catch (e) { } if (this.discoveryTimer) { clearInterval(this.discoveryTimer); } this.discoveryTimer = null; } //#region Subscription onNoClick(): void { this.dialogRef.close(); } onDiscoveryTopics(source) { this.discoveryError = ''; this.discoveryWait = true; this.discoveryTimer = setTimeout(() => { this.discoveryWait = false; }, 10000); this.hmiService.askDeviceBrowse(this.data.device.id, source); } onClearDiscovery() { this.topicsList = {}; this.discoveryError = ''; this.discoveryWait = false; try { if (this.discoveryTimer) { clearInterval(this.discoveryTimer); } } catch { } } selectTopic(topic) { this.selectedTopic = topic; this.loadSelectedSubTopic(); } private loadSelectedSubTopic() { this.topicContent = []; if (this.topicSelectedSubType === 'json') { let obj = JSON.parse(this.selectedTopic.value.content); Object.keys(obj).forEach(key => { let checked = (this.selectedTopic.subs) ? false : true; if (this.selectedTopic.subs && this.selectedTopic.subs.indexOf(key) !== -1) { checked = true; } this.topicContent.push({ key: key, value: obj[key], checked: checked, type: this.topicSelectedSubType }); }); } else if (this.selectedTopic.value && this.selectedTopic.value.content) { this.topicContent = [{ name: this.selectedTopic.name, key: this.selectedTopic.key, value: this.selectedTopic.value.content, checked: true, type: this.topicSelectedSubType }]; } } onSubTopicValChange(topicSelType) { this.loadSelectedSubTopic(); } isTopicSelected(topic) { return (this.selectedTopic === topic.key) ? true : false; } isSubscriptionEdit() { return this.editMode; } isSubscriptionValid() { if (this.topicContent && this.topicContent.length) { let onechecked = false; for (let i = 0; i < this.topicContent.length; i++) { if (this.topicContent[i].checked) { onechecked = true; } } return onechecked; } return false; } onAddToSubscribe() { if (this.topicContent && this.topicContent.length && this.invokeSubscribe) { // let items = []; for (let i = 0; i < this.topicContent.length; i++) { if (this.topicContent[i].checked) { // items.push(this.topicContent[i].key); let tag = new Tag(Utils.getGUID(TAG_PREFIX)); if (this.data.topic) { tag = new Tag(this.data.topic.id); } tag.type = this.topicSelectedSubType; tag.address = this.selectedTopic.key; tag.memaddress = this.topicContent[i].key; tag.options = { subs: this.topicContent.map((tcnt) => { return tcnt.key }) }; if (this.topicContent[i].name) { tag.name = this.topicContent[i].name; } else { tag.name = this.selectedTopic.key; if (tag.type === 'json') { tag.name += '[' + tag.memaddress + ']'; } } this.invokeSubscribe(this.data.topic, [tag]); } } } } //#endregion //#region Publish isPublishTypeToEnable(type: string) { if (type === 'raw' || (this.pubPayload.items && this.pubPayload.items.length)) { return true; } return false; } onAddToPuplish() { if (this.publishTopicPath && this.invokePublish) { let tag = new Tag(Utils.getGUID(TAG_PREFIX)); if (this.data.topic) { tag = new Tag(this.data.topic.id); } tag.name = this.publishTopicName; tag.address = this.publishTopicPath; tag.type = this.topicSelectedPubType; tag.options = { pubs: this.pubPayload.items }; this.invokePublish(this.data.topic, tag); } } onPubTopicValChange(topicSelType) { this.stringifyPublishItem(); } onAddPublishItem() { this.pubPayload.items.push(new MqttPayloadItem()); this.stringifyPublishItem(); } onRemovePublishItem(index: number) { this.pubPayload.items.splice(index, 1); this.stringifyPublishItem(); } onSetPublishItemTag(item: MqttPayloadItem, event: any) { item.value = event.variableId; if (event.variableRaw) { item.name = event.variableRaw.address; } this.stringifyPublishItem(); } onItemTypeChanged(item: MqttPayloadItem) { if (item.type === this.itemTimestamp) { item.value = new Date().toISOString(); } else if (item.type === this.itemStatic) { item.value = ''; } else if (item.type === this.itemValue) { item.name = this.publishTopicPath; } this.stringifyPublishItem(); } /** * Render the payload content */ stringifyPublishItem() { let obj = {}; let row = ''; if (this.pubPayload.items.length) { for (let i = 0; i < this.pubPayload.items.length; i++) { let item: MqttPayloadItem = this.pubPayload.items[i]; let ivalue = item.value; if (item.type === this.itemTimestamp) { ivalue = new Date().toISOString(); } else if (item.type === this.itemTag) { ivalue = `$(${item.name})`; } else if (item.type === this.itemStatic) { ivalue = `${item.value}`; } else if (item.type === this.itemValue) { item.value = this.publishTopicPath; ivalue = `$(${item.value})`; } else{ ivalue = `${item.value}`; } if (this.topicSelectedPubType === 'json') { let keys = item.key.split('.'); let robj = obj; for (let y = 0; y < keys.length; y++) { if (!robj[keys[y]]) { robj[keys[y]] = {}; } if (y >= keys.length - 1) { robj[keys[y]] = ivalue; } robj = robj[keys[y]]; } } else { // payload items in row format if (row) { ivalue = ';' + ivalue; } } row += ivalue; } } else { row = `$(${this.publishTopicPath})`; obj = { '': row }; } if (this.topicSelectedPubType === 'json') { this.pubPayloadResult = JSON.stringify(obj, undefined, 2); } else { this.pubPayloadResult = row; } } isPublishValid() { return (this.publishTopicPath && this.publishTopicPath.length) ? true : false; } //#endregion } export enum MqttItemType { tag = 'device.topic-type-tag', timestamp = 'device.topic-type-timestamp', value = 'device.topic-type-value', static = 'device.topic-type-static', } export class MqttPayload { items: MqttPayloadItem[] = []; } export class MqttPayloadItem { type = Utils.getEnumKey(MqttItemType, MqttItemType.tag); key = ''; value = ''; name; }
the_stack
import { URL_SOUND_LIST_CONVERSATION } from './../../../chat21-core/utils/constants'; import { Component, OnInit, OnDestroy, AfterViewInit, ViewChild, ElementRef, Directive, HostListener, ChangeDetectorRef } from '@angular/core'; import { ActivatedRoute, NavigationEnd, Router } from '@angular/router'; import { ModalController, ToastController, PopoverController, Platform, ActionSheetController, NavController, IonContent, IonTextarea } from '@ionic/angular'; // models import { UserModel } from 'src/chat21-core/models/user'; import { MessageModel } from 'src/chat21-core/models/message'; import { ConversationModel } from 'src/chat21-core/models/conversation'; import { GroupModel } from 'src/chat21-core/models/group'; // services import { ChatManager } from 'src/chat21-core/providers/chat-manager'; import { AppConfigProvider } from '../../services/app-config'; import { CustomTranslateService } from 'src/chat21-core/providers/custom-translate.service'; import { TypingService } from 'src/chat21-core/providers/abstract/typing.service'; import { ConversationHandlerBuilderService } from 'src/chat21-core/providers/abstract/conversation-handler-builder.service'; import { GroupsHandlerService } from 'src/chat21-core/providers/abstract/groups-handler.service'; import { TiledeskAuthService } from 'src/chat21-core/providers/tiledesk/tiledesk-auth.service'; import { ConversationsHandlerService } from 'src/chat21-core/providers/abstract/conversations-handler.service'; import { ArchivedConversationsHandlerService } from 'src/chat21-core/providers/abstract/archivedconversations-handler.service'; import { ConversationHandlerService } from 'src/chat21-core/providers/abstract/conversation-handler.service'; import { ContactsService } from 'src/app/services/contacts/contacts.service'; import { CannedResponsesService } from '../../services/canned-responses/canned-responses.service'; import { compareValues } from '../../../chat21-core/utils/utils'; import { ImageRepoService } from 'src/chat21-core/providers/abstract/image-repo.service'; import { PresenceService } from 'src/chat21-core/providers/abstract/presence.service'; // utils import { TYPE_MSG_TEXT, MESSAGE_TYPE_INFO, MESSAGE_TYPE_MINE, MESSAGE_TYPE_OTHERS } from '../../../chat21-core/utils/constants'; import { checkPlatformIsMobile, checkWindowWidthIsLessThan991px, setConversationAvatar, setChannelType } from '../../../chat21-core/utils/utils'; import { isFirstMessage, isInfo, isMine, messageType } from 'src/chat21-core/utils/utils-message'; // Logger import { LoggerService } from 'src/chat21-core/providers/abstract/logger.service'; import { LoggerInstance } from 'src/chat21-core/providers/logger/loggerInstance'; import { Subject } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; import { TiledeskService } from '../../services/tiledesk/tiledesk.service'; import { NetworkService } from '../../services/network-service/network.service'; @Component({ selector: 'app-conversation-detail', templateUrl: './conversation-detail.page.html', styleUrls: ['./conversation-detail.page.scss'], }) export class ConversationDetailPage implements OnInit, OnDestroy, AfterViewInit { @ViewChild('ionContentChatArea', { static: false }) ionContentChatArea: IonContent; @ViewChild('rowMessageTextArea', { static: false }) rowTextArea: ElementRef; // @ViewChild('info_content', { static: false }) info_content_child : InfoContentComponent; showButtonToBottom = false; // indica lo stato del pulsante per scrollare la chat (showed/hidden) NUM_BADGES = 0; // numero di messaggi non letti COLOR_GREEN = '#24d066'; // colore presence active da spostare nelle costanti COLOR_RED = '#db4437'; // colore presence none da spostare nelle costanti private unsubscribe$: Subject<any> = new Subject<any>(); private subscriptions: Array<any>; public tenant: string; public loggedUser: UserModel; public conversationWith: string; public conversationWithFullname: string; public messages: Array<MessageModel> = []; public groupDetail: GroupModel; public messageSelected: any; public channelType: string; public online: boolean; public lastConnectionDate: string; public showMessageWelcome: boolean; public openInfoConversation = false; public openInfoMessage: boolean; // check is open info message public isMobile = false; public isLessThan991px = false; // nk added public isTyping = false; public nameUserTypingNow: string; public heightMessageTextArea = ''; public translationMap: Map<string, string>; public conversationAvatar: any; public membersConversation: any; public member: UserModel; public urlConversationSupportGroup: any; public isFileSelected: boolean; public showIonContent = false; public conv_type: string; public tagsCanned: any = []; public tagsCannedFilter: any = []; public window: any = window; public styleMap: Map<string, string> = new Map(); MESSAGE_TYPE_INFO = MESSAGE_TYPE_INFO; MESSAGE_TYPE_MINE = MESSAGE_TYPE_MINE; MESSAGE_TYPE_OTHERS = MESSAGE_TYPE_OTHERS; arrowkeyLocation = -1; //SOUND setTimeoutSound: any; audio: any isOpenInfoConversation: boolean; USER_HAS_OPENED_CLOSE_INFO_CONV: boolean = false isHovering: boolean = false; dropEvent: any isMine = isMine; isInfo = isInfo; isFirstMessage = isFirstMessage; messageType = messageType; // info_content_child_enabled: boolean = false private logger: LoggerService = LoggerInstance.getInstance(); public isOnline: boolean = true; public checkInternet: boolean; public msgCount: number /** * Constructor * @param route * @param chatManager * @param actionSheetCtrl * @param platform * @param customTranslateService * @param appConfigProvider * @param modalController * @param typingService * @param tiledeskAuthService * @param conversationsHandlerService * @param archivedConversationsHandlerService * @param conversationHandlerService * @param groupService * @param contactsService * @param conversationHandlerBuilderService * @param linkifyService * @param logger * @param cannedResponsesService * @param imageRepoService * @param presenceService * @param toastController */ constructor( private route: ActivatedRoute, public chatManager: ChatManager, public actionSheetCtrl: ActionSheetController, public platform: Platform, private customTranslateService: CustomTranslateService, public appConfigProvider: AppConfigProvider, public modalController: ModalController, public typingService: TypingService, public tiledeskAuthService: TiledeskAuthService, public conversationsHandlerService: ConversationsHandlerService, public archivedConversationsHandlerService: ArchivedConversationsHandlerService, public conversationHandlerService: ConversationHandlerService, public groupService: GroupsHandlerService, public contactsService: ContactsService, public conversationHandlerBuilderService: ConversationHandlerBuilderService, public cannedResponsesService: CannedResponsesService, public imageRepoService: ImageRepoService, public presenceService: PresenceService, public toastController: ToastController, public tiledeskService: TiledeskService, private networkService: NetworkService ) { // Change list on date change this.route.paramMap.subscribe(params => { this.logger.log('[CONVS-DETAIL] - constructor -> params: ', params); this.conversationWith = params.get('IDConv'); this.conversationWithFullname = params.get('FullNameConv'); this.conv_type = params.get('Convtype'); }); } // ----------------------------------------------------------- // @ Lifehooks // ----------------------------------------------------------- ngOnInit() { // this.logger.log('[CONVS-DETAIL] > ngOnInit - window.location: ', window.location); // this.logger.log('[CONVS-DETAIL] > ngOnInit - fileUploadAccept: ', this.appConfigProvider.getConfig().fileUploadAccept); // const accept_files = this.appConfigProvider.getConfig().fileUploadAccept; // this.logger.log('[CONVS-DETAIL] > ngOnInit - fileUploadAccept typeof accept_files ', typeof accept_files); // const accept_files_array = accept_files.split(',') // this.logger.log('[CONVS-DETAIL] > ngOnInit - fileUploadAccept accept_files_array ', accept_files_array); // this.logger.log('[CONVS-DETAIL] > ngOnInit - fileUploadAccept accept_files_array typeof: ', typeof accept_files_array); // accept_files_array.forEach(accept_file => { // this.logger.log('[CONVS-DETAIL] > ngOnInit - fileUploadAccept accept_file ', accept_file); // const accept_file_segment = accept_file.split('/') // this.logger.log('[CONVS-DETAIL] > ngOnInit - fileUploadAccept accept_file_segment ', accept_file_segment); // if (accept_file_segment[1] === '*') { // } // }); this.watchToConnectionStatus(); } watchToConnectionStatus() { this.networkService.checkInternetFunc().subscribe(isOnline => { this.checkInternet = isOnline // console.log('[CONVS-LIST-PAGE] - watchToConnectionStatus - isOnline', this.checkInternet) // checking internet connection if (this.checkInternet == true) { this.isOnline = true; } else { this.isOnline = false; } }); } ngAfterViewInit() { this.logger.log('[CONVS-DETAIL] > ngAfterViewInit') } ngOnDestroy() { this.logger.log('[CONVS-DETAIL] > ngOnDestroy') } ngOnChanges() { this.logger.log('[CONVS-DETAIL] > ngOnChanges') } ionViewWillEnter() { // this.info_content_child_enabled = true; this.logger.log('[CONVS-DETAIL] TEST > ionViewWillEnter - convId ', this.conversationWith) this.loggedUser = this.tiledeskAuthService.getCurrentUser(); this.logger.log('[CONVS-DETAIL] ionViewWillEnter loggedUser: ', this.loggedUser); this.listnerStart(); } ionViewDidEnter() { this.logger.log('[CONVS-DETAIL] > ionViewDidEnter') // this.info_content_child_enabled = true; } // Unsubscibe when new page transition end ionViewWillLeave() { this.logger.log('[CONVS-DETAIL] > ionViewWillLeave') // this.logger.log('[CONVS-DETAIL] > ionViewWillLeave info_content_child ', this.info_content_child) // if (this.info_content_child) { // this.logger.log('[CONVS-DETAIL] > HERE YES') // this.info_content_child.destroy(); // } // this.logger.log('[CONVS-DETAIL] TEST > ionViewWillLeave info_content_child_enabled ', this.info_content_child_enabled , 'convId ', this.conversationWith) this.unsubescribeAll(); } // reloadTree() { // this.info_content_child_enabled = false; // // now notify angular to check for updates // this.changeDetector.detectChanges(); // // change detection should remove the component now // // then we can enable it again to create a new instance // this.info_content_child_enabled = true; // } private listnerStart() { const that = this; this.chatManager.BSStart.subscribe((data: any) => { this.logger.log('[CONVS-DETAIL] - BSStart data:', data); if (data) { that.initialize(); } }); } // -------------------------------------------------- // @ Inizialize // -------------------------------------------------- initialize() { // this.logger.log('[CONVS-DETAIL] x conversationWith getConversationDetail', this.conversationWith) // this.logger.log('[CONVS-DETAIL] x conversationsHandlerService getConversationDetail', this.conversationsHandlerService) // this.logger.log('[CONVS-DETAIL] x this.conv_type getConversationDetail', this.conv_type) // if (this.conversationWith && this.conversationsHandlerService && this.conv_type === 'active') { // this.conversationsHandlerService.getConversationDetail(this.conversationWith, (conv) => { // this.logger.log('[CONVS-DETAIL] x conversationsHandlerService getConversationDetail', this.conversationWith, conv) // }) // } // else { //get conversation from 'conversations' firebase node // this.archivedConversationsHandlerService.getConversationDetail(this.conversationWith, (conv) => { // this.logger.log('[CONVS-DETAIL] x archivedConversationsHandlerService getConversationDetail', this.conversationWith, conv) // }) // } this.loggedUser = this.tiledeskAuthService.getCurrentUser(); this.logger.log('[CONVS-DETAIL] - initialize -> loggedUser: ', this.loggedUser); this.translations(); // this.conversationSelected = localStorage.getItem('conversationSelected'); this.showButtonToBottom = false; this.showMessageWelcome = false; const appconfig = this.appConfigProvider.getConfig() // this.tenant = appconfig.tenant; this.tenant = appconfig.firebaseConfig.tenant; this.logger.log('[CONVS-DETAIL] - initialize -> firebaseConfig tenant ', this.tenant); this.logger.log('[CONVS-DETAIL] - initialize -> conversationWith: ', this.conversationWith, ' -> conversationWithFullname: ', this.conversationWithFullname); this.subscriptions = []; this.setHeightTextArea(); this.tagsCanned = []; // list of canned this.messages = []; // list messages of conversation this.isFileSelected = false; // indicates if a file has been selected (image to upload) this.openInfoMessage = false; // indicates whether the info message panel is open if (checkPlatformIsMobile()) { this.isMobile = true; // this.openInfoConversation = false; // indica se è aperto il box info conversazione this.logger.log('[CONVS-DETAIL] - initialize -> checkPlatformIsMobile isMobile? ', this.isMobile) } else { this.isMobile = false; this.logger.log('[CONVS-DETAIL] - initialize -> checkPlatformIsMobile isMobile? ', this.isMobile) // this.openInfoConversation = true; } if (this.isMobile === false) { if (checkWindowWidthIsLessThan991px()) { this.logger.log('[CONVS-DETAIL] - initialize -> checkWindowWidthIsLessThan991px ', checkWindowWidthIsLessThan991px()) this.openInfoConversation = false; // indica se è aperto il box info conversazione this.isOpenInfoConversation = false; this.logger.log('[CONVS-DETAIL] - initialize -> openInfoConversation ', this.openInfoConversation, ' -> isOpenInfoConversation ', this.isOpenInfoConversation) } else { this.logger.log('[CONVS-DETAIL] - initialize -> checkWindowWidthIsLessThan991px ', checkWindowWidthIsLessThan991px()) this.openInfoConversation = true; this.isOpenInfoConversation = true; this.logger.log('[CONVS-DETAIL] - initialize -> openInfoConversation ', this.openInfoConversation, ' -> isOpenInfoConversation ', this.isOpenInfoConversation) } } this.online = false; this.lastConnectionDate = ''; // init handler vengono prima delle sottoscrizioni! // this.initConversationsHandler(); // nk if (this.conversationWith) { this.initConversationHandler(); this.initGroupsHandler(); this.initSubscriptions(); } this.addEventsKeyboard(); this.startConversation(); this.updateConversationBadge(); // AGGIORNO STATO DELLA CONVERSAZIONE A 'LETTA' (is_new = false) } returnOpenCloseInfoConversation(openInfoConversation: boolean) { this.logger.log('[CONVS-DETAIL] returnOpenCloseInfoConversation - openInfoConversation ', openInfoConversation); this.resizeTextArea(); this.openInfoMessage = false; this.openInfoConversation = openInfoConversation; this.isOpenInfoConversation = openInfoConversation this.USER_HAS_OPENED_CLOSE_INFO_CONV = true; } @HostListener('window:resize', ['$event']) onResize(event: any) { const newInnerWidth = event.target.innerWidth; if (newInnerWidth < 991) { if (this.USER_HAS_OPENED_CLOSE_INFO_CONV === false) { this.openInfoConversation = false; this.isOpenInfoConversation = false; } } } // -------------------------------------------------------- // translations // translationMap passed to components in the html file // -------------------------------------------------------- public translations() { const keys = [ 'LABEL_AVAILABLE', 'LABEL_NOT_AVAILABLE', 'LABEL_TODAY', 'LABEL_TOMORROW', 'LABEL_TO', 'LABEL_LAST_ACCESS', 'ARRAY_DAYS', 'LABEL_ACTIVE_NOW', 'LABEL_IS_WRITING', 'LABEL_INFO_ADVANCED', 'ID_CONVERSATION', 'UPLOAD_FILE_ERROR', 'LABEL_ENTER_MSG', 'LABEL_ENTER_MSG_SHORT', 'LABEL_ENTER_MSG_SHORTER', 'ONLY_IMAGE_FILES_ARE_ALLOWED_TO_PASTE', 'FAILED_TO_UPLOAD_THE_FORMAT_IS NOT_SUPPORTED', 'NO_INFORMATION_AVAILABLE', 'CONTACT_ID', 'USER_ID' ]; this.translationMap = this.customTranslateService.translateLanguage(keys); this.logger.log('[CONVS-DETAIL] x this.translationMap ', this.translationMap) } // -------------------------------------------------------- // setTranslationMapForConversationHandler // -------------------------------------------------------- private setTranslationMapForConversationHandler(): Map<string, string> { const keys = [ 'INFO_SUPPORT_USER_ADDED_SUBJECT', 'INFO_SUPPORT_USER_ADDED_YOU_VERB', 'INFO_SUPPORT_USER_ADDED_COMPLEMENT', 'INFO_SUPPORT_USER_ADDED_VERB', 'INFO_SUPPORT_CHAT_REOPENED', 'INFO_SUPPORT_CHAT_CLOSED', 'LABEL_TODAY', 'LABEL_TOMORROW', 'LABEL_LAST_ACCESS', 'LABEL_TO', 'ARRAY_DAYS' ]; return this.customTranslateService.translateLanguage(keys); } // ------------------------------------------------------------------------------------- // * retrieving the handler from chatManager // * if it DOESN'T EXIST I create a handler and connect and store it in the chatmanager // * if IT EXISTS I connect // * Upload the messages // * I wait x sec if no messages arrive I display msg wellcome // ------------------------------------------------------------------------------------- initConversationHandler() { const translationMap = this.setTranslationMapForConversationHandler(); this.showMessageWelcome = false; const handler: ConversationHandlerService = this.chatManager.getConversationHandlerByConversationId(this.conversationWith); this.logger.log('[CONVS-DETAIL] - initConversationHandler - handler ', handler, ' conversationWith ', this.conversationWith); if (!handler) { this.conversationHandlerService = this.conversationHandlerBuilderService.build(); this.conversationHandlerService.initialize( this.conversationWith, this.conversationWithFullname, this.loggedUser, this.tenant, translationMap ); this.conversationHandlerService.connect(); this.logger.log('[CONVS-DETAIL] - initConversationHandler - NEW handler - conversationHandlerService', this.conversationHandlerService); this.messages = this.conversationHandlerService.messages; this.logger.log('[CONVS-DETAIL] - initConversationHandler - messages: ', this.messages); this.chatManager.addConversationHandler(this.conversationHandlerService); // // wait 8 second and then display the message if there are no messages const that = this; this.logger.log('[CONVS-DETAIL] - initConversationHandler that.messages ', that.messages); this.logger.log('[CONVS-DETAIL] - initConversationHandler that.messages.length ', that.messages.length); this.msgCount = that.messages.length setTimeout(() => { if (!that.messages || that.messages.length === 0) { this.showIonContent = true; that.showMessageWelcome = true; this.logger.log('[CONVS-DETAIL] - initConversationHandler - showMessageWelcome: ', that.showMessageWelcome); } }, 8000); } else { this.logger.log('[CONVS-DETAIL] - initConversationHandler (else) - conversationHandlerService ', this.conversationHandlerService, ' handler', handler); this.conversationHandlerService = handler; this.messages = this.conversationHandlerService.messages; this.logger.log('[CONVS-DETAIL] - initConversationHandler (else) - this.messages: ', this.messages); this.logger.log('[CONVS-DETAIL] - initConversationHandler (else) - this.showMessageWelcome: ', this.showMessageWelcome); } this.logger.log('[CONVS-DETAIL] - initConversationHandler (else) - message ', this.messages, ' showIonContent', this.showIonContent); } initGroupsHandler() { if (this.conversationWith.startsWith("support-group") || this.conversationWith.startsWith("group-")) { this.groupService.initialize(this.tenant, this.loggedUser.uid) this.logger.log('[CONVS-DETAIL] - initGroupsHandler - tenant', this.tenant, ' loggedUser UID', this.loggedUser.uid); } } private setAttributes(): any { const attributes: any = { client: navigator.userAgent, sourcePage: location.href, }; //TODO: servono ??? if (this.loggedUser && this.loggedUser.email) { attributes.userEmail = this.loggedUser.email } if (this.loggedUser && this.loggedUser.fullname) { attributes.userFullname = this.loggedUser.fullname } return attributes; } // --------------------------------- // startConversation // --------------------------------- startConversation() { this.logger.log('[CONVS-DETAIL] - startConversation conversationWith: ', this.conversationWith); if (this.conversationWith) { this.channelType = setChannelType(this.conversationWith); this.logger.log('[CONVS-DETAIL] - startConversation channelType : ', this.channelType); // this.selectInfoContentTypeComponent(); this.setHeaderContent(); } } setHeaderContent() { // this.logger.log('[CONVS-DETAIL] - setHeaderContent conversationWith', this.conversationWith) // this.logger.log('[CONVS-DETAIL] - setHeaderContent conversationsHandlerService', this.conversationsHandlerService) // this.logger.log('[CONVS-DETAIL] - setHeaderContent conv_type', this.conv_type) if (this.conversationWith && this.conversationsHandlerService && this.conv_type === 'active') { this.logger.log('[CONVS-DETAIL] - setHeaderContent getConversationDetail CALLING') this.conversationsHandlerService.getConversationDetail(this.conversationWith, (conv) => { this.logger.log('[CONVS-DETAIL] - setHeaderContent getConversationDetail (active)', this.conversationWith, conv) this.conversationAvatar = setConversationAvatar( conv.conversation_with, conv.conversation_with_fullname, conv.channel_type ); this.logger.log('[CONVS-DETAIL] - setHeaderContent > conversationAvatar: ', this.conversationAvatar); }) } else { //get conversation from 'conversations' firebase node this.archivedConversationsHandlerService.getConversationDetail(this.conversationWith, (conv) => { this.logger.log('[CONVS-DETAIL] - setHeaderContent getConversationDetail (archived)', this.conversationWith, conv) this.conversationAvatar = setConversationAvatar( conv.conversation_with, conv.conversation_with_fullname, conv.channel_type ); }) } // this.conversationAvatar = setConversationAvatar( // this.conversationWith, // this.conversationWithFullname, // this.channelType // ); // this.logger.log('[CONVS-DETAIL] - setHeaderContent > conversationAvatar: ', this.conversationAvatar); } returnSendMessage(e: any) { this.logger.log('[CONVS-DETAIL] - returnSendMessage event', e, ' - conversationWith', this.conversationWith); this.logger.log('[CONVS-DETAIL] - returnSendMessage event message', e.message); try { let message = ''; if (e.message) { message = e.message; } const type = e.type; const metadata = e.metadata; this.sendMessage(message, type, metadata); } catch (err) { this.logger.error('[CONVS-DETAIL] - returnSendMessage error: ', err); } } /** * SendMessage * @param msg * @param type * @param metadata * @param additional_attributes */ sendMessage(msg: string, type: string, metadata?: any, additional_attributes?: any) { this.logger.log('[CONVS-DETAIL] - SEND MESSAGE - MSG: ', msg); this.logger.log('[CONVS-DETAIL] - SEND MESSAGE - type: ', type); this.logger.log('[CONVS-DETAIL] - SEND MESSAGE - metadata: ', metadata); let fullname = this.loggedUser.uid; if (this.loggedUser.fullname) { fullname = this.loggedUser.fullname; } const g_attributes = this.setAttributes(); // added <any> to resolve the Error occurred during the npm installation: Property 'userFullname' does not exist on type '{}' const attributes = <any>{}; if (g_attributes) { for (const [key, value] of Object.entries(g_attributes)) { attributes[key] = value; } } if (additional_attributes) { for (const [key, value] of Object.entries(additional_attributes)) { attributes[key] = value; } } // || type === 'image' if (type === 'file') { if (msg) { // msg = msg + '<br>' + 'File: ' + metadata.src; msg = `[${metadata.name}](${metadata.src})` + '\n' + msg } else { // msg = 'File: ' + metadata.src; // msg = `<a href=${metadata.src} download> // ${metadata.name} // </a>` // msg = ![file-image-placehoder](./assets/images/file-alt-solid.png) + [${metadata.name}](${metadata.src}) msg = `[${metadata.name}](${metadata.src})` } } // else if (type === 'image') { // if (msg) { // // msg = msg + '<br>' + 'File: ' + metadata.src; // msg = metadata.name + '\n' + msg // } else { // msg = metadata.name // } // } (metadata) ? metadata = metadata : metadata = ''; this.logger.log('[CONVS-DETAIL] - SEND MESSAGE msg: ', msg, ' - messages: ', this.messages, ' - loggedUser: ', this.loggedUser); if (msg && msg.trim() !== '' || type !== TYPE_MSG_TEXT) { this.conversationHandlerService.sendMessage( msg, type, metadata, this.conversationWith, this.conversationWithFullname, this.loggedUser.uid, fullname, this.channelType, attributes ); } } // ---------------------------------------------------------- // InitSubscriptions BS subscriptions // ---------------------------------------------------------- initSubscriptions() { this.logger.log('[CONVS-DETAIL] - initSubscriptions: ', this.subscriptions); const that = this; let subscription: any; let subscriptionKey: string; subscriptionKey = 'BSConversationsChanged'; subscription = this.subscriptions.find(item => item.key === subscriptionKey); if (!subscription) { subscription = this.conversationsHandlerService.conversationChanged.subscribe((data: ConversationModel) => { this.logger.log('[CONVS-DETAIL] subscribe BSConversationsChanged data ', data, ' this.loggedUser.uid:', this.loggedUser.uid); if (data && data.sender !== this.loggedUser.uid) { this.logger.log('[CONVS-DETAIL] subscribe to BSConversationsChange data sender ', data.sender) this.logger.log('[CONVS-DETAIL] subscribe to BSConversationsChange this.loggedUser.uid ', this.loggedUser.uid) this.logger.log('[CONVS-DETAIL] subscribe to BSConversationsChange is_new ', data.is_new) this.logger.log('[CONVS-DETAIL] subscribe to BSConversationsChange showButtonToBottom ', this.showButtonToBottom) // UPDATE THE CONVERSATION TO 'READ' IF IT IS ME WHO WRITES THE LAST MESSAGE OF THE CONVERSATION // AND IF THE POSITION OF THE SCROLL IS AT THE END if (!this.showButtonToBottom && data.is_new) { // ARE AT THE END this.updateConversationBadge() } } }); const subscribe = { key: subscriptionKey, value: subscription }; this.subscriptions.push(subscribe); } subscriptionKey = 'messageAdded'; subscription = this.subscriptions.find(item => item.key === subscriptionKey); if (!subscription) { this.logger.log('[CONVS-DETAIL] subscribe to messageAdded - conversationHandlerService', this.conversationHandlerService); subscription = this.conversationHandlerService.messageAdded.subscribe((msg: any) => { this.logger.log('[CONVS-DETAIL] subscribe to messageAdded - msg ', msg); if (msg) { that.newMessageAdded(msg); } }); const subscribe = { key: subscriptionKey, value: subscription }; this.subscriptions.push(subscribe); } // IS USED ? subscriptionKey = 'messageChanged'; subscription = this.subscriptions.find(item => item.key === subscriptionKey); if (!subscription) { this.logger.log('[CONVS-DETAIL] subscribe to messageChanged'); subscription = this.conversationHandlerService.messageChanged.subscribe((msg: any) => { this.logger.log('[CONVS-DETAIL] subscribe to messageChanged - msg ', msg); }); const subscribe = { key: subscriptionKey, value: subscription }; this.subscriptions.push(subscribe); } subscriptionKey = 'messageRemoved'; subscription = this.subscriptions.find(item => item.key === subscriptionKey); if (!subscription) { this.logger.log('[CONVS-DETAIL] subscribe to messageRemoved'); subscription = this.conversationHandlerService.messageRemoved.subscribe((messageId: any) => { this.logger.log('[CONVS-DETAIL] subscribe to messageRemoved - messageId ', messageId); }); const subscribe = { key: subscriptionKey, value: subscription }; this.subscriptions.push(subscribe); } // subscriptionKey = 'onGroupChange'; // subscription = this.subscriptions.find(item => item.key === subscriptionKey); // if (!subscription) { // subscription = if (this.conversationWith.startsWith("group-")) { this.groupService.onGroupChange(this.conversationWith) .pipe(takeUntil(this.unsubscribe$)) .subscribe((groupDetail: any) => { this.groupDetail = groupDetail; this.logger.log('[CONVS-DETAIL] subscribe to onGroupChange - groupDetail ', this.groupDetail) }, (error) => { this.logger.error('I[CONVS-DETAIL] subscribe to onGroupChange - ERROR ', error); }, () => { this.logger.log('[CONVS-DETAIL] subscribe to onGroupChange /* COMPLETE */'); this.groupDetail = null }); } // const subscribe = { key: subscriptionKey, value: subscription }; // this.subscriptions.push(subscribe); // } } // ------------------------------------------------- // addEventsKeyboard // ------------------------------------------------- addEventsKeyboard() { window.addEventListener('keyboardWillShow', () => { this.logger.log('[CONVS-DETAIL] - Keyboard will Show'); }); window.addEventListener('keyboardDidShow', () => { this.logger.log('[CONVS-DETAIL] - Keyboard is Shown'); }); window.addEventListener('keyboardWillHide', () => { this.logger.log('[CONVS-DETAIL] - Keyboard will Hide'); }); window.addEventListener('keyboardDidHide', () => { this.logger.log('[CONVS-DETAIL] - Keyboard is Hidden'); }); } // ---------------------------------------------------------------- // @ Unsubscribe all subscribed events (called in ionViewWillLeave) // ---------------------------------------------------------------- unsubescribeAll() { this.logger.log('[CONVS-DETAIL] unsubescribeAll 1: ', this.subscriptions); if (this.subscriptions) { this.logger.log('[CONVS-DETAIL] unsubescribeAll 2: ', this.subscriptions); this.subscriptions.forEach(subscription => { subscription.value.unsubscribe(); // vedere come fare l'unsubscribe!!!! }); this.subscriptions = []; // https://www.w3schools.com/jsref/met_element_removeeventlistener.asp window.removeEventListener('keyboardWillShow', null); window.removeEventListener('keyboardDidShow', null); window.removeEventListener('keyboardWillHide', null); window.removeEventListener('keyboardDidHide', null); } this.unsubscribe$.next(); this.unsubscribe$.complete(); // this.conversationHandlerService.dispose(); } /** * newMessageAdded * @param message */ newMessageAdded(message: MessageModel) { if (message) { this.logger.log('[CONVS-DETAIL] - newMessageAdded message ', message); if (message.isSender) { this.scrollBottom(0); } else if (!message.isSender) { if (this.showButtonToBottom) { // NON SONO ALLA FINE this.NUM_BADGES++; } else { //SONO ALLA FINE this.scrollBottom(0); } } } } updateConversationBadge() { if (this.conversationWith && this.conversationsHandlerService && this.conv_type === 'active') { this.conversationsHandlerService.setConversationRead(this.conversationWith) } else if (this.conversationWith && this.archivedConversationsHandlerService && this.conv_type === 'archived') { this.archivedConversationsHandlerService.setConversationRead(this.conversationWith) } } // ----------------------------------------------------------- // OUTPUT-EVENT handler // ----------------------------------------------------------- logScrollStart(event: any) { this.logger.log('[CONVS-DETAIL] logScrollStart: ', event); } logScrolling(event: any) { // EVENTO IONIC-NATIVE: SCATTA SEMPRE, QUINDI DECIDO SE MOSTRARE O MENO IL BADGE this.logger.log('[CONVS-DETAIL] logScrolling: ', event); this.detectBottom() } logScrollEnd(event: any) { this.logger.log('[CONVS-DETAIL] logScrollEnd: ', event); } returnChangeTextArea(e: any) { this.logger.log('[CONVS-DETAIL] returnChangeTextArea event', e); try { let height: number = e.offsetHeight; if (height < 50) { height = 50; } this.heightMessageTextArea = height.toString(); //e.target.scrollHeight + 20; const message = e.msg; this.logger.log('[CONVS-DETAIL] returnChangeTextArea heightMessageTextArea ', this.heightMessageTextArea); this.logger.log('[CONVS-DETAIL] returnChangeTextArea e.detail.value', e.msg); this.logger.log('[CONVS-DETAIL] returnChangeTextArea loggedUser uid:', this.loggedUser.uid); this.logger.log('[CONVS-DETAIL] returnChangeTextArea loggedUser firstname:', this.loggedUser.firstname); this.logger.log('[CONVS-DETAIL] returnChangeTextArea conversationSelected uid:', this.conversationWith); this.logger.log('[CONVS-DETAIL] returnChangeTextArea channelType:', this.channelType); let idCurrentUser = ''; let userFullname = ''; // serve x mantenere la compatibilità con le vecchie chat // if (this.channelType === TYPE_DIRECT) { // userId = this.loggedUser.uid; // } idCurrentUser = this.loggedUser.uid; if (this.loggedUser.firstname && this.loggedUser.firstname !== undefined) { userFullname = this.loggedUser.firstname; } this.typingService.setTyping(this.conversationWith, message, idCurrentUser, userFullname); // ---------------------------------------------------------- // DISPLAY CANNED RESPONSES if message.lastIndexOf("/") // ---------------------------------------------------------- setTimeout(() => { if (this.conversationWith.startsWith("support-group")) { var pos = message.lastIndexOf("/"); this.logger.log("[CONVS-DETAIL] - returnChangeTextArea - canned responses pos of / ", pos); this.logger.log("[CONVS-DETAIL] - returnChangeTextArea - pos:: ", pos); if (pos >= 0) { // if (pos === 0) { // && that.tagsCanned.length > 0 var strSearch = message.substr(pos + 1); this.logger.log("[CONVS-DETAIL] - returnChangeTextArea - canned responses strSearch ", strSearch); this.loadTagsCanned(strSearch, this.conversationWith); } else { this.tagsCannedFilter = []; } } }, 300); // ./ CANNED RESPONSES // } catch (err) { this.logger.error('[CONVS-DETAIL] - returnChangeTextArea - error: ', err); } } // ---------------------------------------------------------- // @ CANNED RESPONSES methods // ---------------------------------------------------------- loadTagsCanned(strSearch, conversationWith) { this.logger.log("[CONVS-DETAIL] - loadTagsCanned strSearch ", strSearch); this.logger.log("[CONVS-DETAIL] - loadTagsCanned groupDetail ", this.groupDetail); this.logger.log("[CONVS-DETAIL] - loadTagsCanned conversationWith ", conversationWith); const conversationWith_segments = conversationWith.split('-'); // Removes the last element of the array if is = to the separator if (conversationWith_segments[conversationWith_segments.length - 1] === '') { conversationWith_segments.pop(); } if (conversationWith_segments.length === 4) { const lastArrayElement = conversationWith_segments[conversationWith_segments.length - 1] this.logger.log('[CONVS-DETAIL] - lastArrayElement ', lastArrayElement); this.logger.log('[CONVS-DETAIL] - lastArrayElement length', lastArrayElement.length); if (lastArrayElement.length !== 32) { conversationWith_segments.pop(); } } this.logger.log("[CONVS-DETAIL] - loadTagsCanned conversationWith_segments ", conversationWith_segments); let projectId = "" if (conversationWith_segments.length === 4) { projectId = conversationWith_segments[2]; this.logger.log("[CONVS-DETAIL] - loadTagsCanned projectId ", projectId); this.getAndShowCannedResponses(strSearch, projectId) } else { this.getProjectIdByConversationWith(strSearch, this.conversationWith) } } getProjectIdByConversationWith(strSearch, conversationWith: string) { const tiledeskToken = this.tiledeskAuthService.getTiledeskToken(); this.tiledeskService.getProjectIdByConvRecipient(tiledeskToken, conversationWith).subscribe(res => { this.logger.log('[CONVS-DETAIL] - loadTagsCanned - GET PROJECTID BY CONV RECIPIENT RES', res); if (res) { const projectId = res.id_project this.logger.log('[CONVS-DETAIL] - loadTagsCanned - GET PROJECTID BY CONV RECIPIENT projectId ', projectId); if (projectId) { this.getAndShowCannedResponses(strSearch, projectId) } } }, (error) => { this.logger.error('[CONVS-DETAIL] - loadTagsCanned - GET PROJECTID BY CONV RECIPIENT - ERROR ', error); }, () => { this.logger.log('[CONVS-DETAIL] - loadTagsCanned - GET PROJECTID BY CONV RECIPIENT * COMPLETE *'); }); } getAndShowCannedResponses(strSearch, projectId) { const tiledeskToken = this.tiledeskAuthService.getTiledeskToken(); this.logger.log('[CONVS-DETAIL] - loadTagsCanned tagsCanned.length', this.tagsCanned.length); //if(this.tagsCanned.length <= 0 ){ this.tagsCanned = []; this.cannedResponsesService.getCannedResponses(tiledeskToken, projectId).subscribe(res => { this.logger.log('[CONVS-DETAIL] - loadTagsCanned getCannedResponses RES', res); this.tagsCanned = res this.showTagsCanned(strSearch); }, (error) => { this.logger.error('[CONVS-DETAIL] - loadTagsCanned getCannedResponses - ERROR ', error); }, () => { this.logger.log('[CONVS-DETAIL] - loadTagsCanned getCannedResponses * COMPLETE *'); }); } showTagsCanned(strSearch) { this.logger.log('[CONVS-DETAIL] - showTagsCanned strSearch ', strSearch); this.tagsCannedFilter = []; var tagsCannedClone = JSON.parse(JSON.stringify(this.tagsCanned)); this.logger.log('[CONVS-DETAIL] - showTagsCanned tagsCannedClone ', tagsCannedClone); //this.logger.log("that.contacts lenght:: ", strSearch); this.tagsCannedFilter = this.filterItems(tagsCannedClone, strSearch); this.logger.log('[CONVS-DETAIL] - showTagsCanned tagsCannedFilter ', this.tagsCannedFilter); this.tagsCannedFilter.sort(compareValues('title', 'asc')); var strReplace = strSearch; if (strSearch.length > 0) { strReplace = "<b class='highlight-search-string'>" + strSearch + "</b>"; } for (var i = 0; i < this.tagsCannedFilter.length; i++) { const textCanned = "<div class='cannedText'>" + this.replacePlaceholderInCanned(this.tagsCannedFilter[i].text) + "</div>"; this.tagsCannedFilter[i].title = "<div class='cannedContent'><div class='cannedTitle'>" + this.tagsCannedFilter[i].title.toString().replace(strSearch, strReplace.trim()) + "</div>" + textCanned + '</div>'; } } filterItems(items, searchTerm) { this.logger.log('[CONVS-DETAIL] filterItems tagsCannedClone ', items, ' searchTerm: ', searchTerm); //this.logger.log("filterItems::: ",searchTerm); return items.filter((item) => { //this.logger.log("filterItems::: ", item.title.toString().toLowerCase()); this.logger.log('[CONVS-DETAIL] filtered tagsCannedClone item ', item); return item.title.toString().toLowerCase().indexOf(searchTerm.toString().toLowerCase()) > -1; }); } replacePlaceholderInCanned(str) { this.logger.log('[CONVS-DETAIL] - replacePlaceholderInCanned str ', str); str = str.replace('$recipient_name', this.conversationWithFullname); if (this.loggedUser && this.loggedUser.fullname) { str = str.replace('$agent_name', this.loggedUser.fullname); } return str; } replaceTagInMessage(canned) { const elTextArea = this.rowTextArea['el']; const textArea = elTextArea.getElementsByTagName('ion-textarea')[0]; this.logger.log("[CONVS-DETAIL] replaceTagInMessage textArea ", textArea); this.logger.log("[CONVS-DETAIL] replaceTagInMessage textArea value", textArea.value) this.arrowkeyLocation = -1 this.tagsCannedFilter = []; this.logger.log("[CONVS-DETAIL] replaceTagInMessage canned text ", canned.text); // // prendo val input // replace text var pos = textArea.value.lastIndexOf("/"); var strSearch = textArea.value.substr(pos); this.logger.log("[CONVS-DETAIL] replaceTagInMessage strSearch ", strSearch); var strTEMP = textArea.value.replace(strSearch, canned.text); strTEMP = this.replacePlaceholderInCanned(strTEMP); // strTEMP = this.replacePlaceholderInCanned(strTEMP); // textArea.value = ''; // that.messageString = strTEMP; textArea.value = strTEMP; setTimeout(() => { textArea.focus(); this.resizeTextArea(); }, 200); } @HostListener('document:keydown', ['$event']) handleKeyboardEvent(event: KeyboardEvent) { // this.logger.log("CONVERSATION-DETAIL handleKeyboardEvent event.key ", event.key); if (this.tagsCannedFilter.length > 0) { if (event.key === 'ArrowDown') { this.arrowkeyLocation++; if (this.arrowkeyLocation === this.tagsCannedFilter.length) { this.arrowkeyLocation-- } // this.replaceTagInMessage(this.tagsCannedFilter[this.arrowkeyLocation]) } else if (event.key === 'ArrowUp') { if (this.arrowkeyLocation > 0) { this.arrowkeyLocation--; } else if (this.arrowkeyLocation < 0) { this.arrowkeyLocation++; } // this.replaceTagInMessage(this.tagsCannedFilter[this.arrowkeyLocation]) } if (event.key === 'Enter') { const canned_selected = this.tagsCannedFilter[this.arrowkeyLocation] if (canned_selected) { this.replaceTagInMessage(canned_selected) } } } } // ---------------------------------------------------------- // ./end CANNED RESPONSES methods // ---------------------------------------------------------- // ---------------------------------------------------------- // @ Rule of sound message // * if I send it -> NO SOUND // * if I'm not in the conversation -> SOUND // * if I'm in the conversation at the bottom of the page -> NO SOUND // * otherwise -> SOUND // ---------------------------------------------------------- soundMessage() { const that = this; this.audio = new Audio(); // this.audio.src = '/assets/sounds/pling.mp3'; this.audio.src = URL_SOUND_LIST_CONVERSATION; this.audio.load(); this.logger.log('[CONVS-DETAIL] soundMessage conversation this.audio', this.audio); clearTimeout(this.setTimeoutSound); this.setTimeoutSound = setTimeout(function () { that.audio.play().then(() => { // Audio is playing. this.logger.log('[CONVS-DETAIL] soundMessag that.audio.src ', that.audio.src); }).catch(error => { that.logger.error(error); }); }, 1000); } returnOnBeforeMessageRender(event) { //this.onBeforeMessageRender.emit(event) } returnOnAfterMessageRender(event) { // this.onAfterMessageRender.emit(event) } returnOnMenuOption(event: boolean) { // this.isMenuShow = event; } returnOnScrollContent(event: boolean) { } returnOnAttachmentButtonClicked(event: any) { this.logger.debug('[CONV-COMP] eventbutton', event) if (!event || !event.target.type) { return; } switch (event.target.type) { case 'url': try { this.openLink(event.target.button); } catch (err) { this.logger.error('[CONV-COMP] url > Error :' + err); } return; case 'action': try { this.actionButton(event.target.button); } catch (err) { this.logger.error('[CONV-COMP] action > Error :' + err); } return false; case 'text': try { const text = event.target.button.value const metadata = { 'button': true }; this.sendMessage(text, TYPE_MSG_TEXT, metadata); } catch (err) { this.logger.error('[CONV-COMP] text > Error :' + err); } default: return; } } onImageRenderedFN(event) { const imageRendered = event; if (this.showButtonToBottom) { this.scrollBottom(0) } } private openLink(event: any) { const link = event.link ? event.link : ''; const target = event.target ? event.target : ''; if (target === 'self' || target === 'parent') { window.open(link, '_parent'); } else { window.open(link, '_blank'); } } private actionButton(event: any) { // console.log(event); const action = event.action ? event.action : ''; const message = event.value ? event.value : ''; const subtype = event.show_reply ? '' : 'info'; const attributes = { action: action, subtype: subtype }; this.sendMessage(message, TYPE_MSG_TEXT, null, attributes); this.logger.debug('[CONV-COMP] > action :'); } addUploadingBubbleEvent(event: boolean) { this.logger.log('[CONVS-DETAIL] addUploadingBubbleEvent event', event); if (event === true) { this.scrollBottom(0); } } onPresentModalScrollToBottom(event: boolean) { this.logger.log('[CONVS-DETAIL] onPresentModalScrollToBottom event', event); if (event === true) { this.scrollBottom(0); } } // -------------- START SCROLL/RESIZE -------------- // /** */ resizeTextArea() { try { const elTextArea = this.rowTextArea['el']; const that = this; setTimeout(() => { const textArea = elTextArea.getElementsByTagName('ion-textarea')[0]; if (textArea) { this.logger.log('[CONVS-DETAIL] resizeTextArea textArea ', textArea); const txtValue = textArea.value; textArea.value = ' '; textArea.value = txtValue; } }, 0); setTimeout(() => { if (elTextArea) { this.logger.log('[CONVS-DETAIL] resizeTextArea elTextArea.offsetHeight ', elTextArea.offsetHeight); that.heightMessageTextArea = elTextArea.offsetHeight; } }, 100); } catch (err) { this.logger.error('[CONVS-DETAIL] resizeTextArea - error: ', err); } } /** * scrollBottom * @param time */ private scrollBottom(time: number) { this.showIonContent = true; if (this.ionContentChatArea) { setTimeout(() => { this.ionContentChatArea.scrollToBottom(time); }, 0); // nota: se elimino il settimeout lo scrollToBottom non viene richiamato!!!!! } } /** * detectBottom */ async detectBottom() { const scrollElement = await this.ionContentChatArea.getScrollElement(); if (scrollElement.scrollTop < scrollElement.scrollHeight - scrollElement.clientHeight) { //NON SONO ALLA FINE --> mostra badge this.showButtonToBottom = true; } else { // SONO ALLA FINE --> non mostrare badge, this.showButtonToBottom = false; } } /** * Scroll to bottom of page after a short delay. * FIREBY BY: click event ScrollToBottom bottom-right icon button */ public actionScrollBottom() { this.logger.log('[CONVS-DETAIL] actionScrollBottom - ionContentChatArea: ', this.ionContentChatArea); // const that = this; this.showButtonToBottom = false; this.updateConversationBadge() this.NUM_BADGES = 0; setTimeout(() => { this.ionContentChatArea.scrollToBottom(0); // this.conversationsHandlerService.readAllMessages.next(this.conversationWith); }, 0); } /** * Scroll to top of the page after a short delay. */ scrollTop() { this.logger.log('[CONVS-DETAIL] scrollTop'); this.ionContentChatArea.scrollToTop(100); } /** */ setHeightTextArea() { try { if (this.rowTextArea) { this.heightMessageTextArea = this.rowTextArea['el'].offsetHeight; this.logger.log('[CONVS-DETAIL] setHeightTextArea - heightMessageTextArea: ', this.heightMessageTextArea); } } catch (e) { this.logger.error('[CONVS-DETAIL] setHeightTextArea - ERROR ', e) // this.heightMessageTextArea = '50'; this.heightMessageTextArea = '57'; // NK edited } } checkAcceptedFile(draggedFileMimeType) { let isAcceptFile = false; this.logger.log('[CONVS-DETAIL] > checkAcceptedFile - fileUploadAccept: ', this.appConfigProvider.getConfig().fileUploadAccept); const accept_files = this.appConfigProvider.getConfig().fileUploadAccept; this.logger.log('[CONVS-DETAIL] > checkAcceptedFile - mimeType: ', draggedFileMimeType); if (accept_files === "*/*") { isAcceptFile = true; return isAcceptFile } else if (accept_files !== "*/*") { this.logger.log('[CONVS-DETAIL] > checkAcceptedFile - fileUploadAccept typeof accept_files ', typeof accept_files); const accept_files_array = accept_files.split(',') this.logger.log('[CONVS-DETAIL] > checkAcceptedFile - fileUploadAccept accept_files_array ', accept_files_array); this.logger.log('[CONVS-DETAIL] > checkAcceptedFile - fileUploadAccept accept_files_array typeof: ', typeof accept_files_array); accept_files_array.forEach(accept_file => { this.logger.log('[CONVS-DETAIL] > checkAcceptedFile - fileUploadAccept accept_file ', accept_file); const accept_file_segment = accept_file.split('/') this.logger.log('[CONVS-DETAIL] > checkAcceptedFile - fileUploadAccept accept_file_segment ', accept_file_segment); if (accept_file_segment[1] === '*') { if (draggedFileMimeType.startsWith(accept_file_segment[0])) { isAcceptFile = true; this.logger.log('[CONVS-DETAIL] > checkAcceptedFile - fileUploadAccept isAcceptFile', isAcceptFile); return isAcceptFile } else { isAcceptFile = false; this.logger.log('[CONVS-DETAIL] > checkAcceptedFile - fileUploadAccept isAcceptFile', isAcceptFile); return isAcceptFile } } else if (accept_file_segment[1] !== '*') { if (draggedFileMimeType === accept_file) { isAcceptFile = true; this.logger.log('[CONVS-DETAIL] > checkAcceptedFile - fileUploadAccept isAcceptFile', isAcceptFile); return isAcceptFile } } return isAcceptFile }); return isAcceptFile } } // ------------------------------------------------------------- // DRAG FILE // ------------------------------------------------------------- // DROP (WHEN THE FILE IS RELEASED ON THE DROP ZONE) drop(ev: any) { ev.preventDefault(); ev.stopPropagation(); this.logger.log('[CONVS-DETAIL] ----> FILE - DROP ev ', ev); const fileList = ev.dataTransfer.files; this.logger.log('[CONVS-DETAIL] ----> FILE - DROP ev.dataTransfer.files ', fileList); this.isHovering = false; this.logger.log('[CONVS-DETAIL] ----> FILE - DROP isHovering ', this.isHovering); if (fileList.length > 0) { const file: File = fileList[0]; this.logger.log('[CONVS-DETAIL] ----> FILE - DROP file ', file); var mimeType = fileList[0].type; this.logger.log('[CONVS-DETAIL] ----> FILE - DROP mimeType files ', mimeType); // if (mimeType.startsWith("image") || mimeType.startsWith("application")) { // this.logger.log('[CONVS-DETAIL] ----> FILE - DROP mimeType files: ', this.appConfigProvider.getConfig().fileUploadAccept); // this.checkAcceptedFile(mimeType); const isAccepted = this.checkAcceptedFile(mimeType); this.logger.log('[CONVS-DETAIL] > checkAcceptedFile - fileUploadAccept isAcceptFile FILE - DROP', isAccepted); if (isAccepted === true) { this.handleDropEvent(ev); } else { this.logger.log('[CONVS-DETAIL] ----> FILE - DROP mimeType files ', mimeType, 'NOT SUPPORTED FILE TYPE'); this.presentToastOnlyImageFilesAreAllowedToDrag() } } } handleDropEvent(ev) { this.logger.log('[CONVS-DETAIL] ----> FILE - HANDLE DROP EVENT ', ev); this.dropEvent = ev } // DRAG OVER (WHEN HOVER OVER ON THE "DROP ZONE") allowDrop(ev: any) { ev.preventDefault(); ev.stopPropagation(); this.logger.log('[CONVS-DETAIL] ----> FILE - (dragover) allowDrop ev ', ev); this.isHovering = true; this.logger.log('[CONVS-DETAIL] ----> FILE - (dragover) allowDrop isHovering ', this.isHovering); } // DRAG LEAVE (WHEN LEAVE FROM THE DROP ZONE) drag(ev: any) { ev.preventDefault(); ev.stopPropagation(); this.logger.log('[CONVS-DETAIL] ----> FILE - (dragleave) drag ev ', ev); this.isHovering = false; this.logger.log('[CONVS-DETAIL] ----> FILE - FILE - (dragleave) drag his.isHovering ', this.isHovering); } async presentToastOnlyImageFilesAreAllowedToDrag() { const toast = await this.toastController.create({ message: this.translationMap.get('FAILED_TO_UPLOAD_THE_FORMAT_IS_NOT_SUPPORTED'), duration: 5000, color: "danger", cssClass: 'toast-custom-class', }); toast.present(); } } // END ALL //
the_stack
import { ArrayTypeName, assert, Assignment, ASTNode, Conditional, ContractDefinition, ContractKind, DataLocation, ElementaryTypeName, ErrorDefinition, EventDefinition, Expression, ExternalReferenceType, FunctionCall, FunctionCallKind, FunctionDefinition, FunctionTypeName, Identifier, IndexAccess, InheritanceSpecifier, Mapping, MemberAccess, ModifierDefinition, ModifierInvocation, ParameterList, Return, SourceUnit, StructDefinition, TupleExpression, TypeName, UnaryOperation, UserDefinedTypeName, VariableDeclaration, VariableDeclarationStatement } from "solc-typed-ast"; import { single, zip, print } from "../util/misc"; import { InstrumentationContext } from "./instrumentation_context"; export type LHS = Expression | VariableDeclaration | [Expression, string]; export type RHS = Expression | [Expression, number]; /** * Given potentially complex assignments involving tuples and function return desugaring, return an * iterable of all the primitive assignments happening between. (i.e. assignments where the LHS is not a tuple) */ function* getAssignmentComponents( lhs: Expression | VariableDeclarationStatement, rhs: Expression ): Iterable<[LHS, RHS]> { if (lhs instanceof TupleExpression || lhs instanceof VariableDeclarationStatement) { let assignedDecls: Array<null | VariableDeclaration | Expression>; if (lhs instanceof TupleExpression) { assignedDecls = lhs.vOriginalComponents; } else { assignedDecls = lhs.assignments.map((declId) => declId === null ? null : (lhs.requiredContext.locate(declId) as VariableDeclaration) ); } if (assignedDecls.length === 1) { if (assignedDecls[0] !== null) { yield* getAssignmentComponents(assignedDecls[0], rhs); } } else if (rhs instanceof TupleExpression) { assert( assignedDecls.length === rhs.vOriginalComponents.length, "Mismatch in declarations: {0} and {1}", assignedDecls, rhs.vOriginalComponents ); for (let i = 0; i < assignedDecls.length; i++) { const lhsComp = assignedDecls[i]; if (lhsComp === null) { continue; } const rhsComp = rhs.vOriginalComponents[i]; // Skip assignments where LHS is omitted assert(rhsComp !== null, "Unexpected null in rhs of {0} in position {1}", rhs, i); yield* getAssignmentComponents(lhsComp, rhsComp); } } else if (rhs instanceof FunctionCall) { for (let i = 0; i < assignedDecls.length; i++) { const lhsComp = assignedDecls[i]; // Skip assignments where LHS is omitted if (lhsComp === null) { continue; } yield [lhsComp, [rhs, i]]; } } else if (rhs instanceof Conditional) { yield* getAssignmentComponents(lhs, rhs.vTrueExpression); yield* getAssignmentComponents(lhs, rhs.vFalseExpression); } else { assert(false, "Unexpected rhs in tuple assignment", rhs); } } else { yield [lhs, rhs]; } } /** * Find all explicit and implicit assignments that occur within `node`. These include: * * 1) Normal assignments - `a = 1` yields [a, 1] * * 2) Tuple assignments - these are broken down into primitive assignments. * E.g. (a,b) = (1,2) yields [[a,1], [b,2]]; * * 3) Tuple assignments with function returns. E.g (a,b) = foo(); yields [[a, * [foo(), 0]], [b, [foo(), 1]]] * * 4) Variable declaration statements. E.g. (uint a = 1) yields [uint a, 1]. * Tuples and function are handled similarly to normal assignments. * * 5) Function calls. The passing of arguments is an implicit assignment. E.g: * ``` * function foo(uint x, uint y) ... * ... * foo(1, 2); * ``` * Yields [[uint x, 1], [uint y, 2]] * * 6) Modifier invocations - handled similarly to function calls * * 7) Function returns - handle similarly to function arguments passing * * 8) Inline state variable initialization/file level constant initailization * * 9) Base constructor calls (using InheritanceSpecifiers) * * Returns a list of [lhs, rhs] tuples. */ export function* getAssignments(node: ASTNode): Iterable<[LHS, RHS]> { /** * Given a list of formal parameters/returns `formals` and actual values that are assigned to them `actuals` * return a list of assignments. This handles several cases: * * 1) Normal function call - e.g. foo(1,2) where foo is defined as foo(uint x, int8 y) returns [[uint x, 1], [int8 y, 2]] * 2) Library function call - e.g. arr.extend(otherArr) where extend is defined in a library as `function extend(uint[] a1, uint[] a2)` returns * [[uint[] a1, arr], [uint[] a2, otherArr]] * 3) Return with a single value - e.g. `return 1;` in a function with `returns (uint RET)` returns [[uint RET, 1]] * 4) Return with tuples - e.g. `return (1,2)` in a function with `returns (uint RET0, RET1)` returns [[uint RET0, 1], [uint RET1, 2]] * * * @param formals * @param actuals * @returns */ const helper = ( formals: VariableDeclaration[], actuals: Expression[] | Expression ): Iterable<[LHS, RHS]> => { if (formals.length === 1) { if (actuals instanceof Array) { return zip(formals, actuals); } return [[formals[0], actuals]]; } if (actuals instanceof Array) { return zip(formals, actuals); } if (actuals instanceof TupleExpression) { assert( actuals.vComponents.length === actuals.vOriginalComponents.length, "Expected tuple to not have placeholders", actuals ); return zip(formals, actuals.vComponents); } if (actuals instanceof FunctionCall) { const callRets: Array<[FunctionCall, number]> = ( actuals.vReferencedDeclaration as FunctionDefinition ).vReturnParameters.vParameters.map<[FunctionCall, number]>((decl, i) => [actuals, i]); return zip(formals, callRets); } assert(false, "Unexpected rhs {0} for lhs {1}", actuals, formals); }; for (const candidate of node.getChildrenBySelector( (n) => n instanceof Assignment || n instanceof VariableDeclarationStatement || n instanceof FunctionCall || n instanceof Return || n instanceof ModifierInvocation || n instanceof VariableDeclaration || n instanceof InheritanceSpecifier )) { if (candidate instanceof Assignment) { yield* getAssignmentComponents(candidate.vLeftHandSide, candidate.vRightHandSide); } else if (candidate instanceof VariableDeclarationStatement) { if (candidate.vInitialValue === undefined) { continue; } const rhs = candidate.vInitialValue; yield* getAssignmentComponents(candidate, rhs); } else if (candidate instanceof FunctionCall || candidate instanceof ModifierInvocation) { // Account for implicit assignments to callee formal parameters. // Handle struct constructors as a special case if ( candidate instanceof FunctionCall && candidate.kind === FunctionCallKind.StructConstructorCall ) { const structDecl = (candidate.vExpression as UserDefinedTypeName) .vReferencedDeclaration as StructDefinition; const fieldNames = candidate.fieldNames !== undefined ? candidate.fieldNames : structDecl.vMembers .filter((decl) => !(decl.vType instanceof Mapping)) .map((decl) => decl.name); assert( fieldNames.length === candidate.vArguments.length, "Expected struct field names to correspond to call arguments" ); for (let i = 0; i < fieldNames.length; i++) { yield [[candidate, fieldNames[i]], candidate.vArguments[i]]; } } // Skip type conversions (handled in findAliasedStateVars) and builtin calls if ( candidate instanceof FunctionCall && (candidate.kind !== FunctionCallKind.FunctionCall || candidate.vFunctionCallType !== ExternalReferenceType.UserDefined) ) { continue; } const decl = candidate instanceof FunctionCall ? candidate.vReferencedDeclaration : candidate.vModifier; assert(decl !== undefined, "Should have a decl since builtins are skipped"); // Compute formal VariableDeclarations let formals: VariableDeclaration[]; if ( decl instanceof FunctionDefinition || decl instanceof EventDefinition || decl instanceof ErrorDefinition || decl instanceof ModifierDefinition ) { // Function-like definitions (functions, events, errors, modifiers) just get the declaraed parameters formals = decl.vParameters.vParameters; } else if (decl instanceof VariableDeclaration) { // For variable definitions we have 2 cases - either its a public state var or a function pointer variable if (decl.stateVariable) { // This case is tricky, as there are no formal parameters in the AST to yield. (the getter is implicitly generated) // Luckily, these implicit assignments don't allow aliasing (as they are external calls). // Furthermore these use sites don't need special instrumentation. // So we allow imprecision here and skip these continue; } else { assert( decl.vType instanceof FunctionTypeName, "Unexpected callee variable without function type", decl.vType ); // The result in this case is not also quite correct. From a dataflow perspective // correct overapproximation would be to should consider // assignments to the formal parameters of all declared functions that match // the variable signature. For scribble's use case (detecting potential aliasing of state vars) this // code is sufficient. formals = decl.vType.vParameterTypes.vParameters; } } else if (decl.vConstructor) { formals = decl.vConstructor.vParameters.vParameters; } else { // Implicit constructor - no arguments formals = []; } const actuals = [...candidate.vArguments]; // When we have a library method bound with `using lib for ...` // need to add the implicit first argument if ( candidate instanceof FunctionCall && decl instanceof FunctionDefinition && decl.parent instanceof ContractDefinition && decl.parent.kind === ContractKind.Library && formals.length === candidate.vArguments.length + 1 ) { assert( candidate.vExpression instanceof MemberAccess, "Unexpected callee in library call", candidate ); actuals.unshift(candidate.vExpression.vExpression); } yield* helper(formals, actuals); } else if (candidate instanceof Return) { const formals = candidate.vFunctionReturnParameters.vParameters; const rhs = candidate.vExpression; if (rhs === undefined) { // @note (dimo) skipping implicit 0-assignment of return vars continue; } yield* helper(formals, rhs); } else if (candidate instanceof VariableDeclaration) { // Handle iniline initializers for state variables and file-level constants if ( (candidate.stateVariable || candidate.parent instanceof SourceUnit) && candidate.vValue !== undefined ) { yield [candidate, candidate.vValue]; } } else if (candidate instanceof InheritanceSpecifier) { const contract = candidate.vBaseType.vReferencedDeclaration; assert( contract instanceof ContractDefinition, "Unexpected base in inheritance specifier", contract ); const formals = contract.vConstructor ? contract.vConstructor.vParameters.vParameters : []; // If there is both an InheritanceSpecifier and a ModifierInvocation at the constructor, // we want to skip the InheritanceSpecifier. if (formals.length !== 0 && candidate.vArguments.length === 0) { continue; } yield* helper(formals, candidate.vArguments); } else { assert(false, "NYI assignment candidate", candidate); } } } /** * Return true IFF the type `t` is aliasable by a storage pointer. */ export function isTypeAliasable(t: TypeName): boolean { return ( t instanceof ArrayTypeName || t instanceof Mapping || (t instanceof UserDefinedTypeName && t.vReferencedDeclaration instanceof StructDefinition) || (t instanceof ElementaryTypeName && (t.name === "string" || t.name === "bytes")) ); } /** * Find all state vars that have been assigned (or an aliasable part of them assigned) to * a storage pointer on the stack. * * @todo (dimo) This code is hacky. To do this cleanly we need proper dataflow analysis. * Its tricky to implement dataflow analysis over an AST. * * Returns a map from variable declarations to ASTNodes, where the node is a possible aliasing * assignment for that state var */ export function findAliasedStateVars(units: SourceUnit[]): Map<VariableDeclaration, ASTNode> { const assignments: Array<[LHS, RHS]> = []; const res = new Map<VariableDeclaration, ASTNode>(); // First collect all assignments for (const unit of units) { assignments.push(...getAssignments(unit)); } /** * Given a potentially complex RHS expression, return the list of * state variable declarations that it may alias */ const gatherRHSVars = (rhs: Expression): VariableDeclaration[] => { if (isStateVarRef(rhs)) { return [rhs.vReferencedDeclaration as VariableDeclaration]; } if (rhs instanceof Identifier) { return []; } if (rhs instanceof MemberAccess) { return gatherRHSVars(rhs.vExpression); } if (rhs instanceof IndexAccess) { return gatherRHSVars(rhs.vBaseExpression); } if (rhs instanceof FunctionCall) { if (rhs.kind === FunctionCallKind.TypeConversion) { return gatherRHSVars(single(rhs.vArguments)); } else { // If the rhs is the result of a function call. no need to // do anything - we will catch any aliasing inside the // callee return []; } } if (rhs instanceof Conditional) { const trueVars = gatherRHSVars(rhs.vTrueExpression); const falseVars = gatherRHSVars(rhs.vFalseExpression); return trueVars.concat(falseVars); } if (rhs instanceof TupleExpression && rhs.vOriginalComponents.length === 1) { return gatherRHSVars(rhs.vOriginalComponents[0] as Expression); } assert(false, `Unexpected RHS element ${print(rhs)} in assignment to state var pointer`); }; for (const [lhs, rhs] of assignments) { // Storage pointers can't be nested in // structs or arrays so the LHS can't be a `MemberAccess` or // `IndexAccess`. if (!(lhs instanceof Identifier || lhs instanceof VariableDeclaration)) { continue; } const lhsDecl = lhs instanceof VariableDeclaration ? lhs : lhs.vReferencedDeclaration; // If LHS is a VariableDeclaration make sure its for a local variable or a function call/return value if ( !( lhsDecl instanceof VariableDeclaration && (lhsDecl.parent instanceof VariableDeclarationStatement || (lhsDecl.parent instanceof ParameterList && (lhsDecl.parent.parent instanceof FunctionDefinition || lhsDecl.parent.parent instanceof ModifierDefinition))) ) ) { continue; } // Dont support old-style `var`s (<0.5.0) assert(lhsDecl.vType !== undefined, "Missing type for declaration", lhsDecl); // Check that the LHS is a pointer to storage if (!(isTypeAliasable(lhsDecl.vType) && lhsDecl.storageLocation === DataLocation.Storage)) { continue; } // If the rhs is an [Expression, number] then its the result of a function call. // No need to do anything - we will catch any aliasing inside the callee if (rhs instanceof Array) { continue; } const varDecls = gatherRHSVars(rhs); for (const decl of varDecls) { const lhsNode = lhs instanceof Array ? lhs[0] : lhs; res.set(decl, lhsNode); } } return res; } /** * Describes the sequence of IndexAccesses and MemberAccesses on a given * expression. */ export type ConcreteDatastructurePath = Array<Expression | string>; export type StateVarUpdateNode = | [Assignment, number[]] | VariableDeclaration | FunctionCall | UnaryOperation; /** * Tuple describing a location in the AST where a SINGLE state variable is modified. Has the following * 4 fields: * * 1) `ASTNode` containing the update. It can be one of the following: * - `[Assignment, number[]]` - an assignment. The LHS can potentiall be a * tuple, in which case the second tuple argument describes the location in the * tuple where the state var reference is (see statevars.spec.ts for examples) * - `VariableDeclaration` - corresponds to an inline initializer at the state var definition site. * - `FunctionCall` - corresponds to `.push(..)` and `.pop()` calls on arrays * - `UnaryOperation` - corresponds to a `delete ...`, `++` or `--` operation * 2) The `VariableDeclaration` of the state var that is being modified. * 3) A `ConcreteDatastructurePath` describing what part of the state var is being modified. (see statevars.spec.ts for examples) * 4) The new value that is being assigned to the state variable/part of the state variable. It can be 3 different types: * - `Expression` - an AST expression that is being directly assigned * - `[Expression, number]` - corresponds to the case where we have an assignment of the form `(x,y,z) = func()`. Describes which * return of the function is being assigned * - undefined - in the cases where we do `.push(..)`, `.pop()`, `delete ...`, * `x++`, `x--` we don't quite have a new value being assigned, so we leave * this undefined. * */ export type StateVarUpdateDesc = [ StateVarUpdateNode, VariableDeclaration, ConcreteDatastructurePath, Expression | [Expression, number] | undefined ]; /** * Given a LHS expression that may be wrapped in `MemberAccess` and * `IndexAccess`-es, unwrap it into a base expression that is either an * `Identifier` or a `MemberAccess` that refers to a local var, argument, * return or state variable and a list describing the `MemberAccess`-es and * `IndexAccess`-es. * * @note there is one exception here: `arr.push() = 10`. But honestly screw it. */ export function decomposeLHS( e: Expression ): [Identifier | MemberAccess, ConcreteDatastructurePath] { const path: ConcreteDatastructurePath = []; const originalExp = e; while (true) { if ( e instanceof MemberAccess && !( e.vReferencedDeclaration instanceof VariableDeclaration && !(e.vReferencedDeclaration.parent instanceof StructDefinition) ) ) { path.unshift(e.memberName); e = e.vExpression; continue; } if (e instanceof IndexAccess) { assert(e.vIndexExpression !== undefined, "Expected index expression to be defined", e); path.unshift(e.vIndexExpression); e = e.vBaseExpression; continue; } if (e instanceof TupleExpression && e.vOriginalComponents.length === 1) { e = e.vOriginalComponents[0] as Expression; continue; } if ( e instanceof FunctionCall && e.vFunctionName === "get_lhs" && e.vReferencedDeclaration instanceof FunctionDefinition && e.vReferencedDeclaration.vScope instanceof ContractDefinition && e.vReferencedDeclaration.vScope.kind === ContractKind.Library ) { assert(e.vArguments.length === 2, "Unexpected args for get_lhs: {0}", e.vArguments); path.unshift(e.vArguments[1]); e = e.vArguments[0]; continue; } break; } if (e instanceof FunctionCall && e.vFunctionName === "push") { throw new Error( `Scribble doesn't support instrumenting assignments where the LHS is a push(). Problematic LHS: ${print( originalExp )}` ); } if (e instanceof Assignment) { throw new Error( `Scribble doesn't support instrumenting assignments where the LHS is an assignment itself. Problematic LHS: ${print( originalExp )}` ); } assert(e instanceof Identifier || e instanceof MemberAccess, "Unexpected LHS", e); return [e, path]; } /** * Return true IFF `node` refers to same state variable */ export function isStateVarRef(node: ASTNode): node is Identifier | MemberAccess { return ( (node instanceof Identifier || node instanceof MemberAccess) && node.vReferencedDeclaration instanceof VariableDeclaration && node.vReferencedDeclaration.stateVariable ); } /** * Given a context `ctx` and the left-hand side of an assignment pair `lhs` (as * returned from `getAssignments`), return true IFF the original assignment from * which `lhs` comes is an call to a custom map library setter function. I.e. * this was an assignment that was instrumented due to a `forall` annotation. */ function isAssignmentCustomMapSet(ctx: InstrumentationContext, lhs: LHS): boolean { if ( !( lhs instanceof VariableDeclaration && lhs.vScope instanceof FunctionDefinition && lhs.vScope.name === "set" && lhs === lhs.vScope.vParameters.vParameters[0] ) ) { return false; } const contract = lhs.vScope.vScope; return ( contract instanceof ContractDefinition && ctx.typesToLibraryMap.isCustomMapLibrary(contract) ); } /** * Given a set of units, find all locations in the AST where state variables are updated directly. * (NOTE: This doesn't find locations where state variables are updated through pointers!!) * * Returns a list of locations descriptions tuples `[node, variable, path, newValue]`. Given the following example: * * ``` * struct Point { * uint x; * uint y; * } * * Point[] points; * ... * points[0].x = 1; * ``` * * We would get `[points[0].x = 1, Point[] points, [0, "x"], 1]`. * Below are the definitions of the tuple elements: * * - `node` is the ASTNode where the update happens. In the above example its the assignment `point[0].x = 1;` * - `variable` is the `VariableDeclaration` for the modified variable. In the above example its the def `Point[] points` * - `path` is an description of what part of a complex state var is changed. In the above example its `[0, "x"]`. Expression * elements of the array refer to indexing, and string elements refer to field lookups in structs. * - `newValue` is the new expression that is being assigned. In the above example its `1`. */ export function findStateVarUpdates( units: SourceUnit[], ctx: InstrumentationContext ): StateVarUpdateDesc[] { const res: StateVarUpdateDesc[] = []; /** * Given some `lhs` expression, return the containing `Assignment`, and build the tuple path * from the `Assignment` to `lhs`. */ const getLHSAssignmentAndPath = (lhs: Expression): [Assignment, number[]] => { const idxPath: number[] = []; while (lhs.parent instanceof TupleExpression) { const idx = lhs.parent.vOriginalComponents.indexOf(lhs); assert( idx !== -1, "Unable to detect LHS index in tuple expression components", lhs, lhs.parent ); idxPath.unshift(idx); lhs = lhs.parent; } const assignment = lhs.parent as ASTNode; assert(assignment instanceof Assignment, "Expected assignment, got {0}", assignment); return [assignment, idxPath]; }; /** * Helper to skip assignment locations where the LHS is not a state variable ref */ const addStateVarUpdateLocDesc = ( node: [Assignment, number[]] | FunctionCall | UnaryOperation, lhs: Expression, rhs: Expression | [Expression, number] | undefined ): void => { const [baseExp, path] = decomposeLHS(lhs); // Skip assignments where the base of the LHS is not a direct reference to a state variable if (!isStateVarRef(baseExp)) { return; } const stateVarDecl = baseExp.vReferencedDeclaration as VariableDeclaration; res.push([node, stateVarDecl, path, rhs]); }; for (const unit of units) { // First find all updates due to assignments for (const [lhs, rhs] of getAssignments(unit)) { // Assignments to struct constructor fields - ignore if (lhs instanceof Array) { continue; } if (isAssignmentCustomMapSet(ctx, lhs)) { assert( rhs instanceof Expression, "Cannot have a tuple as second argument to library.set()" ); const funCall = rhs.parent; assert( funCall instanceof FunctionCall && funCall.vFunctionName === "set" && funCall.vArguments.length === 3 && rhs === funCall.vArguments[0], "RHS parent must be a call to library.set() not {0}", funCall ); const [baseExp, path] = decomposeLHS(funCall.vArguments[0]); // Skip assignments where the base of the LHS is not a direct reference to a state variable if (!isStateVarRef(baseExp)) { continue; } path.push(funCall.vArguments[1]); const stateVarDecl = baseExp.vReferencedDeclaration as VariableDeclaration; res.push([funCall, stateVarDecl, path, funCall.vArguments[2]]); continue; } if (lhs instanceof VariableDeclaration) { // Local variable/function arg/function return - skip if (!lhs.stateVariable) { continue; } assert( rhs instanceof Expression, `RHS cannot be a tuple/function with multiple returns.` ); // State variable inline initializer res.push([lhs, lhs, [], rhs]); continue; } addStateVarUpdateLocDesc(getLHSAssignmentAndPath(lhs), lhs, rhs); } // Find all state var updates due to .push() and pop() calls for (const candidate of unit.getChildrenBySelector<FunctionCall>( (node) => node instanceof FunctionCall && node.vFunctionCallType === ExternalReferenceType.Builtin && (node.vFunctionName === "push" || node.vFunctionName === "pop") )) { addStateVarUpdateLocDesc( candidate, (candidate.vExpression as MemberAccess).vExpression, undefined ); } // Find all state var updates due to unary operations (delete, ++, --) for (const candidate of unit.getChildrenBySelector<UnaryOperation>( (node) => node instanceof UnaryOperation && (node.operator === "delete" || node.operator === "++" || node.operator === "--") )) { addStateVarUpdateLocDesc(candidate, candidate.vSubExpression, undefined); } } return res; }
the_stack
import { InteractionProfile, Device, ActionBinding, Input, InputState, ActionType, Av, InputInfo, ActionSet, ActiveActionSet, Action } from './aardvark'; interface InputCallback { id: number; } interface BooleanCallback extends InputCallback { rising?: () => void; falling?: () => void; } interface FloatCallback extends InputCallback { change: ( oldValue: number, newValue: number ) => void; } interface Vector2Callback extends InputCallback { change: ( oldValue: [ number, number ], newValue: [ number, number ] ) => void; } interface InteractionProfileCallback extends InputCallback { change: ( oldInteractionProfile: string, newInteractionProfile: string ) => void; } interface ActionWithListeners extends Action { leftCallbacks?: (BooleanCallback | FloatCallback | Vector2Callback )[]; rightCallbacks?: (BooleanCallback | FloatCallback | Vector2Callback )[]; suppressLeft?: boolean; suppressRight?: boolean; } /** Helper class to allow registering callbacks for input state changes instead of polling state. */ export class InputProcessor { private inputInfo: InputInfo = { activeActionSets: [], }; private state: InputState; private inputIntervalMs: number; private inputTimer:number; private actionSets: ActionSet[]; private nextCallbackId = 1; private syncInputOverride: ( info: InputInfo ) => InputState; private interactionProfileCallbacks: InteractionProfileCallback[] = []; constructor( actionSets: ActionSet[], inputIntervalMs?: number, syncInputOverride?: ( info: InputInfo ) => InputState ) { this.actionSets = actionSets; this.syncInputOverride = syncInputOverride; this.inputIntervalMs = inputIntervalMs ?? 30; Av()?.registerInput( actionSets ); } public get currentInteractionProfile(): string { return this.state?.interactionProfile; } public get isStateValid(): boolean { return this.state != undefined && this.state != null; } /** Used by tests to force a state update */ public TEST_UpdateState( newState: InputState ) { this.applyNewState( JSON.parse( JSON.stringify( newState ) ) as InputState ); } /** * Activates an action set on the next action sync. if a list of devices is * not supplied the action set is activated for all devices. If a single string * is provided, that device is added to the existing list. If a list of devices * is provided, the list replaces the existing list. */ public activateActionSet( actionSetName: string, devices?: Device | Device[]) { let activeSet: ActiveActionSet; for( let as of this.inputInfo.activeActionSets ) { if( as.actionSetName == actionSetName ) { activeSet = as; break; } } let somethingAdded = false; if( !activeSet ) { activeSet = { actionSetName, topLevelPaths: [], }; this.inputInfo.activeActionSets.push( activeSet ); } let newDevices: Device[]; if( typeof devices == "string" ) { newDevices = [ devices ]; } else if( typeof devices == "object" ) { newDevices = devices; } else { newDevices = [ Device.Left, Device.Right ]; } for( let newDevice of newDevices ) { if( !activeSet.topLevelPaths.includes( newDevice ) ) { activeSet.topLevelPaths.push( newDevice ); this.suppressInitialPressForActionSet( actionSetName, newDevice ); somethingAdded = true; } } if( !this.inputTimer && this.inputIntervalMs && somethingAdded ) { this.inputTimer = window.setTimeout( () => this.onInputTick(), this.inputIntervalMs ); } } private suppressInitialPressForActionSet( actionSetName: string, device: Device ) { let actionSet: ActionSet; for( let as of this.actionSets ) { if( as.name == actionSetName ) { actionSet = as; break; } } if( !actionSet ) { return; } for( let actionBase of actionSet.actions ?? [] ) { let action = actionBase as ActionWithListeners; if( action.type == ActionType.Boolean ) { switch( device ) { case Device.Left: action.suppressLeft = true; break; case Device.Right: action.suppressRight = true; break; } } } } /** * Deactivates an action set on the next action sync. If a device list * is not supplied, the action set is deactivated for all devices. */ public deactivateActionSet( actionSetName: string, device?: Device) { for( let i = 0; i < this.inputInfo.activeActionSets.length; i++ ) { let as = this.inputInfo.activeActionSets[i]; if( as.actionSetName == actionSetName ) { if( !device ) { // remove for all devices this.inputInfo.activeActionSets.splice( i, 1 ); } else { as.topLevelPaths = as.topLevelPaths.filter( ( dev: Device ) => dev != device ); if( as.topLevelPaths.length == 0 ) { this.inputInfo.activeActionSets.splice( i, 1 ); } } return; } } // if we didn't find the action set in our list there's nothing to remove } /** Registers boolean callbacks for an action and device */ public registerBooleanCallbacks( actionSetName: string, actionName: string, device: Device, rising: () => void, falling?: ()=> void ) { let cb: BooleanCallback = { id: this.nextCallbackId++, rising, falling, }; return this.registerCallback( actionSetName, actionName, device, cb ); } /** Registers float callbacks for an action and device */ public registerFloatCallback( actionSetName: string, actionName: string, device: Device, change: ( oldValue: number, newValue: number ) => void ) { let cb: FloatCallback = { id: this.nextCallbackId++, change, }; return this.registerCallback( actionSetName, actionName, device, cb ); } /** Registers float callbacks for an action and device */ public registerVector2Callback( actionSetName: string, actionName: string, device: Device, change: ( oldValue: [ number, number ], newValue: [ number, number ] ) => void ) { let cb: Vector2Callback = { id: this.nextCallbackId++, change, }; return this.registerCallback( actionSetName, actionName, device, cb ); } private registerCallback( actionSetName: string, actionName: string, device: Device, cb: BooleanCallback | FloatCallback | Vector2Callback ) { let action = this.getAction( actionSetName, actionName ); if( !action ) { throw new Error( `Unknown action ${ actionName } in action set ${ actionSetName }` ); } switch( device ) { case Device.Left: action.leftCallbacks = [ ...( action.leftCallbacks ?? [] ), cb ]; break; case Device.Right: action.rightCallbacks = [ ...( action.rightCallbacks ?? [] ), cb ]; break; } return cb.id; } public registerInteractionProfileCallback( cb: ( oldInteractionProfile: string, newInteractionProfile: string ) => void ) { let cbid = this.nextCallbackId++; this.interactionProfileCallbacks.push( { id: cbid, change: cb, } ); return cbid; } /** Unregisters a callback by id */ public unregisterCallback( id: number ) { for( let actionSet of this.actionSets ) { for( let baseAction of actionSet.actions ?? [] ) { let action = baseAction as ActionWithListeners; action.leftCallbacks = action.leftCallbacks?.filter( ( cb ) => cb.id != id ); action.rightCallbacks = action.rightCallbacks?.filter( ( cb ) => cb.id != id ); } } this.interactionProfileCallbacks = this.interactionProfileCallbacks?.filter( ( cb ) => cb.id != id ); } private onInputTick() { try { let state = this.syncInputOverride ? this.syncInputOverride( this.inputInfo ) :Av().syncInput( this.inputInfo ); this.applyNewState( state ); } catch( e ) { console.log( "failed to sync input" ); } if( this.inputInfo.activeActionSets.length > 0 && this.inputIntervalMs) { this.inputTimer = window.setTimeout( () => this.onInputTick(), this.inputIntervalMs ); } else { this.inputTimer = undefined; } } private getAction( actionSetName: string, actionName: string ): ActionWithListeners | undefined { for( let actionSet of this.actionSets ) { if( actionSet.name != actionSetName ) continue; for( let action of actionSet.actions ?? [] ) { if( action.name == actionName ) { return action; } } } return undefined; } private applyNewState( newState: InputState ) { this.processDiffs( this.state, newState ); let oldInteractionProfile = this.state?.interactionProfile; let newInteractionProfile = newState?.interactionProfile; this.state = newState; if( oldInteractionProfile != newInteractionProfile ) { console.log( `Interaction profile has changed from ${ oldInteractionProfile } to ` + `${ newInteractionProfile }` ); for( let cb of this.interactionProfileCallbacks ) { cb.change( oldInteractionProfile, newInteractionProfile ); } } } private callCallback( cb: BooleanCallback | FloatCallback | Vector2Callback, oldValue: boolean | number | [ number, number ], newValue: boolean | number | [ number, number ], type: ActionType ) { switch( type ) { case ActionType.Boolean: { let bcb = cb as BooleanCallback; if( oldValue && !newValue ) { bcb.falling?.(); } else if( !oldValue && newValue ) { bcb.rising?.(); } } break; case ActionType.Float: { let fcb = cb as FloatCallback; let oldFloat = typeof oldValue == "number" ? oldValue as number : 0; let newFloat = typeof newValue == "number" ? newValue as number : 0; if( oldFloat != newFloat ) { fcb.change( oldFloat, newFloat ); } } break; case ActionType.Vector2: { const [ ox, oy ] = oldValue as [ number, number ] ?? [ 0, 0 ]; const [ nx, ny ] = newValue as [ number, number ] ?? [ 0, 0 ]; let vcb = cb as Vector2Callback; if( ox != nx || oy != ny ) { vcb.change( [ ox, oy ], [ nx, ny ] ); } } break; } } private processDiffs( old: InputState, newState: InputState ) { for( let actionSet of this.actionSets ) { for( let baseAction of actionSet.actions ?? [] ) { let action = baseAction as ActionWithListeners; let oldAction = old?.results[ actionSet.name ]?.[ action.name ]; let newAction = newState.results[ actionSet.name ]?.[ action.name ]; let oldLeft = oldAction?.left?.value; let oldRight = oldAction?.right?.value; let newLeft = newAction?.left?.value; let newRight = newAction?.right?.value; if( action.suppressLeft ) { if( !newLeft ) { action.suppressLeft = false; } } else { for( let cb of action.leftCallbacks ?? [] ) { this.callCallback( cb, oldLeft, newLeft, action.type ); } } if( action.suppressRight ) { if( !newRight ) { action.suppressRight = false; } } else { for( let cb of action.rightCallbacks ?? [] ) { this.callCallback( cb, oldRight, newRight, action.type ); } } } } } } /** Helper to create the same binding on multiple devices */ export function multiDeviceBinding( interactionProfile: InteractionProfile, devicePaths: Device[], componentPath: Input ) :ActionBinding[] { return devicePaths.map( (value: string) => { return { interactionProfile, inputPath: value + componentPath, }; } ); } /** Helper to create the same binding on both hands */ export function twoHandBinding( interactionProfile: InteractionProfile, componentPath: Input ) { return multiDeviceBinding(interactionProfile, [ Device.Left, Device.Right ], componentPath ); }
the_stack
import * as vscode from 'vscode'; import * as chai from 'chai'; import * as sinon from 'sinon'; import * as path from 'path'; import * as fs from 'fs-extra'; import * as os from 'os'; import { ExtensionCommands } from '../../ExtensionCommands'; import { LogType, FabricGatewayRegistryEntry, FabricGatewayRegistry, ConnectionProfileUtil, FabricWalletRegistryEntry, FabricWalletGeneratorFactory, FabricEnvironmentRegistryEntry, EnvironmentType, FabricEnvironmentRegistry, FabricEnvironment, FabricNode } from 'ibm-blockchain-platform-common'; import { FabricGatewayConnection } from 'ibm-blockchain-platform-gateway-v1'; import { VSCodeBlockchainOutputAdapter } from '../../extension/logging/VSCodeBlockchainOutputAdapter'; import { ExtensionUtil } from '../../extension/util/ExtensionUtil'; import { TestUtil } from '../TestUtil'; import { FabricGatewayConnectionManager } from '../../extension/fabric/FabricGatewayConnectionManager'; import { BlockchainTreeItem } from '../../extension/explorer/model/BlockchainTreeItem'; import { BlockchainGatewayExplorerProvider } from '../../extension/explorer/gatewayExplorer'; import { ChannelTreeItem } from '../../extension/explorer/model/ChannelTreeItem'; import { InstantiatedTreeItem } from '../../extension/explorer/model/InstantiatedTreeItem'; import { UserInputUtil } from '../../extension/commands/UserInputUtil'; import { InstantiatedContractTreeItem } from '../../extension/explorer/model/InstantiatedContractTreeItem'; import sinonChai = require('sinon-chai'); import { Reporter } from '../../extension/util/Reporter'; import { FabricWallet } from 'ibm-blockchain-platform-wallet'; import { InstantiatedAssociatedTreeItem } from '../../extension/explorer/model/InstantiatedAssociatedTreeItem'; import { InstantiatedAssociatedContractTreeItem } from '../../extension/explorer/model/InstantiatedAssociatedContractTreeItem'; import { ContractTreeItem } from '../../extension/explorer/model/ContractTreeItem'; import { EnvironmentFactory } from '../../extension/fabric/environments/EnvironmentFactory'; chai.use(sinonChai); // tslint:disable: no-unused-expression describe('exportAppData', () => { let mySandBox: sinon.SinonSandbox; const fakeTargetPath: string = path.join('/', 'a', 'fake', 'path'); let logSpy: sinon.SinonSpy; let fabricClientConnectionMock: sinon.SinonStubbedInstance<FabricGatewayConnection>; let executeCommandStub: sinon.SinonStub; let getConnectionStub: sinon.SinonStub; let connectionProfile: any; let readProfileStub: sinon.SinonStub; let showInstantiatedSmartContractsQuickPickStub: sinon.SinonStub; let allChildren: Array<BlockchainTreeItem>; let blockchainGatewayExplorerProvider: BlockchainGatewayExplorerProvider; let fabricConnectionManager: FabricGatewayConnectionManager; let instantiatedSmartContract: InstantiatedContractTreeItem; let gatewayRegistryEntry: FabricGatewayRegistryEntry; let environmentRegistryEntry: FabricEnvironmentRegistryEntry; let getGatewayRegistryStub: sinon.SinonStub; let peerNode: FabricNode; let caNode: FabricNode; let ordererNode: FabricNode; let mockRuntime: sinon.SinonStubbedInstance<FabricEnvironment>; let channels: Array<ChannelTreeItem>; let contracts: Array<InstantiatedTreeItem>; let writeFileStub: sinon.SinonStub; let showSaveDialogStub: sinon.SinonStub; let homeDirStub: sinon.SinonStub; let sendTelemetryEventStub: sinon.SinonStub; let workspaceFolderStub: sinon.SinonStub; let workspaceFolder: any; let showQuickPickItemStub: sinon.SinonStub; let showIdentitiesQuickPickStub: sinon.SinonStub; let walletRegistryEntry: FabricWalletRegistryEntry; let exportedData: string; let moreFakeMetadata: any; before(async () => { mySandBox = sinon.createSandbox(); await TestUtil.setupTests(mySandBox); }); beforeEach(async () => { logSpy = mySandBox.spy(VSCodeBlockchainOutputAdapter.instance(), 'log'); executeCommandStub = mySandBox.stub(vscode.commands, 'executeCommand'); executeCommandStub.withArgs(ExtensionCommands.CONNECT_TO_GATEWAY).resolves(); executeCommandStub.callThrough(); fabricClientConnectionMock = mySandBox.createStubInstance(FabricGatewayConnection); fabricClientConnectionMock.connect.resolves(); const map: Map<string, Array<string>> = new Map<string, Array<string>>(); map.set('myChannel', ['peerOne']); fabricClientConnectionMock.createChannelMap.resolves(map); fabricClientConnectionMock.getChannelCapabilityFromPeer.resolves([UserInputUtil.V2_0]); fabricConnectionManager = FabricGatewayConnectionManager.instance(); getConnectionStub = mySandBox.stub(FabricGatewayConnectionManager.instance(), 'getConnection').returns(fabricClientConnectionMock); gatewayRegistryEntry = new FabricGatewayRegistryEntry({ name: 'myGateway', associatedWallet: '', transactionDataDirectories: [{ chaincodeName: 'myContract', channelName: 'myChannel', transactionDataPath: 'some/file/path' }], connectionProfilePath: 'myPath/connection.json' }); mockRuntime = mySandBox.createStubInstance(FabricEnvironment); getGatewayRegistryStub = mySandBox.stub(fabricConnectionManager, 'getGatewayRegistryEntry'); getGatewayRegistryStub.resolves(gatewayRegistryEntry); await FabricGatewayRegistry.instance().clear(); await FabricGatewayRegistry.instance().add(gatewayRegistryEntry); fabricClientConnectionMock.getInstantiatedChaincode.resolves([ { name: 'myContract', version: '0.0.1', } ]); moreFakeMetadata = { contracts: { myContract: { name: 'myContract', transactions: [ { name: 'aLovelyTransaction', parameters: [ { name: 'value', schema: { type: 'string' } }, ] }, ] }, myOtherContract: { name: 'myOtherContract', transactions: [ { name: 'aHappyTransaction', parameters: [ { name: 'value', schema: { type: 'string' } } ] }, ] } } }; blockchainGatewayExplorerProvider = ExtensionUtil.getBlockchainGatewayExplorerProvider(); allChildren = await blockchainGatewayExplorerProvider.getChildren(); channels = await blockchainGatewayExplorerProvider.getChildren(allChildren[2]) as Array<ChannelTreeItem>; contracts = await blockchainGatewayExplorerProvider.getChildren(channels[0]) as Array<InstantiatedTreeItem>; instantiatedSmartContract = contracts[0]; showInstantiatedSmartContractsQuickPickStub = mySandBox.stub(UserInputUtil, 'showClientInstantiatedSmartContractsQuickPick').withArgs(sinon.match.any).resolves({ label: 'myContract@0.0.1', data: { name: 'myContract', channel: 'myChannel', version: '0.0.1' } }); workspaceFolder = { name: 'myFolder', uri: vscode.Uri.file('myPath') }; workspaceFolderStub = mySandBox.stub(UserInputUtil, 'getWorkspaceFolders').returns([workspaceFolder]); writeFileStub = mySandBox.stub(fs, 'writeFile'); showSaveDialogStub = mySandBox.stub(vscode.window, 'showSaveDialog').resolves(vscode.Uri.file(fakeTargetPath)); homeDirStub = mySandBox.stub(os, 'homedir'); homeDirStub.returns('homedir'); readProfileStub = mySandBox.stub(ConnectionProfileUtil, 'readConnectionProfile'); connectionProfile = { name: 'myProfile', wallet: 'myWallet' }; readProfileStub.resolves(connectionProfile); sendTelemetryEventStub = mySandBox.stub(Reporter.instance(), 'sendTelemetryEvent'); showQuickPickItemStub = mySandBox.stub(UserInputUtil, 'showQuickPickItem').resolves([{ label: UserInputUtil.GENERATE_ENVIRONMENT_PROFILE, data: UserInputUtil.GENERATE_ENVIRONMENT_PROFILE, description: UserInputUtil.GENERATE_ENVIRONMENT_PROFILE_DESCRIPTION }]); environmentRegistryEntry = new FabricEnvironmentRegistryEntry(); environmentRegistryEntry.name = 'myEnv'; environmentRegistryEntry.environmentType = EnvironmentType.ENVIRONMENT; await FabricEnvironmentRegistry.instance().add(environmentRegistryEntry); peerNode = FabricNode.newPeer('peerNode', 'Org1Peer1', 'http://localhost:17051', undefined, undefined, 'Org1MSP'); peerNode.container_name = 'randomText_containerName'; caNode = FabricNode.newCertificateAuthority('caNodeWithoutCreds', 'Org1CA', 'http://localhost:17054', 'ca.org1.example.com', undefined, undefined, undefined, undefined, undefined); caNode.container_name = 'randomText_anotherContainerName'; ordererNode = FabricNode.newOrderer('ordererNode', 'orderer.example.com', 'http://localhost:17056', undefined, undefined, 'osmsp', undefined); mockRuntime.getNodes.returns([ordererNode, peerNode, caNode]); mySandBox.stub(EnvironmentFactory, 'getEnvironment').returns(mockRuntime); // walletStubs const testFabricWallet: FabricWallet = await FabricWallet.newFabricWallet(path.join(__dirname, '../../tmp/v2/wallets/testWallet')); walletRegistryEntry = new FabricWalletRegistryEntry(); walletRegistryEntry.name = 'myWallet'; walletRegistryEntry.walletPath = 'walletPath'; mySandBox.stub(fabricConnectionManager, 'getConnectionWallet').returns(walletRegistryEntry); mySandBox.stub(FabricWalletGeneratorFactory.getFabricWalletGenerator(), 'getWallet').resolves(testFabricWallet); mySandBox.stub(fabricConnectionManager, 'getConnectionIdentity').returns('someIdentity'); mySandBox.stub(FabricWallet.prototype, 'getIDs').resolves([ { name: 'someIdentity', msp_id: 'someMSP', cert: 'base64CertificateHere', private_key: 'base64PrivKeyHere' }, { name: 'someOtherIdentity', msp_id: 'someOtherMSP', cert: 'anotherbase64CertificateHere', private_key: 'anotherbase64PrivKeyHere' } ]); mySandBox.stub(FabricWallet.prototype, 'getIdentityNames').resolves(['someIdentity', 'someOtherIdentity', 'anotherRandomIdentity']); showIdentitiesQuickPickStub = mySandBox.stub(UserInputUtil, 'showIdentitiesQuickPickBox').resolves(['someIdentity', 'someOtherIdentity']); exportedData = `FABRIC_CONNECTION_PROFILE={"name":"myProfile"}\nFABRIC_WALLET_CREDENTIALS=[{"name":"someIdentity","msp_id":"someMSP","cert":"base64CertificateHere","private_key":"base64PrivKeyHere"},{"name":"someOtherIdentity","msp_id":"someOtherMSP","cert":"anotherbase64CertificateHere","private_key":"anotherbase64PrivKeyHere"}]\nFABRIC_DEFAULT_IDENTITY=someIdentity\nFABRIC_CHANNEL=myChannel\nFABRIC_CONTRACT=myContract`; }); afterEach(async () => { mySandBox.restore(); await FabricEnvironmentRegistry.instance().clear(); }); it('should export application data through command pallete', async () => { await vscode.commands.executeCommand(ExtensionCommands.EXPORT_APP_DATA); logSpy.getCall(0).should.have.been.calledWithExactly(LogType.INFO, undefined, `exportAppData`); writeFileStub.should.have.been.calledWithExactly(fakeTargetPath, exportedData); logSpy.getCall(1).should.have.been.calledWithExactly(LogType.SUCCESS, `Successfully exported application data to ${fakeTargetPath}`); sendTelemetryEventStub.should.have.been.calledOnceWithExactly('exportAppDataCommand'); }); it('should export application data through command pallete when not connected to gateway', async () => { getConnectionStub.onCall(3).returns(undefined); await vscode.commands.executeCommand(ExtensionCommands.EXPORT_APP_DATA); logSpy.getCall(0).should.have.been.calledWithExactly(LogType.INFO, undefined, `exportAppData`); writeFileStub.should.have.been.calledWithExactly(fakeTargetPath, exportedData); logSpy.getCall(1).should.have.been.calledWithExactly(LogType.SUCCESS, `Successfully exported application data to ${fakeTargetPath}`); sendTelemetryEventStub.should.have.been.calledOnceWithExactly('exportAppDataCommand'); }); it('should handle unsuccessful attempt when to connecting to a gateway', async () => { getConnectionStub.returns(undefined); await vscode.commands.executeCommand(ExtensionCommands.EXPORT_APP_DATA); logSpy.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, `exportAppData`); writeFileStub.should.not.have.been.called; sendTelemetryEventStub.should.not.have.been.called; }); it('should handle cancellation when choosing an instantiated contract', async () => { showInstantiatedSmartContractsQuickPickStub.resolves(undefined); await vscode.commands.executeCommand(ExtensionCommands.EXPORT_APP_DATA); logSpy.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, `exportAppData`); writeFileStub.should.not.have.been.called; sendTelemetryEventStub.should.not.have.been.called; }); it('should export application data through the tree', async () => { await vscode.commands.executeCommand(ExtensionCommands.EXPORT_APP_DATA, instantiatedSmartContract); logSpy.getCall(0).should.have.been.calledWithExactly(LogType.INFO, undefined, `exportAppData`); writeFileStub.should.have.been.calledWithExactly(fakeTargetPath, exportedData); logSpy.getCall(1).should.have.been.calledWithExactly(LogType.SUCCESS, `Successfully exported application data to ${fakeTargetPath}`); sendTelemetryEventStub.should.have.been.calledOnceWithExactly('exportAppDataCommand'); }); it('should export application data for a ContractTreeItem', async () => { fabricClientConnectionMock.getMetadata.resolves(moreFakeMetadata); allChildren = await blockchainGatewayExplorerProvider.getChildren(); const channelChildren: Array<ChannelTreeItem> = await blockchainGatewayExplorerProvider.getChildren(allChildren[2]) as Array<ChannelTreeItem>; channelChildren[0].tooltip.should.equal(`Associated peers: peerOne\nChannel capabilities: ${UserInputUtil.V2_0}`); const instantiatedAssociatedChainCodes: Array<InstantiatedAssociatedTreeItem> = await blockchainGatewayExplorerProvider.getChildren(channelChildren[0]) as Array<InstantiatedAssociatedTreeItem>; await blockchainGatewayExplorerProvider.getChildren(instantiatedAssociatedChainCodes[0]); const instantiatedTreeItems: Array<InstantiatedAssociatedContractTreeItem> = await blockchainGatewayExplorerProvider.getChildren(channelChildren[0]) as Array<InstantiatedAssociatedContractTreeItem>; const contractTreeItems: Array<ContractTreeItem> = await blockchainGatewayExplorerProvider.getChildren(instantiatedTreeItems[0]) as Array<ContractTreeItem>; await vscode.commands.executeCommand(ExtensionCommands.EXPORT_APP_DATA, contractTreeItems[0]); logSpy.getCall(0).should.have.been.calledWithExactly(LogType.INFO, undefined, `exportAppData`); writeFileStub.should.have.been.calledWithExactly(fakeTargetPath, exportedData); logSpy.getCall(1).should.have.been.calledWithExactly(LogType.SUCCESS, `Successfully exported application data to ${fakeTargetPath}`); sendTelemetryEventStub.should.have.been.calledOnceWithExactly('exportAppDataCommand'); }); it('should handle cancellation when choosing type of app assets to generate', async () => { showQuickPickItemStub.resolves(undefined); await vscode.commands.executeCommand(ExtensionCommands.EXPORT_APP_DATA); logSpy.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, `exportAppData`); writeFileStub.should.not.have.been.called; sendTelemetryEventStub.should.not.have.been.called; }); it('should handle cancellation when choosing identities', async () => { showIdentitiesQuickPickStub.resolves(undefined); await vscode.commands.executeCommand(ExtensionCommands.EXPORT_APP_DATA); logSpy.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, `exportAppData`); showSaveDialogStub.should.not.have.been.called; writeFileStub.should.not.have.been.called; sendTelemetryEventStub.should.not.have.been.called; }); it('should handle user selecting the "Ok" button without choosing type of app asset', async () => { showQuickPickItemStub.resolves([]); await vscode.commands.executeCommand(ExtensionCommands.EXPORT_APP_DATA); logSpy.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, `exportAppData`); writeFileStub.should.not.have.been.called; sendTelemetryEventStub.should.not.have.been.called; }); it('should handle user selecting the "Ok" button without choosing any identities', async () => { const error: Error = new Error('No identities were selected.'); showIdentitiesQuickPickStub.resolves([]); await vscode.commands.executeCommand(ExtensionCommands.EXPORT_APP_DATA); logSpy.getCall(0).should.have.been.calledWith(LogType.INFO, undefined, `exportAppData`); logSpy.getCall(1).should.have.been.calledWithExactly(LogType.ERROR, `Error exporting application data: ${error.message}`, `Error exporting application data: ${error.toString()}`); showSaveDialogStub.should.not.have.been.called; writeFileStub.should.not.have.been.called; sendTelemetryEventStub.should.not.have.been.called; }); it('should throw error if connection profile has localhost in url and unsupported gateway', async () => { const anotherConnectionProfile: any = { certificateAuthorities: { Org1CA: { caName: 'ca', url: 'http://localhost:1245' } }, peers: { Org1Peer1: { url: 'grpc://localhost:4416' } }, wallet: 'myWallet' }; readProfileStub.resolves(anotherConnectionProfile); const error: Error = new Error('Gateway not supported'); await vscode.commands.executeCommand(ExtensionCommands.EXPORT_APP_DATA); logSpy.getCall(0).should.have.been.calledWith(LogType.INFO, undefined, `exportAppData`); logSpy.getCall(1).should.have.been.calledWithExactly(LogType.ERROR, `Error exporting application data: ${error.message}`, `Error exporting application data: ${error.toString()}`); showSaveDialogStub.should.not.have.been.called; writeFileStub.should.not.have.been.called; sendTelemetryEventStub.should.not.have.been.called; }); it('should replace all instances of localhost from url with the correct container names', async () => { const anotherConnectionProfile: any = { certificateAuthorities: { Org1CA: { caName: 'ca', url: 'http://localhost:4415' } }, peers: { Org1Peer1: { url: 'grpc://localhost:2316' } }, wallet: 'myWallet' }; readProfileStub.resolves(anotherConnectionProfile); const anotherGatewayRegistryEntry: FabricGatewayRegistryEntry = new FabricGatewayRegistryEntry({ name: 'myGateway', associatedWallet: '', transactionDataDirectories: [{ chaincodeName: 'myContract', channelName: 'myChannel', transactionDataPath: 'some/file/path' }], connectionProfilePath: 'myPath/connection.json', fromEnvironment: 'myEnv' }); getGatewayRegistryStub.resolves(anotherGatewayRegistryEntry); const dataToExport: string = `FABRIC_CONNECTION_PROFILE={"certificateAuthorities":{"Org1CA":{"caName":"ca","url":"http://anotherContainerName:4415"}},"peers":{"Org1Peer1":{"url":"grpc://containerName:2316"}}}\nFABRIC_WALLET_CREDENTIALS=[{"name":"someIdentity","msp_id":"someMSP","cert":"base64CertificateHere","private_key":"base64PrivKeyHere"},{"name":"someOtherIdentity","msp_id":"someOtherMSP","cert":"anotherbase64CertificateHere","private_key":"anotherbase64PrivKeyHere"}]\nFABRIC_DEFAULT_IDENTITY=someIdentity\nFABRIC_CHANNEL=myChannel\nFABRIC_CONTRACT=myContract`; await vscode.commands.executeCommand(ExtensionCommands.EXPORT_APP_DATA); writeFileStub.should.have.been.calledWithExactly(fakeTargetPath, dataToExport); }); it('should handle cancellation when choosing where to save the exported file', async () => { workspaceFolderStub.resolves([]); showSaveDialogStub.resolves(undefined); await vscode.commands.executeCommand(ExtensionCommands.EXPORT_APP_DATA); logSpy.should.have.been.calledOnceWithExactly(LogType.INFO, undefined, `exportAppData`); writeFileStub.should.not.have.been.called; sendTelemetryEventStub.should.not.have.been.called; }); it('should show error message if error exporting the data', async () => { const error: Error = new Error('someError'); writeFileStub.throws(error); await vscode.commands.executeCommand(ExtensionCommands.EXPORT_APP_DATA); logSpy.getCall(0).should.have.been.calledWithExactly(LogType.INFO, undefined, `exportAppData`); logSpy.getCall(1).should.have.been.calledWithExactly(LogType.ERROR, `Error exporting application data: ${error.message}`, `Error exporting application data: ${error.toString()}`); sendTelemetryEventStub.should.not.have.been.called; }); });
the_stack
import 'reflect-metadata' import { GLOBAL_KEY_SYMBOL, EffectModule, ImmerReducer, Module, Effect, Reducer, RETRY_KEY_SYMBOL } from '@sigi/core' import { Injectable, Injector } from '@sigi/di' import { emitSSREffects, match } from '@sigi/ssr' import { Action } from '@sigi/types' import { Draft } from 'immer' import { useEffect } from 'react' import { renderToString } from 'react-dom/server' import { create, act } from 'react-test-renderer' import { Observable, of, timer } from 'rxjs' import { endWith, switchMap, map, mergeMap, withLatestFrom } from 'rxjs/operators' import { SSRContext, useModule } from '../index.browser' interface CountState { count: number name: string } interface TipState { tip: string } @Injectable() class Service { getName() { return of('client service') } } @Module('ServiceModule') class ServiceModule extends EffectModule<CountState> { readonly defaultState = { count: 0, name: '' } constructor(public readonly service: Service) { super() } @ImmerReducer() setName(state: Draft<CountState>, name: string) { state.name = name } @Effect({ ssr: true, }) setNameEffect(payload$: Observable<void>): Observable<Action> { return payload$.pipe( switchMap(() => this.service.getName().pipe( map((name) => this.getActions().setName(name)), endWith(this.terminate()), ), ), ) } @Effect({ payloadGetter: (ctx: { failure: boolean }, skip) => { if (!ctx.failure) { return skip } return 1 }, }) setNameWithFailure(payload$: Observable<number | undefined>): Observable<Action> { return payload$.pipe( mergeMap((p) => { if (p) { return of(this.retryOnClient().setNameWithFailure(), this.terminate()) } return of(this.getActions().setName('From retry')) }), ) } } @Module('CountModel') class CountModel extends EffectModule<CountState> { defaultState = { count: 0, name: '' } @ImmerReducer() setCount(state: Draft<CountState>, count: number) { state.count = count } @ImmerReducer() setName(state: Draft<CountState>, name: string) { state.name = name } @Effect({ ssr: true, }) getCount(payload$: Observable<void>): Observable<Action> { return payload$.pipe( mergeMap(() => timer(20).pipe( map(() => this.getActions().setCount(1)), endWith(this.terminate()), ), ), ) } @Effect({ payloadGetter: (ctx: { url: string }, skip) => ctx.url || skip, skipFirstClientDispatch: false, }) skippedEffect(payload$: Observable<string>): Observable<Action> { return payload$.pipe( switchMap((name) => timer(20).pipe( map(() => this.getActions().setName(name)), endWith(this.terminate()), ), ), ) } } interface InfinityWaitModelState { count: number } @Module('InfinityWaitModel') class InfinityWaitModel extends EffectModule<InfinityWaitModelState> { defaultState = { count: 0 } @ImmerReducer() setCount(state: Draft<InfinityWaitModelState>, count: number) { state.count = count } @Effect({ ssr: true, }) infinityWait(payload$: Observable<void>): Observable<Action> { return payload$.pipe(map(() => this.getActions().setCount(1))) } } @Module('TipModel') class TipModel extends EffectModule<TipState> { defaultState = { tip: '' } @ImmerReducer() setTip(state: Draft<TipState>, tip: string) { state.tip = tip } @Effect({ ssr: true }) getTip(payload$: Observable<void>): Observable<Action> { return payload$.pipe( mergeMap(() => timer(1).pipe( map(() => this.getActions().setTip('tip')), endWith(this.terminate()), ), ), ) } } const Component = () => { const [state, actions] = useModule(CountModel) useEffect(() => { actions.setName('new name') }, [actions]) return ( <> <span>{state.count}</span> </> ) } const ComponentWithSelector = () => { const [state, actions] = useModule(CountModel, { selector: (s) => ({ count: s.count + 1, }), dependencies: [], }) useEffect(() => { actions.setName('new name') }, [actions]) return ( <> <span>{state.count}</span> </> ) } const MODULES = [CountModel, TipModel, ServiceModule, Service] describe('SSR specs:', () => { it('should throw if module name not given', () => { function generateException() { // @ts-expect-error @Module() class ErrorModel extends EffectModule<any> { defaultState = {} } return ErrorModel } expect(generateException).toThrow() }) it('should pass valid module name', () => { @Module('1') class Model extends EffectModule<any> { defaultState = {} } @Module('2') class Model2 extends EffectModule<any> { defaultState = {} } function generateException1() { @Module('1') class ErrorModel1 extends EffectModule<any> { defaultState = {} } return ErrorModel1 } function generateException2() { @Module('1') class ErrorModel2 extends EffectModule<any> { defaultState = {} } return { ErrorModel2 } } // eslint-disable-next-line sonarjs/no-identical-functions function generateException3() { // @ts-expect-error @Module() class ErrorModel extends EffectModule<any> { defaultState = {} } return ErrorModel } expect(Model).not.toBe(undefined) expect(Model2).not.toBe(undefined) expect(generateException1).toThrow() expect(generateException2).toThrow() expect(generateException3).toThrow() }) it('should run ssr effects', async () => { const state = await emitSSREffects({ url: 'name' } as any, [CountModel], { providers: MODULES, }).pendingState const moduleState = state['dataToPersist']['CountModel'] expect(moduleState).not.toBe(undefined) expect(moduleState.count).toBe(1) expect(moduleState.name).toBe('name') expect(state['dataToPersist']).toMatchSnapshot() }) it('should skip effect if it returns SKIP_SYMBOL', async () => { const state = await emitSSREffects({}, [CountModel], { providers: MODULES, }).pendingState const moduleState = state['dataToPersist']['CountModel'] expect(moduleState.name).toBe('') expect(state['dataToPersist']).toMatchSnapshot() }) it('should return right state in hooks', async () => { const req = {} const { pendingState, injector } = emitSSREffects(req, [CountModel], { providers: MODULES, }) await pendingState const html = renderToString( <SSRContext value={injector}> <Component /> </SSRContext>, ) expect(html).toContain('<span>1</span>') expect(html).toMatchSnapshot() }) it('should restore state from global', () => { global[GLOBAL_KEY_SYMBOL] = { CountModel: { count: 101, name: '', }, } const testRenderer = create(<Component />) act(() => { testRenderer.update(<Component />) }) expect(testRenderer.root.findByType('span').children[0]).toBe('101') delete global[GLOBAL_KEY_SYMBOL] testRenderer.unmount() }) it('should restore state from global #with selector', () => { global[GLOBAL_KEY_SYMBOL] = { CountModel: { count: 10, name: '', }, } const testRenderer = create( <SSRContext value={new Injector().addProviders(MODULES)}> <ComponentWithSelector /> </SSRContext>, ) expect(testRenderer.root.findByType('span').children[0]).toBe('11') delete global[GLOBAL_KEY_SYMBOL] testRenderer.unmount() }) it('should not restore state from global if state is null', () => { global[GLOBAL_KEY_SYMBOL] = { OtherModule: { count: 10, name: '', }, } const injector = new Injector().addProviders(MODULES) const testRenderer = create( <SSRContext value={injector}> <ComponentWithSelector /> </SSRContext>, ) act(() => { testRenderer.update( <SSRContext value={injector}> <ComponentWithSelector /> </SSRContext>, ) }) expect(testRenderer.root.findByType('span').children[0]).toBe('1') delete global[GLOBAL_KEY_SYMBOL] testRenderer.unmount() }) it('should restore and skip first action on client side', () => { const Component = () => { const [state, actions] = useModule(CountModel) useEffect(() => { actions.getCount() }, [actions]) return ( <> <span>{state.count}</span> </> ) } global[GLOBAL_KEY_SYMBOL] = { CountModel: { count: 2, name: '', }, } const injector = new Injector().addProviders(MODULES) const testRenderer = create( <SSRContext value={injector}> <Component /> </SSRContext>, ) act(() => { testRenderer.update( <SSRContext value={injector}> <Component /> </SSRContext>, ) }) expect(testRenderer.root.findByType('span').children[0]).toBe('2') delete global[GLOBAL_KEY_SYMBOL] testRenderer.unmount() }) it('should retry action if needed on client side', () => { const Component = () => { const [state, dispatcher] = useModule(ServiceModule) useEffect(() => { dispatcher.setNameWithFailure(void 0) }, [dispatcher]) return ( <> <span>{state.name}</span> </> ) } global[RETRY_KEY_SYMBOL] = { ServiceModule: ['setNameWithFailure'], } const injector = new Injector().addProviders(MODULES) const testRenderer = create( <SSRContext value={injector}> <Component /> </SSRContext>, ) // eslint-disable-next-line sonarjs/no-identical-functions act(() => { testRenderer.update( <SSRContext value={injector}> <Component /> </SSRContext>, ) }) expect(testRenderer.root.findByType('span').children[0]).toBe('From retry') delete global[GLOBAL_KEY_SYMBOL] testRenderer.unmount() }) it('should timeout', async () => { const req = {} return emitSSREffects(req, [CountModel], { providers: MODULES, timeout: 0 }).pendingState.catch((e: Error) => { expect(e.message).toBe('Terminate timeout') }) }) // Do not use `Sinon.fakeTimers` here // It would cause `UnhandledPromiseRejection` it('should timeout #2', async () => { const req = {} const { pendingState } = emitSSREffects(req, [InfinityWaitModel, TipModel], { timeout: 2 / 1000, }) await pendingState.catch((e) => { expect(e.message).toBe('Terminate timeout') }) }) it('should resolve empty object if no modules provided', async () => { const req = {} const state = await emitSSREffects(req, [], { providers: MODULES }).pendingState expect(state['dataToPersist']).toStrictEqual({}) }) it('should do nothing if Module contains no SSREffects', async () => { const req = {} @Module('WithoutSSR') class WithoutSSRModule extends EffectModule<{ count: number }> { defaultState = { count: 0, } @ImmerReducer() set(state: Draft<{ count: number }>, payload: number) { state.count = payload } @Effect() addOne(payload$: Observable<void>): Observable<Action> { return payload$.pipe( withLatestFrom(this.state$), map(([, { count }]) => this.getActions().set(count + 1)), ) } } const state = await emitSSREffects(req, [WithoutSSRModule], { providers: MODULES }).pendingState expect(state['dataToPersist']).toStrictEqual({}) }) it('should throw error if runEffects error', async () => { const req = {} const error = new TypeError('whatever') @Module('ErrorModule') class SSRErrorModule extends EffectModule<{ count: number }> { defaultState = { count: 0, } @Effect({ ssr: true }) addOne(payload$: Observable<void>): Observable<Action> { return payload$.pipe( withLatestFrom(this.state$), map(() => { throw error }), ) } } try { await emitSSREffects(req, [SSRErrorModule], { providers: MODULES }).pendingState throw new TypeError('Unreachable code path') } catch (e) { expect(e).toBe(error) } }) it('should throw error if reducer throw', async () => { const req = {} const error = new TypeError('whatever') @Module('ErrorReducerModule') class SSRErrorModule extends EffectModule<{ count: number }> { defaultState = { count: 0, } @Reducer() set() { throw error } @Effect({ ssr: true }) addOne(payload$: Observable<void>): Observable<Action> { return payload$.pipe( withLatestFrom(this.state$), map(() => this.getActions().set()), ) } } try { await emitSSREffects(req, [SSRErrorModule], { providers: MODULES }).pendingState throw new TypeError('Unreachable code path') } catch (e) { expect(e).toBe(error) } }) it('should throw error if payloadGetter throw', async () => { const req = {} const error = new TypeError('whatever') @Module('ErrorMiddlewareModule') class SSRErrorModule extends EffectModule<{ count: number }> { defaultState = { count: 0, } @Reducer() set(state: { count: number }, payload: number) { return { ...state, count: payload } } @Effect({ payloadGetter: () => { throw error }, }) addOne(payload$: Observable<void>): Observable<Action> { return payload$.pipe( withLatestFrom(this.state$), map(([, state]) => this.getActions().set(state.count + 1)), ) } } try { await emitSSREffects(req, [SSRErrorModule], { providers: MODULES }).pendingState throw new TypeError('Unreachable code path') } catch (e) { expect(e).toBe(error) } }) it('should replace injector if providers provided', async () => { const req = {} const state = await emitSSREffects(req, [ServiceModule], { providers: MODULES }).pendingState expect(state['dataToPersist'].ServiceModule.name).toBe('client service') const state2 = await emitSSREffects(req, [ServiceModule], { providers: [...MODULES, { provide: Service, useValue: { getName: () => of('server service') } }], }).pendingState expect(state2['dataToPersist'].ServiceModule.name).toBe('server service') }) it('should persist states which mutated by the other modules', async () => { @Module('InnerStateModule') class StateModel extends EffectModule<{ count: number }> { defaultState = { count: 0 } @ImmerReducer() setCount(state: Draft<{ count: number }>, count: number) { state.count = count } } @Module('InnerCountModel') // eslint-disable-next-line @typescript-eslint/ban-types class CountModel extends EffectModule<{}> { defaultState = {} constructor(private readonly stateModule: StateModel) { super() } @Effect({ ssr: true, }) getCount(payload$: Observable<void>): Observable<Action> { return payload$.pipe( mergeMap(() => timer(20).pipe( map(() => this.stateModule.getActions().setCount(1)), endWith(this.terminate()), ), ), ) } } const req = {} const state = await emitSSREffects(req, [CountModel, StateModel]).pendingState expect(state['dataToPersist']).toEqual({ InnerCountModel: {}, InnerStateModule: { count: 1, }, }) }) it('should persist actions to retry if needed', async () => { const req = { failure: true } const state = await emitSSREffects(req, [ServiceModule], { providers: MODULES }).pendingState expect(state['actionsToRetry']).toEqual({ ServiceModule: ['setNameWithFailure'] }) }) it('should be able to persist actions to retry on the other module, and the skipped actions', async () => { @Module('InnerServiceModule') // eslint-disable-next-line @typescript-eslint/ban-types class InnerServiceModule extends EffectModule<CountState> { readonly defaultState = { count: 0, name: '' } constructor(public readonly service: Service) { super() } @ImmerReducer() setName(state: Draft<CountState>, name: string) { state.name = name } @Effect() setNameWithFailure(payload$: Observable<number | undefined>): Observable<Action> { return payload$.pipe(mergeMap(() => of(this.retryOnClient().setNameWithFailure(), this.terminate()))) } } @Module('InnerCountModel2') // eslint-disable-next-line @typescript-eslint/ban-types class InnerCountModule2 extends EffectModule<{}> { defaultState = {} constructor(private readonly serviceModule: InnerServiceModule) { super() } @Effect({ ssr: true, }) setName(payload$: Observable<void>): Observable<Action> { return payload$.pipe(mergeMap(() => of(this.serviceModule.getActions().setNameWithFailure(1)))) } @Effect({ payloadGetter(_: any, skipAction) { return skipAction }, }) skippedSetName(payload$: Observable<void>): Observable<Action> { return payload$.pipe(map(() => this.serviceModule.getActions().setName('skipped'))) } } const req = {} const state = await emitSSREffects(req, [InnerServiceModule, InnerCountModule2], { providers: MODULES }) .pendingState expect(state['actionsToRetry']).toEqual({ InnerCountModel2: ['skippedSetName'], InnerServiceModule: ['setNameWithFailure'], }) }) it('should support match fn', async () => { @Module('InnerServiceModule2') class InnerServiceModule2 extends EffectModule<CountState> { readonly defaultState = { count: 0, name: '' } @ImmerReducer() setName(state: Draft<CountState>, name: string) { state.name = name } @Effect({ payloadGetter: match( ['/users/:id'], (ctx: any) => ctx.request.path, )((ctx) => { return ctx.request.path.length }), }) setNameWithFailure(payload$: Observable<number>): Observable<Action> { return payload$.pipe(mergeMap((l) => of(this.getActions().setName(`length: ${l}`), this.terminate()))) } } const req = { request: { path: '/users/linus', }, } const state = await emitSSREffects(req, [InnerServiceModule2], { providers: [InnerServiceModule2] }).pendingState expect(state['dataToPersist']).toEqual({ InnerServiceModule2: { count: 0, name: `length: ${req.request.path.length}`, }, }) }) })
the_stack
import {HttpClient} from "@angular/common/http"; import {Component, EventEmitter, Inject, Input, OnDestroy, OnInit, Output} from "@angular/core"; import {FormControl, FormGroup, Validators} from "@angular/forms"; import {TdDialogService} from "@covalent/core/dialogs"; import {Observable, ObservableInput} from "rxjs/Observable"; import {debounceTime} from "rxjs/operators/debounceTime"; import {switchMap} from "rxjs/operators/switchMap"; import {Subscription} from "rxjs/Subscription"; import {CloneUtil} from "../../../common/utils/clone-util"; import {StateService} from "../../../services/StateService"; import {UserDatasource} from "../../model/user-datasource"; import {VisualQuerySaveService} from "../services/save.service"; import {SaveRequest, SaveResponseStatus} from "../wrangler/api/rest-model"; import {QueryEngine} from "../wrangler/query-engine"; import {SaveOptionsComponent} from "./save-options.component"; import {DatasourcesService, JdbcDatasource, TableReference} from '../../services/DatasourcesServiceIntrefaces'; import {DataSource} from "../../catalog/api/models/datasource"; import {CatalogService} from "../../catalog/api/services/catalog.service"; import * as _ from "underscore"; export enum SaveMode { INITIAL, SAVING, SAVED} @Component({ selector: "thinkbig-visual-query-store", styleUrls: ["./store.component.scss"], templateUrl: "./store.component.html" }) export class VisualQueryStoreComponent implements OnDestroy, OnInit { /** * Query engine */ @Input() engine: QueryEngine<any>; /** * Transformation model */ @Input() model: any; /** * Connected to 'Back' button */ @Output() back = new EventEmitter<void>(); /** * Indicates if there is an error connecting to the data source */ connectionError: boolean; /** * Target destination type. Either DOWNLOAD or TABLE. */ destination: string; /** * Identifier for download */ downloadId: string; /** * Url to download results */ downloadUrl: string; /** * Error message */ error: string; /** * Spark data source names */ downloadFormats: string[]; /** * Spark table source names */ tableFormats: string[]; /** * Indicates if the properties are valid. */ isValid: boolean; /** * List of Kylo data sources */ kyloDataSources: UserDatasource[] = []; /** * Indicates the page is loading */ loading = true; /** * Additional options for the output format. */ properties: any[] = []; propertiesForm = new FormGroup({}); /** * Subscription to notification removal */ removeSubscription: Subscription; /** * Subscription to save response */ saveSubscription: Subscription; saveMode: SaveMode = SaveMode.INITIAL; tableNameControl = new FormControl(null, [Validators.required, Validators.minLength(1)]); tableNameList: Observable<TableReference[]>; catalogSQLDataSources: DataSource[] = []; /** * Output configuration */ target: SaveRequest = {}; constructor(private $http: HttpClient, @Inject("DatasourcesService") private DatasourcesService: DatasourcesService, @Inject("RestUrlService") private RestUrlService: any, private VisualQuerySaveService: VisualQuerySaveService, private $mdDialog: TdDialogService, @Inject("StateService") private stateService: StateService, private catalogService:CatalogService) { // Listen for notification removals this.removeSubscription = this.VisualQuerySaveService.subscribeRemove((event) => { if (event.id === this.downloadId) { this.downloadId = null; this.downloadUrl = null; } }); // Listen for table name changes this.tableNameControl.valueChanges.subscribe(text => this.target.tableName = text); this.tableNameList = this.tableNameControl.valueChanges.pipe( debounceTime(100), switchMap(text => this.findTables(text)) ); }; /** * Release resources when component is destroyed. */ ngOnDestroy(): void { if (this.removeSubscription) { this.removeSubscription.unsubscribe(); } if (this.saveSubscription) { this.saveSubscription.unsubscribe(); } } /** * Initialize resources when component is initialized. */ ngOnInit(): void { // Get list of Kylo data sources this.target.jdbc; this.target.catalogDatasource = new DataSource(); const kyloSourcesPromise = Promise.all([this.engine.getNativeDataSources(), this.DatasourcesService.findAll()]) .then(resultList => { this.kyloDataSources = resultList[0].concat(resultList[1]); if (this.model.$selectedDatasourceId) { let jdbcSource = this.kyloDataSources.find(datasource => datasource.id === this.model.$selectedDatasourceId) if(jdbcSource != undefined) { this.target.jdbc = (jdbcSource as JdbcDatasource); } } }); const catalogDataSourceObservable = this.catalogService.getDataSourcesForPluginIds(["hive","jdbc"]); const catalogDataSourcePromise = catalogDataSourceObservable.toPromise(); catalogDataSourceObservable.subscribe(datasources => { if(datasources && datasources.length >0){ this.catalogSQLDataSources = _(datasources).chain().sortBy( (ds:DataSource) =>{ return ds.title; }).sortBy((ds:DataSource) =>{ return ds.connector.pluginId; }).value() } else { this.catalogSQLDataSources = []; } }); // Get list of Spark data sources const sparkSourcesPromise = this.$http.get<string[]>(this.RestUrlService.SPARK_SHELL_SERVICE_URL + "/data-sources").toPromise() .then(response => { this.downloadFormats = response["downloads"].sort(); this.tableFormats = response["tables"].sort(); }); // Wait for completion Promise.all([kyloSourcesPromise, sparkSourcesPromise,catalogDataSourcePromise]) .then(() => this.loading = false, () => this.error = "Invalid response from server."); this.destination = "DOWNLOAD"; } /** * Downloads the saved results. */ download(): void { window.open(this.downloadUrl, "_blank"); // Clear download buttons this.VisualQuerySaveService.removeNotification(this.downloadId); this.downloadId = null; this.downloadUrl = null; } /** * Find tables matching the specified name. */ findTables(name: any): ObservableInput<TableReference[]> { if (this.target.jdbc) { const tables = this.engine.searchTableNames(name, this.target.jdbc.id); if (tables instanceof Promise) { return tables.then(response => { this.connectionError = false; return response; }, () => { this.connectionError = true; return []; }); } else { this.connectionError = false; return Observable.of(tables); } } else if(this.target.catalogDatasource){ return this.catalogService.listTables(this.target.catalogDatasource.id,name) } else { return Observable.of([]) } } /** * Should the Results card be shown, or the one showing the Download options * @return {boolean} */ showSaveResultsCard(): boolean { return this.saveMode == SaveMode.SAVING || this.saveMode == SaveMode.SAVED; } /** * Is a save for a file download in progress * @return {boolean} */ isSavingFile(): boolean { return this.saveMode == SaveMode.SAVING && this.destination === "DOWNLOAD"; } /** * is a save for a table export in progress * @return {boolean} */ isSavingTable(): boolean { return this.saveMode == SaveMode.SAVING && this.destination === "TABLE"; } /** * is a save for a table export complete * @return {boolean} */ isSavedTable(): boolean { return this.saveMode == SaveMode.SAVED && this.destination === "TABLE"; } /** * have we successfully saved either to a file or table * @return {boolean} */ isSaved(): boolean { return this.saveMode == SaveMode.SAVED; } /** * Navigate back from the saved results card and show the download options */ downloadAgainAs(): void { this._reset(); } /** * Navigate back and take the user from the Save/store screen to the Transform table screen */ modifyTransformation(): void { this._reset(); this.back.emit(null); } /** * Reset download options * @private */ _reset(): void { this.saveMode = SaveMode.INITIAL; this.downloadUrl = null; this.error = null; this.loading = false; this.propertiesForm = new FormGroup({}); } /** * Exit the Visual Query and go to the Feeds list */ exit(): void { this.stateService.navigateToHome(); } /** * Reset options when format changes. */ onFormatChange(): void { this.target.options = {}; } /** * Show options info dialog for different data formats for download. */ showOptionsInfo(): void { this.$mdDialog.open(SaveOptionsComponent, {panelClass: "full-screen-dialog"}); }; /** * Saves the results. */ save(): void { this.saveMode = SaveMode.SAVING; // Remove current subscription if (this.saveSubscription) { this.saveSubscription.unsubscribe(); this.saveSubscription = null; } // Build request let request: SaveRequest; if (this.destination === "DOWNLOAD") { request = { format: this.target.format, options: this.getOptions() }; } else { request = CloneUtil.deepCopy(this.target); request.options = this.getOptions(); } // Save transformation this.downloadUrl = null; this.error = null; this.loading = true; this.saveSubscription = this.VisualQuerySaveService.save(request, this.engine) .subscribe(response => { this.loading = false; if (response.status === SaveResponseStatus.SUCCESS && this.destination === "DOWNLOAD") { this.downloadId = response.id; this.downloadUrl = response.location; //reset the save mode if its Saving if (this.saveMode == SaveMode.SAVING) { this.saveMode = SaveMode.SAVED; } } }, response => { this.error = response.message; this.loading = false; this.saveMode = SaveMode.INITIAL; }, () => this.loading = false); } trackDataSource(index: number, dataSource: UserDatasource) { return dataSource.id; } /** * Gets the target output options by parsing the properties object. */ private getOptions(): { [k: string]: string } { if(this.target.options) { let options = CloneUtil.deepCopy(this.target.options); this.properties.forEach(property => options[property.systemName] = property.value); return options; } else { return {}; } } }
the_stack
import { getSnapshot } from 'mobx-keystone' import { RootInstance } from '../type' // import { mapToArrary } from '../util' import { initStyle } from './item/style' const getLength = (length: number) => { return length >= 20 ? length : 20 } export const createData = (root: RootInstance) => { //alert('createData') const t0 = +new Date() const { style, colors } = initStyle({ primaryColor: root.Ui.themeColor }) const res = [...root.Models.values()] .filter( a => !root.sys.dagreLayout || (root.sys.dagreLayout && a.aggregateModelKey) ) .map(m => { return { id: 'model-' + m.id, type: 'console-model-Node', isKeySharp: root.graph.zoom <= 0.4, visible: !!root.sys.checkedKeys.find(a => a === m.id), selected: m.id === root.sys.currentModel, showNameOrLabel: root.sys.showNameOrLabel, config: { width: 300, headerHeight: 48, fieldHeight: 32, labelSize: 14, styleConfig: style, colors }, data: { moduleKey: m.moduleId, label: m.label, fields: m.fields.map(a => ({ // ...getSnapshot(a) , // relationModel: getSnapshot(a.relationModel) ...a, relationModel: a.relationModel })), key: m.id, name: m.name, tag: 'aggregate', aggregateRoot: m.aggregateRoot, aggregateModelKey: m.aggregateModelKey, belongAggregate: m.belongAggregate, nodeSize: (((48 + getLength(m.fields.length) * 48) / 6) * 6) / 6 }, themeColor: colors.blue, darkness: root.Ui.darkness, size: ((48 + getLength(m.fields.length) * 48) / 6) * 6 } }) .filter(a => a.visible) //const t1 = +new Date() // console.log(res) //alert(res.length + ' ' + (t1 - t0)) if (res.length > 0) return res.concat([createSysNode() as any]) return res } const createSysNode = () => { return { id: 'model-SYS-CENTER-POINT', type: 'circle', isSys: true, visible: true, isKeySharp: true, size: 10, style: { opacity: 0 } } } const Relation = { ToOne: '1:1', ToMany: '1:n', lookup: '查找', toOne: '1:1', toMany: '1:n', Lookup: '查找' } export const createLinks = (root: RootInstance) => { const { style } = initStyle({ primaryColor: root.Ui.themeColor }) const links = [...root.Models.values()].reduce((pre, model) => { if (!root.sys.checkedKeys.find(a => a === model.id)) return pre const sysLink = { key: 'model-' + model.id + '~' + 'model-SYS-CENTER-POINT', source: 'model-' + model.id, // target: 'model-' + relationModel!.id, // visible: false, isSys: true, // style: { // visible: false, // }, target: 'model-SYS-CENTER-POINT', type: 'console-line', style: { opacity: 0 } } const fieldLinks = model.fields.reduce((fPre, field, i) => { const tempfPre = fPre // const { id } = field if (Array.isArray(field.typeMeta)) { const arr = field.typeMeta.forEach((element: any) => { const isRelation = element.type === 'Relation' && element?.relationModel if (isRelation) { if ( root.sys.onIgnoreEdge && root.sys.onIgnoreEdge(field) ) return fPre const relationModel = root.findModelByName( element!.relationModel ) if ( !relationModel || !root.sys.checkedKeys.find( a => a === relationModel!.id ) ) return fPre const isTo = true const l = model.fields.length const sourceAnchor = !isTo ? i + 2 : 2 + i + l const targetTable = [...root.Models.values()].find( pre => pre.id === relationModel!.id ) let targetTableFieldIndex = targetTable?.fields.findIndex( item => item.name === element.field ) + 2 const relationEdge = { key: 'model-' + model.id + '~' + 'model-' + relationModel!.id, source: 'model-' + model.id, target: 'model-' + relationModel!.id, sourceAnchor, targetAnchor: targetTableFieldIndex, fieldIndex: i, tooltip: `<div>从 <span class='text'>${relationModel?.label }</span> 到 <span class='text'>${model?.label}=> ${element.field }</span> ${Relation[field.type] || field.type} 关系</div>`, fieldsLength: l, style: style.fieldRelation.edge, type: 'console-line', // label: field.type, labelAutoRotate: true, loopCfg: { // position: 'top', clockwise: true, // dist: 200, dist: 100 } } tempfPre.push(relationEdge) return tempfPre } else return tempfPre }) } else { const isRelation = field.typeMeta && field.typeMeta.type === 'Relation' && field.typeMeta?.relationModel if (isRelation) { if (root.sys.onIgnoreEdge && root.sys.onIgnoreEdge(field)) return fPre //if(field?.typeMeta?.relationModel === 'base_User' && (confirmEnding(field.name, 'createdBy') || confirmEnding(field.name,'updatedBy') ) ) return fPre const relationModel = root.findModelByName( field.typeMeta!.relationModel ) if ( !relationModel || !root.sys.checkedKeys.find(a => a === relationModel!.id) ) return fPre const isTo = true const l = model.fields.length const sourceAnchor = !isTo ? i + 2 : 2 + i + l return [ ...fPre, { key: 'model-' + model.id + '~' + 'model-' + relationModel!.id, source: 'model-' + model.id, target: 'model-' + relationModel!.id, sourceAnchor, // // targetAnchor: sourceAnchor, targetAnchor: model.id === relationModel.id ? sourceAnchor - 1 : undefined, fieldIndex: i, tooltip: `<div>从 <span class='text'>${relationModel?.label }</span> 到 <span class='text'>${model?.label }</span> ${Relation[field.type] || field.type} 关系</div>`, fieldsLength: l, style: style.default.edge, type: 'console-line', label: Relation[field.type] || field.type, labelAutoRotate: true, loopCfg: { // position: 'top', clockwise: true, // dist: 200, dist: 100 }, labelCfg: { style: { stroke: '#fff', lineWidth: 30 } }, } ] } } return fPre }, []) return [...pre, ...fieldLinks, sysLink] }, []) return links.filter(a => !!a) } // export const getNodes = (models, styleConfig) => { // // const _key = stateConfig.model_keys.key // const nodeRes = models // .map((model, i) => { // return { // id: 'model-' + model.key, // hide: checkedKeys.indexOf('model-' + model.key) === -1, // // groupId: `module-${model.moduleKey}`, // config: { // width: 300, // headerHeight: 48, // fieldHeight: 32, // labelSize: 14 , // hide: checkedKeys.indexOf('model-' + model.key) === -1, // styleConfig, // }, // data: { // moduleKey: `module-${model.moduleKey}`, // label: showLable(model), // fields: fields(model, models), // key: model.key, // name: model.name || model.key, // tag: 'aggregate', // aggregateRoot: model.aggregateRoot, // aggregateModelKey: model.aggregateModelKey, // belongAggregate: model.belongAggregate, // nodeSize: ((48 + getLength(model.fields.length) * 48) / 6) * // 6 / 6, // }, // type: 'console-model-Node', // isKeySharp: true, // size: ((48 + getLength(model.fields.length) * 48) / 6) * // 6 , // } // }) // return nodeRes.length > 0 ? nodeRes.concat([createSysNode()]) : nodeRes // // }) // }
the_stack